Merge
authorasaha
Fri, 10 Apr 2009 13:05:12 -0700
changeset 2676 e22d7be9f23a
parent 2418 15096652c4d4 (diff)
parent 2675 91fc59916eb4 (current diff)
child 2677 cd181222973b
Merge
--- a/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 0c4657194eec95c08ba478aee9cfc3c295e41657 jdk7-b47
 1bf51a4c2627c2f0e0cbcc2cf0421bdb37f1f2b2 jdk7-b48
 6b84b04a80afe23262377c60913eebfc898f14c4 jdk7-b49
+5da0e6b9f4f18ef483c977337214b12ee0e1fc8f jdk7-b50
+a25c5ec5e40e07733d1ff9898a0abe36159288ff jdk7-b51
+7a90e89e36d103038f8667f6a7daae34ecfa1ad8 jdk7-b52
+d52186ee770dac57950536cd00ccbfdef360b04c jdk7-b53
--- a/.hgtags-top-repo	Mon Mar 09 15:32:10 2009 -0700
+++ b/.hgtags-top-repo	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 d7744e86dedc21a8ecf6bdb73eb191b8eaf5b0da jdk7-b47
 4ae9f4bfdb98f65bd957e3fe72471b320150b38e jdk7-b48
 aee93a8992d2389121eb610c00a86196f3e2b9b0 jdk7-b49
+5111e13e44e542fe945b47ab154546daec36737d jdk7-b50
+0f0189d55ce4a1f7840da7582ac7d970b3b7ab15 jdk7-b51
+4264c2fe66493e57c411045a1b61377796641e45 jdk7-b52
+c235f4a8559d196879c56af80159f67ee5d0e720 jdk7-b53
--- a/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 167ad0164301f318b069a947e1c9c07ed667748a jdk7-b47
 0be222241fd405e48915647facfaa176621b39b9 jdk7-b48
 d70978bc64bc7a04be7797ab0dcd9b7b1b3a6bff jdk7-b49
+0edbd0074b02b42b2b83cc47cb391d4869b7a8ec jdk7-b50
+3eb8f1047a7402a9a79937d1c39560e931e91da2 jdk7-b51
+bec82237d694f9802b820fa11bbb4f7fa9bf8e77 jdk7-b52
+3c4d73194f6f89f040ae3b2d257335dfa8a1b2b5 jdk7-b53
--- a/corba/make/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -112,8 +112,6 @@
   TARGET_JAVA = java
 endif
 
-NO_PROPRIETARY_API_WARNINGS = -XDignore.symbol.file=true
-
 SELF = $(lastword $(MAKEFILE_LIST))
 
 # for jdk, we generate the following:
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_dynamicany.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_dynamicany.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_encoding.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_encoding.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_ior.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_ior.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_orbutil.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_orbutil.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_protocol.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_impl_protocol.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_legacy_interceptor.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_legacy_interceptor.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_monitoring.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_monitoring.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_presentation_rmi.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_presentation_rmi.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_transport.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/com_sun_corba_se_spi_transport.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/org_omg_CosNaming.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/org_omg_CosNaming.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/org_omg_DynamicAny.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/org_omg_DynamicAny.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/minclude/org_omg_PortableInterceptor.jmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/minclude/org_omg_PortableInterceptor.jmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/com/sun/corba/se/sources/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/com/sun/corba/se/sources/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -46,8 +46,6 @@
 include $(CORBA_JMK_DIRECTORY)com_sun_corba_se_PortableActivationIDL.jmk
 include $(CORBA_JMK_DIRECTORY)com_sun_corba_se_impl_logging.jmk
 
-FILES_java += com/sun/corba/se/org/omg/CORBA/ORB.java
-
 #
 # Dirs
 #
@@ -80,11 +78,11 @@
 POA.MC          = $(SRC_DIR)/com/sun/corba/se/spi/logging/data/POA.mc
 UTIL.MC         = $(SRC_DIR)/com/sun/corba/se/spi/logging/data/Util.mc
 
-MC_GENERATE_CLASS = $(SRC_DIR)/com/sun/tools/corba/se/logutil/scripts/mc.scm -main main make-class
-MC_GENERATE_LOG_RB = $(SRC_DIR)/com/sun/tools/corba/se/logutil/scripts/mc.scm -main main make-resource 
+MC_GENERATE_CLASS = make-class
+MC_GENERATE_LOG_RB = make-resource 
 
-JSCHEME_GENERATE_CLASS = $(BOOT_JAVA_CMD) jscheme.REPL $(MC_GENERATE_CLASS) 
-JSCHEME_GENERATE_LOG_RB = $(BOOT_JAVA_CMD) jscheme.REPL $(MC_GENERATE_LOG_RB) 
+JSCHEME_GENERATE_CLASS = $(BOOT_JAVA_CMD) com.sun.tools.corba.se.logutil.MC $(MC_GENERATE_CLASS) 
+JSCHEME_GENERATE_LOG_RB = $(BOOT_JAVA_CMD) com.sun.tools.corba.se.logutil.MC $(MC_GENERATE_LOG_RB) 
 
 
 #
--- a/corba/make/common/Defs-windows.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/Defs-windows.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/common/Rules.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/Rules.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -191,14 +191,18 @@
 # Make sure all newer sources are compiled (in a batch)
 classes : $(CLASSES_INIT) .delete.classlist .compile.classlist
 
+# Use this javac option to force it to favor the sourcepath file classes
+#   rather than any bootclasspath classes.
+JAVAC_PREFER_SOURCE = -Xprefer:source
+
 .compile.classlist : $(JAVA_SOURCE_LIST)
 	@$(MKDIR) -p $(CLASSDESTDIR)
 	@if [ `$(CAT) $(JAVA_SOURCE_LIST) | $(WC) -l` -ge 1 ] ; then \
 	  $(ECHO) "# Java sources to be compiled: (listed in file $(JAVA_SOURCE_LIST))"; \
 	  $(CAT) $(JAVA_SOURCE_LIST); \
 	  $(ECHO) "# Running javac:"; \
-	  $(ECHO) $(JAVAC_CMD) -sourcepath "$(SOURCEPATH)" -d $(CLASSDESTDIR) @$(JAVA_SOURCE_LIST); \
-	  $(JAVAC_CMD) -sourcepath "$(SOURCEPATH)" -d $(CLASSDESTDIR) @$(JAVA_SOURCE_LIST); \
+	  $(ECHO) $(JAVAC_CMD) $(JAVAC_PREFER_SOURCE) -sourcepath "$(SOURCEPATH)" -d $(CLASSDESTDIR) @$(JAVA_SOURCE_LIST); \
+	  $(JAVAC_CMD) $(JAVAC_PREFER_SOURCE) -sourcepath "$(SOURCEPATH)" -d $(CLASSDESTDIR) @$(JAVA_SOURCE_LIST); \
 	fi
 	@$(java-vm-cleanup)
 
--- a/corba/make/common/shared/Compiler-msvc.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Compiler-msvc.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -128,9 +128,19 @@
         endif
       endif
     endif
-    # This will cause problems if ALT_COMPILER_PATH is defined to ""
-    # which is a directive to use the PATH.
-    REBASE         = $(COMPILER_PATH)../REBASE
+    ifeq ($(CC_MAJORVER), 15)
+      # This should be: CC_VER=15.00.21022.8 LINK_VER=9.00.21022.8
+      REQUIRED_CC_VER = 15.00.21022.8
+      REQUIRED_LINK_VER = 9.00.21022.8
+      COMPILER_NAME=Windows SDK 6.1 Visual Studio 9
+      COMPILER_VERSION=VS2008
+      RC = $(MSSDK61)/bin/x64/rc
+      REBASE = $(MSSDK61/bin/x64/rebase
+    else
+      # This will cause problems if ALT_COMPILER_PATH is defined to ""
+      # which is a directive to use the PATH.
+      REBASE         = $(COMPILER_PATH)../REBASE
+    endif
     ifndef COMPILER_PATH
       COMPILER_PATH := $(error COMPILER_PATH cannot be empty here)
     endif
--- a/corba/make/common/shared/Compiler-sun.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Compiler-sun.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/common/shared/Defs-java.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Defs-java.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -104,6 +104,9 @@
   JAVACFLAGS  += -Werror
 endif
 
+NO_PROPRIETARY_API_WARNINGS = -XDignore.symbol.file=true
+JAVACFLAGS  += $(NO_PROPRIETARY_API_WARNINGS)
+
 # Add the source level (currently all source is 1.5, should this be 1.6?)
 LANGUAGE_VERSION = -source 1.5
 JAVACFLAGS  += $(LANGUAGE_VERSION)
@@ -117,7 +120,7 @@
 JAVACFLAGS  += $(OTHER_JAVACFLAGS)
 
 # Needed for javah
-JAVAHFLAGS += -bootclasspath $(CLASSBINDIR)
+JAVAHFLAGS += -classpath $(CLASSBINDIR)
 
 # Langtools
 ifdef LANGTOOLS_DIST
--- a/corba/make/common/shared/Defs-utils.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Defs-utils.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/common/shared/Defs-windows.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Defs-windows.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -282,13 +282,27 @@
 
 # Compilers for 64bit are from SDK
 ifeq ($(ARCH_DATA_MODEL), 64)
-  ifneq ($(_ms_sdk),)
+  xMSSDK61 :="C:/Program Files/Microsoft SDKs/Windows/v6.1/"
+  MSSDK61 :=$(call FullPath,$(xMSSDK61))
+  xVS2008 :="C:/Program Files (x86)/Microsoft Visual Studio 9.0/"
+  _vs2008 :=$(call FullPath,$(xVS2008))
+  ifneq ($(_vs2008),)
     ifeq ($(ARCH), ia64)
-      _compiler_bin :=$(_ms_sdk)/Bin/Win64
+      _compiler_bin :=$(_vs2008)/VC/Bin/x86_ia64
     endif
     ifeq ($(ARCH), amd64)
-      _compiler_bin :=$(_ms_sdk)/Bin/Win64/x86/$(ARCH)
-      _redist_sdk   :=$(_ms_sdk)/redist/win64/AMD64
+      _compiler_bin :=$(_vs2008)/VC/Bin/$(ARCH)
+      _redist_sdk   :=$(MSSDK61)/VC/redist
+    endif
+  else
+    ifneq ($(_ms_sdk),)
+      ifeq ($(ARCH), ia64)
+        _compiler_bin :=$(_ms_sdk)/Bin/Win64
+      endif
+      ifeq ($(ARCH), amd64)
+        _compiler_bin :=$(_ms_sdk)/Bin/Win64/x86/$(ARCH)
+        _redist_sdk   :=$(_ms_sdk)/redist/win64/AMD64
+      endif
     endif
   endif
 endif
--- a/corba/make/common/shared/Defs.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/common/shared/Defs.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/javax/xa/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/javax/xa/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/jprt.config	Fri Apr 10 13:05:12 2009 -0700
@@ -1,7 +1,7 @@
 #!echo "This is not a shell script"
 #############################################################################
 #
-# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/org/omg/CORBA/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/org/omg/CORBA/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/corba/make/sun/rmi/corbalogsources/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/sun/rmi/corbalogsources/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -75,15 +75,14 @@
 POA.MC          = $(SRC_DIR)/com/sun/corba/se/spi/logging/data/POA.mc
 UTIL.MC         = $(SRC_DIR)/com/sun/corba/se/spi/logging/data/Util.mc
 
-MC_GENERATE_CLASS = $(SRC_DIR)/com/sun/tools/corba/se/logutil/scripts/mc.scm -main main make-class
-MC_GENERATE_LOG_RB = $(SRC_DIR)/com/sun/tools/corba/se/logutil/scripts/mc.scm -main main make-resource 
+MC_GENERATE_CLASS = make-class
+MC_GENERATE_LOG_RB = make-resource 
 
-JSCHEME_LIB_DIRECTORY=$(SRC_DIR)/com/sun/tools/corba/se/logutil/lib
-JSCHEME_CLASSPATH=$(JSCHEME_LIB_DIRECTORY)/jscheme.jar$(CLASSPATH_SEPARATOR)$(JSCHEME_LIB_DIRECTORY)/jschemelogutil.jar
-JSCHEME_GENERATE_CLASS = $(BOOT_JAVA_CMD) \
-    -cp "$(JSCHEME_CLASSPATH)" jscheme.REPL $(MC_GENERATE_CLASS) 
-JSCHEME_GENERATE_LOG_RB = $(BOOT_JAVA_CMD) \
-    -cp "$(JSCHEME_CLASSPATH)" jscheme.REPL $(MC_GENERATE_LOG_RB) 
+MC_CLASSPATH=$(BUILDTOOLJARDIR)/MC.jar
+MCJ_GENERATE_CLASS = $(BOOT_JAVA_CMD) \
+    -cp "$(MC_CLASSPATH)" com.sun.tools.corba.se.logutil.MC $(MC_GENERATE_CLASS) 
+MCJ_GENERATE_LOG_RB = $(BOOT_JAVA_CMD) \
+    -cp "$(MC_CLASSPATH)" com.sun.tools.corba.se.logutil.MC $(MC_GENERATE_LOG_RB) 
 
 
 #
@@ -104,28 +103,28 @@
 	$(MKDIR) -p $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/ActivationSystemException.java : $(ACTIVATION.MC)
-	$(JSCHEME_GENERATE_CLASS) $(ACTIVATION.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(ACTIVATION.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/IORSystemException.java : $(IOR.MC)
-	$(JSCHEME_GENERATE_CLASS) $(IOR.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(IOR.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/InterceptorsSystemException.java : $(INTERCEPTORS.MC)
-	$(JSCHEME_GENERATE_CLASS) $(INTERCEPTORS.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(INTERCEPTORS.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/NamingSystemException.java : $(NAMING.MC)
-	$(JSCHEME_GENERATE_CLASS) $(NAMING.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(NAMING.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/OMGSystemException.java : $(OMG.MC)
-	$(JSCHEME_GENERATE_CLASS) $(OMG.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(OMG.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/ORBUtilSystemException.java : $(ORBUTIL.MC)
-	$(JSCHEME_GENERATE_CLASS) $(ORBUTIL.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(ORBUTIL.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/POASystemException.java : $(POA.MC)
-	$(JSCHEME_GENERATE_CLASS) $(POA.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(POA.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/UtilSystemException.java : $(UTIL.MC)
-	$(JSCHEME_GENERATE_CLASS) $(UTIL.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_CLASS) $(UTIL.MC) $(LOG_GENDIRECTORY)
 
 logresource.generate: $(LOG_GENDIRECTORY)/LogStrings.properties
 
@@ -142,28 +141,28 @@
 	$(CAT) $(LOG_GENDIRECTORY)/*.resource > $(LOG_GENDIRECTORY)/LogStrings.properties
 
 $(LOG_GENDIRECTORY)/ActivationSystemException.resource : $(ACTIVATION.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(ACTIVATION.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(ACTIVATION.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/IORSystemException.resource : $(IOR.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(IOR.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(IOR.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/InterceptorsSystemException.resource : $(INTERCEPTORS.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(INTERCEPTORS.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(INTERCEPTORS.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/NamingSystemException.resource : $(NAMING.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(NAMING.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(NAMING.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/OMGSystemException.resource : $(OMG.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(OMG.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(OMG.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/ORBUtilSystemException.resource : $(ORBUTIL.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(ORBUTIL.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(ORBUTIL.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/POASystemException.resource : $(POA.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(POA.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(POA.MC) $(LOG_GENDIRECTORY)
 
 $(LOG_GENDIRECTORY)/UtilSystemException.resource : $(UTIL.MC)
-	$(JSCHEME_GENERATE_LOG_RB) $(UTIL.MC) $(LOG_GENDIRECTORY)
+	$(MCJ_GENERATE_LOG_RB) $(UTIL.MC) $(LOG_GENDIRECTORY)
 
 
 #
--- a/corba/make/tools/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/make/tools/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -33,6 +33,7 @@
 SUBDIRS =                   \
   strip_properties          \
   idlj                      \
+  logutil		    \
 
 all build clean clobber::
 	$(SUBDIRS-loop)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/corba/make/tools/logutil/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,43 @@
+#
+# Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Sun designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# Makefile for building the idlj tool
+#
+
+BUILDDIR = ../..
+PACKAGE = com.sun.tools.corba.se.logutil
+PRODUCT = tools
+PROGRAM = MC
+include $(BUILDDIR)/common/Defs.gmk
+
+BUILDTOOL_SOURCE_ROOT = $(SHARE_SRC)/classes
+BUILDTOOL_MAIN        = $(PKGDIR)/MC.java
+
+#
+# Build tool jar rules.
+#
+include $(BUILDDIR)/common/BuildToolJar.gmk
+
--- a/corba/src/share/classes/com/sun/tools/corba/se/logutil/IndentingPrintWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/src/share/classes/com/sun/tools/corba/se/logutil/IndentingPrintWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,6 @@
 import java.io.OutputStream ;
 import java.io.BufferedWriter ;
 import java.io.OutputStreamWriter ;
-import jsint.Pair ;
 import java.util.StringTokenizer ;
 
 public class IndentingPrintWriter extends PrintWriter {
@@ -38,22 +37,20 @@
     private int indentWidth = 4 ;
     private String indentString = "" ;
 
-    public void printMsg( String msg, Pair data )
+    public void printMsg( String msg, Object... data )
     {
         // System.out.println( "printMsg called with msg=" + msg + " data=" + data ) ;
         StringTokenizer st = new StringTokenizer( msg, "@", true ) ;
         StringBuffer result = new StringBuffer() ;
-        Object head = data.first ;
-        Pair tail = (Pair)data.rest ;
         String token = null ;
+        int pos = 0;
 
         while (st.hasMoreTokens()) {
             token = st.nextToken() ;
             if (token.equals("@")) {
-                if (head != null) {
-                    result.append( head ) ;
-                    head = tail.first ;
-                    tail = (Pair)tail.rest ;
+                if (pos < data.length) {
+                    result.append( data[pos] );
+                    ++pos;
                 } else {
                     throw new Error( "List too short for message" ) ;
                 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/corba/src/share/classes/com/sun/tools/corba/se/logutil/Input.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.tools.corba.se.logutil;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStreamReader;
+import java.io.IOException;
+
+import java.util.LinkedList;
+import java.util.Queue;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Input {
+
+  /**
+   * The name of the package this class will inhabit.
+   */
+  private String packageName;
+
+  /**
+   * The name of the generated class.
+   */
+  private String className;
+
+  /**
+   * The name of the group of exceptions handled by the class.
+   */
+  private String groupName;
+
+  /**
+   * The group of exceptions.
+   */
+  private Queue<InputException> exceptions;
+
+  /**
+   * Represents the current state of parsing the input.
+   */
+  private enum State
+  {
+    OUTER,
+    IN_CLASS,
+    IN_EXCEPTION_LIST
+  };
+
+  /**
+   * Regular expression to match each code line.
+   */
+  private static final Pattern EXCEPTION_INFO_REGEX =
+    Pattern.compile("(\\w+)\\s*(\\d+)\\s*(\\w+)");
+
+  /**
+   * Parses the specified file to create a new {@link Input}
+   * object.
+   *
+   * @param filename the file to parse.
+   * @throws FileNotFoundException if the file can't be found.
+   * @throws IOException if an I/O error occurs.
+   */
+  public Input(final String filename)
+  throws FileNotFoundException, IOException {
+    BufferedReader r =
+      new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
+    State state = State.OUTER;
+    InputException current = null;
+    exceptions = new LinkedList<InputException>();
+    String line;
+    while ((line = r.readLine()) != null) {
+      // Skip ; comments
+      if (line.startsWith(";"))
+        continue;
+
+      int index = line.indexOf("(");
+      if (index == -1)
+        continue;
+
+      switch (state) {
+      case OUTER:
+        state = State.IN_CLASS;
+        String[] classInfo = line.substring(index).split(" ");
+        packageName = classInfo[0].substring(2, classInfo[0].length() - 1);
+        className = classInfo[1].substring(1, classInfo[1].length() - 1);
+        groupName = classInfo[2];
+        break;
+      case IN_CLASS:
+        state = State.IN_EXCEPTION_LIST;
+        break;
+      case IN_EXCEPTION_LIST:
+        boolean inQuote = false;
+        boolean inCode = false;
+        boolean end = false;
+        int start = index + 1;
+        Queue<String> lines = new LinkedList<String>();
+        for (int a = start; a < line.length(); ++a) {
+          if (line.charAt(a) == '(' && !inCode && !inQuote) {
+            if (current == null)
+              current =
+                new InputException(line.substring(start, a).trim());
+            start = a + 1;
+            inCode = true;
+          }
+          if (line.charAt(a) == '"')
+            inQuote = !inQuote;
+          if (line.charAt(a) == ')' && !inQuote) {
+            if (inCode) {
+              lines.offer(line.substring(start, a));
+              inCode = false;
+            } else
+              end = true;
+          }
+          if (!end && a == line.length() - 1)
+            line += r.readLine();
+        }
+        for (String l : lines) {
+          int stringStart = l.indexOf("\"") + 1;
+          int stringEnd = l.indexOf("\"", stringStart);
+          Matcher matcher = EXCEPTION_INFO_REGEX.matcher(l.substring(0, stringStart));
+          if (matcher.find())
+            current.add(new InputCode(matcher.group(1),
+                                      Integer.parseInt(matcher.group(2)),
+                                      matcher.group(3),
+                                      l.substring(stringStart, stringEnd)));
+        }
+        exceptions.offer(current);
+        current = null;
+        break;
+      }
+    }
+  }
+
+  /**
+   * Returns the name of this group of exceptions.
+   *
+   * @return the name of this group of exceptions.
+   */
+  public String getGroupName()
+  {
+    return groupName;
+  }
+
+  /**
+   * Returns the name of the package this class will go in.
+   *
+   * @return the name of the package.
+   */
+  public String getPackageName()
+  {
+    return packageName;
+  }
+
+  /**
+   * Returns the name of the generated class.
+   *
+   * @return the name of the class.
+   */
+  public String getClassName()
+  {
+    return className;
+  }
+
+  /**
+   * Returns the exceptions contained in this class.
+   *
+   * @return the exceptions.
+   */
+  public Queue<InputException> getExceptions() {
+    return exceptions;
+  }
+
+  /**
+   * Returns a textual representation of this input.
+   *
+   * @return a textual representation.
+   */
+  public String toString() {
+    return getClass().getName() +
+      "[packageName=" + packageName +
+      ",className=" + className +
+      ",groupName=" + groupName +
+      ",exceptions=" + exceptions +
+      "]";
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/corba/src/share/classes/com/sun/tools/corba/se/logutil/InputCode.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package com.sun.tools.corba.se.logutil;
+
+public class InputCode {
+
+  /**
+   * The name of this code.
+   */
+  private final String name;
+
+  /**
+   * The code.
+   */
+  private final int code;
+
+  /**
+   * The log level for this code.
+   */
+  private final String logLevel;
+
+  /**
+   * The error message for this code.
+   */
+  private final String message;
+
+  /**
+   * Creates a new error code with the specified name, code,
+   * log level and error message.
+   *
+   * @param name the name of the new code.
+   * @param code the code itself.
+   * @param logLevel the level of severity of this error.
+   * @param message the error message for this code.
+   */
+  public InputCode(final String name, final int code,
+                   final String logLevel, final String message) {
+    this.name = name;
+    this.code = code;
+    this.logLevel = logLevel;
+    this.message = message;
+  }
+
+  /**
+   * Returns the name of this code.
+   *
+   * @return the name of the code.
+   */
+  public String getName() {
+    return name;
+  }
+
+  /**
+   * Returns the code.
+   *
+   * @return the code.
+   */
+  public int getCode() {
+    return code;
+  }
+
+  /**
+   * Returns the severity of this code.
+   *
+   * @return the log level severity of the code.
+   */
+  public String getLogLevel() {
+    return logLevel;
+  }
+
+  /**
+   * Returns the error message for this code.
+   *
+   * @return the error message for this code.
+   */
+  public String getMessage() {
+    return message;
+  }
+
+  /**
+   * Returns a textual representation of this code.
+   *
+   * @return a textual representation.
+   */
+  public String toString() {
+    return getClass().getName() +
+      "[name=" + name +
+      ",code=" + code +
+      ",logLevel=" + logLevel +
+      ",message=" + message +
+      "]";
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/corba/src/share/classes/com/sun/tools/corba/se/logutil/InputException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package com.sun.tools.corba.se.logutil;
+
+import java.util.LinkedList;
+import java.util.Queue;
+
+public class InputException {
+
+  /**
+   * The name of this exception.
+   */
+  private final String name;
+
+  /**
+   * The codes associated with this exception.
+   */
+  private final Queue<InputCode> codes;
+
+  /**
+   * Constructs a new {@link InputException} with the
+   * specified name.
+   *
+   * @param name the name of the new exception;
+   */
+  public InputException(final String name) {
+    this.name = name;
+    codes = new LinkedList<InputCode>();
+  }
+
+  /**
+   * Adds a new code to this exception.
+   *
+   * @param c the code to add.
+   */
+  public void add(InputCode c)
+  {
+    codes.offer(c);
+  }
+
+  /**
+   * Returns the name of this exception.
+   *
+   * @return the exception's name.
+   */
+  public String getName() {
+    return name;
+  }
+
+  /**
+   * Returns the codes associated with this exception.
+   *
+   * @return the exception's codes.
+   */
+  public Queue<InputCode> getCodes() {
+    return codes;
+  }
+
+  /**
+   * Returns a textual representation of this exception.
+   *
+   * @return a textual representation.
+   */
+  public String toString() {
+    return getClass().getName()
+      + "[name=" + name
+      + ",codes=" + codes
+      + "]";
+  }
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/corba/src/share/classes/com/sun/tools/corba/se/logutil/MC.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,559 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package com.sun.tools.corba.se.logutil;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Formatter;
+import java.util.List;
+import java.util.Queue;
+
+public class MC {
+
+  private static final String VERSION = "1.0";
+
+  private static final List<String> SUN_EXCEPTION_GROUPS = Arrays.asList(new String[]
+    { "SUNBASE", "ORBUTIL", "ACTIVATION", "NAMING", "INTERCEPTORS", "POA", "IOR", "UTIL" });
+
+  private static final List<String> EXCEPTIONS = Arrays.asList(new String[]
+    { "UNKNOWN", "BAD_PARAM", "NO_MEMORY", "IMP_LIMIT", "COMM_FAILURE", "INV_OBJREF", "NO_PERMISSION",
+      "INTERNAL", "MARSHAL", "INITIALIZE", "NO_IMPLEMENT", "BAD_TYPECODE", "BAD_OPERATION", "NO_RESOURCES",
+      "NO_RESPONSE", "PERSIST_STORE", "BAD_INV_ORDER", "TRANSIENT", "FREE_MEM", "INV_IDENT", "INV_FLAG",
+      "INTF_REPOS", "BAD_CONTEXT", "OBJ_ADAPTER", "DATA_CONVERSION", "OBJECT_NOT_EXIST", "TRANSACTION_REQUIRED",
+      "TRANSACTION_ROLLEDBACK", "INVALID_TRANSACTION", "INV_POLICY", "CODESET_INCOMPATIBLE", "REBIND",
+      "TIMEOUT", "TRANSACTION_UNAVAILABLE", "BAD_QOS", "INVALID_ACTIVITY", "ACTIVITY_COMPLETED",
+      "ACTIVITY_REQUIRED" });
+
+  /**
+   * Read the minor codes from the input file and
+   * write out a resource file.
+   *
+   * @param inFile the file to read the codes from.
+   * @param outDir the directory to write the resource file to.
+   * @throws FileNotFoundException if the input file can not be found.
+   * @throws IOException if an I/O error occurs.
+   */
+  private void makeResource(String inFile, String outDir)
+  throws FileNotFoundException, IOException {
+    writeResource(outDir, new Input(inFile));
+  }
+
+  /**
+   * Create a new Java source file using the specified Scheme input file,
+   * and writing the result to the given output directory.
+   *
+   * @param inFile the file to read the data from.
+   * @param outDir the directory to write the Java class to.
+   * @throws FileNotFoundException if the input file can not be found.
+   * @throws IOException if an I/O error occurs.
+   */
+  private void makeClass(String inFile, String outDir)
+  throws FileNotFoundException, IOException {
+    writeClass(inFile, outDir, new Input(inFile));
+  }
+
+  /**
+   * Writes out a Java source file using the data from the given
+   * {@link Input} object.  The result is written to {@code outDir}.
+   * The name of the input file is just used in the header of the
+   * resulting source file.
+   *
+   * @param inFile the name of the file the data was read from.
+   * @param outDir the directory to write the Java class to.
+   * @param input the parsed input data.
+   * @throws FileNotFoundException if the output file can't be written.
+   */
+  private void writeClass(String inFile, String outDir, Input input)
+    throws FileNotFoundException {
+    String packageName = input.getPackageName();
+    String className = input.getClassName();
+    String groupName = input.getGroupName();
+    Queue<InputException> exceptions = input.getExceptions();
+    FileOutputStream file = new FileOutputStream(outDir + File.separator + className + ".java");
+    IndentingPrintWriter pw = new IndentingPrintWriter(file);
+
+    writeClassHeader(inFile, groupName, pw);
+    pw.printMsg("package @ ;", packageName);
+    pw.println();
+    pw.println("import java.util.logging.Logger ;");
+    pw.println("import java.util.logging.Level ;");
+    pw.println();
+    pw.println("import org.omg.CORBA.OMGVMCID ;");
+    pw.println( "import com.sun.corba.se.impl.util.SUNVMCID ;");
+    pw.println( "import org.omg.CORBA.CompletionStatus ;");
+    pw.println( "import org.omg.CORBA.SystemException ;");
+    pw.println();
+    pw.println( "import com.sun.corba.se.spi.orb.ORB ;");
+    pw.println();
+    pw.println( "import com.sun.corba.se.spi.logging.LogWrapperFactory;");
+    pw.println();
+    pw.println( "import com.sun.corba.se.spi.logging.LogWrapperBase;");
+    pw.println();
+    writeImports(exceptions, pw);
+    pw.println();
+    pw.indent();
+    pw.printMsg("public class @ extends LogWrapperBase {", className);
+    pw.println();
+    pw.printMsg("public @( Logger logger )", className);
+    pw.indent();
+    pw.println( "{");
+    pw.undent();
+    pw.println( "super( logger ) ;");
+    pw.println( "}");
+    pw.println();
+    pw.flush();
+    writeFactoryMethod(className, groupName, pw);
+    writeExceptions(groupName, exceptions, className, pw);
+    pw.undent();
+    pw.println( );
+    pw.println( "}");
+    pw.flush();
+    pw.close();
+  }
+
+  /**
+   * Writes out the header of a Java source file.
+   *
+   * @param inFile the input file the file was generated from.
+   * @param groupName the group of exceptions the Java source file is for.
+   * @param pw the print writer used to write the output.
+   */
+  private void writeClassHeader(String inFile, String groupName,
+                                IndentingPrintWriter pw) {
+    if (groupName.equals("OMG"))
+      pw.println("// Log wrapper class for standard exceptions");
+    else
+      pw.printMsg("// Log wrapper class for Sun private system exceptions in group @",
+                  groupName);
+    pw.println("//");
+    pw.printMsg("// Generated by MC.java version @, DO NOT EDIT BY HAND!", VERSION);
+    pw.printMsg("// Generated from input file @ on @", inFile, new Date());
+    pw.println();
+  }
+
+  /**
+   * Write out the import list for the exceptions.
+   *
+   * @param groups the exceptions that were parsed.
+   * @param pw the {@link IndentingPrintWriter} for writing to the file.
+   */
+  private void writeImports(Queue<InputException> exceptions,
+                            IndentingPrintWriter pw) {
+    if (exceptions == null)
+      return;
+    for (InputException e : exceptions)
+      pw.println("import org.omg.CORBA." + e.getName() + " ;");
+  }
+
+  /**
+   * Write out the factory method for this group of exceptions.
+   *
+   * @param className the name of the generated class.
+   * @param groupName the name of this group of exceptions.
+   * @param pw the {@link IndentingPrintWriter} for writing to the file.
+   */
+  private void writeFactoryMethod(String className, String groupName,
+                                  IndentingPrintWriter pw) {
+    pw.indent();
+    pw.println( "private static LogWrapperFactory factory = new LogWrapperFactory() {");
+    pw.println( "public LogWrapperBase create( Logger logger )" );
+    pw.indent();
+    pw.println( "{");
+    pw.undent();
+    pw.printMsg("return new @( logger ) ;", className);
+    pw.undent();
+    pw.println( "}" );
+    pw.println( "} ;" );
+    pw.println();
+    pw.printMsg("public static @ get( ORB orb, String logDomain )", className);
+    pw.indent();
+    pw.println( "{");
+    pw.indent();
+    pw.printMsg( "@ wrapper = ", className);
+    pw.indent();
+    pw.printMsg( "(@) orb.getLogWrapper( logDomain, ", className);
+    pw.undent();
+    pw.undent();
+    pw.printMsg( "\"@\", factory ) ;", groupName);
+    pw.undent();
+    pw.println( "return wrapper ;" );
+    pw.println( "} " );
+    pw.println();
+    pw.printMsg( "public static @ get( String logDomain )", className);
+    pw.indent();
+    pw.println( "{");
+    pw.indent();
+    pw.printMsg( "@ wrapper = ", className);
+    pw.indent();
+    pw.printMsg( "(@) ORB.staticGetLogWrapper( logDomain, ", className);
+    pw.undent();
+    pw.undent();
+    pw.printMsg( "\"@\", factory ) ;", groupName);
+    pw.undent();
+    pw.println( "return wrapper ;" );
+    pw.println( "} " );
+    pw.println();
+  }
+
+  /**
+   * Writes out the exceptions themselves.
+   *
+   * @param groupName the name of this group of exceptions.
+   * @param exceptions the exceptions to write out.
+   * @param className the name of the generated class.
+   * @param pw the {@link IndentingPrintWriter} for writing to the file.
+   */
+  private void writeExceptions(String groupName, Queue<InputException> exceptions,
+                               String className, IndentingPrintWriter pw) {
+    for (InputException e : exceptions) {
+      pw.println("///////////////////////////////////////////////////////////");
+      pw.printMsg("// @", e.getName());
+      pw.println("///////////////////////////////////////////////////////////");
+      pw.println();
+      for (InputCode c : e.getCodes())
+        writeMethods(groupName, e.getName(), c.getName(), c.getCode(),
+                     c.getLogLevel(), className, StringUtil.countArgs(c.getMessage()), pw);
+      pw.flush();
+    }
+  }
+
+  /**
+   * Writes out the methods for a particular error.
+   *
+   * @param groupName the name of this group of exceptions.
+   * @param exceptionName the name of this particular exception.
+   * @param errorName the name of this particular error.
+   * @param code the minor code for this particular error.
+   * @param ident the name of the error in mixed-case identifier form.
+   * @param level the level at which to place log messages.
+   * @param className the name of the class for this group of exceptions.
+   * @param numParams the number of parameters the detail message takes.
+   * @param pw the print writer for writing to the file.
+   */
+  private void writeMethods(String groupName, String exceptionName, String errorName,
+                            int code, String level, String className, int numParams,
+                            IndentingPrintWriter pw) {
+    String ident = StringUtil.toMixedCase(errorName);
+    pw.printMsg("public static final int @ = @ ;", errorName, getBase(groupName, code));
+    pw.println();
+    pw.flush();
+    writeMethodStatusCause(groupName, exceptionName, errorName, ident, level,
+                           numParams, className, pw);
+    pw.println();
+    pw.flush();
+    writeMethodStatus(exceptionName, ident, numParams, pw);
+    pw.println();
+    pw.flush();
+    writeMethodCause(exceptionName, ident, numParams, pw);
+    pw.println();
+    pw.flush();
+    writeMethodNoArgs(exceptionName, ident, numParams, pw);
+    pw.println();
+    pw.flush();
+  }
+
+  /**
+   * Writes out a method for an error that takes a
+   * {@link org.omg.CORBA.CompletionStatus} and a cause.
+   *
+   * @param groupName the name of this group of exceptions.
+   * @param exceptionName the name of this particular exception.
+   * @param errorName the name of this particular error.
+   * @param ident the name of the error in mixed-case identifier form.
+   * @param logLevel the level at which to place log messages.
+   * @param numParams the number of parameters the detail message takes.
+   * @param className the name of the class for this group of exceptions.
+   * @param pw the print writer for writing to the file.
+   */
+  private void writeMethodStatusCause(String groupName, String exceptionName,
+                                      String errorName, String ident,
+                                      String logLevel, int numParams,
+                                      String className, IndentingPrintWriter pw) {
+    pw.indent();
+    pw.printMsg( "public @ @( CompletionStatus cs, Throwable t@) {", exceptionName,
+                 ident, makeDeclArgs(true, numParams));
+    pw.printMsg( "@ exc = new @( @, cs ) ;", exceptionName, exceptionName, errorName);
+    pw.indent();
+    pw.println( "if (t != null)" );
+    pw.undent();
+    pw.println( "exc.initCause( t ) ;" );
+    pw.println();
+    pw.indent();
+    pw.printMsg( "if (logger.isLoggable( Level.@ )) {", logLevel);
+    if (numParams > 0) {
+      pw.printMsg( "Object[] parameters = new Object[@] ;", numParams);
+      for (int a = 0; a < numParams; ++a)
+        pw.printMsg("parameters[@] = arg@ ;", a, a);
+    } else
+      pw.println( "Object[] parameters = null ;");
+    pw.indent();
+    pw.printMsg( "doLog( Level.@, \"@.@\",", logLevel, groupName, ident);
+    pw.undent();
+    pw.undent();
+    pw.printMsg( "parameters, @.class, exc ) ;", className);
+    pw.println( "}");
+    pw.println();
+
+    pw.undent();
+    pw.println( "return exc ;");
+    pw.println( "}");
+  }
+
+  /**
+   * Writes out a method for an error that takes a
+   * {@link org.omg.CORBA.CompletionStatus}.
+   *
+   * @param exceptionName the name of this particular exception.
+   * @param ident the name of the error in mixed-case identifier form.
+   * @param numParams the number of parameters the detail message takes.
+   * @param pw the print writer for writing to the file.
+   */
+  private void writeMethodStatus(String exceptionName, String ident,
+                                 int numParams, IndentingPrintWriter pw) {
+    pw.indent();
+    pw.printMsg("public @ @( CompletionStatus cs@) {", exceptionName,
+                ident, makeDeclArgs(true, numParams));
+    pw.undent();
+    pw.printMsg("return @( cs, null@ ) ;", ident, makeCallArgs(true, numParams));
+    pw.println("}");
+  }
+
+  /**
+   * Writes out a method for an error that takes a cause.
+   *
+   * @param exceptionName the name of this particular exception.
+   * @param ident the name of the error in mixed-case identifier form.
+   * @param numParams the number of parameters the detail message takes.
+   * @param pw the print writer for writing to the file.
+   */
+  private void writeMethodCause(String exceptionName, String ident,
+                                int numParams, IndentingPrintWriter pw) {
+    pw.indent();
+    pw.printMsg("public @ @( Throwable t@) {", exceptionName, ident,
+                makeDeclArgs(true, numParams));
+    pw.undent();
+    pw.printMsg("return @( CompletionStatus.COMPLETED_NO, t@ ) ;", ident,
+                makeCallArgs(true, numParams));
+    pw.println("}");
+  }
+
+  /**
+   * Writes out a method for an error that takes no arguments.
+   *
+   * @param exceptionName the name of this particular exception.
+   * @param ident the name of the error in mixed-case identifier form.
+   * @param numParams the number of parameters the detail message takes.
+   * @param pw the print writer for writing to the file.
+   */
+  private void writeMethodNoArgs(String exceptionName, String ident,
+                                 int numParams, IndentingPrintWriter pw) {
+
+    pw.indent();
+    pw.printMsg("public @ @( @) {", exceptionName, ident,
+                makeDeclArgs(false, numParams));
+    pw.undent();
+    pw.printMsg("return @( CompletionStatus.COMPLETED_NO, null@ ) ;",
+                ident, makeCallArgs(true, numParams));
+    pw.println("}");
+  }
+
+  /**
+   * Returns a list of comma-separated arguments with type declarations.
+   *
+   * @param leadingComma true if the list should start with a comma.
+   * @param numArgs the number of arguments to generate.
+   * @return the generated string.
+   */
+  private String makeDeclArgs(boolean leadingComma, int numArgs) {
+    return makeArgString("Object arg", leadingComma, numArgs);
+  }
+
+  /**
+   * Returns a list of comma-separated arguments without type declarations.
+   *
+   * @param leadingComma true if the list should start with a comma.
+   * @param numArgs the number of arguments to generate.
+   * @return the generated string.
+   */
+  private String makeCallArgs(boolean leadingComma, int numArgs) {
+    return makeArgString("arg", leadingComma, numArgs);
+  }
+
+  /**
+   * Returns a list of comma-separated arguments.
+   *
+   * @param prefixString the string with which to prefix each argument.
+   * @param leadingComma true if the list should start with a comma.
+   * @param numArgs the number of arguments to generate.
+   * @return the generated string.
+   */
+  private String makeArgString(String prefixString, boolean leadingComma,
+                               int numArgs) {
+    if (numArgs == 0)
+      return " ";
+    if (numArgs == 1) {
+      if (leadingComma)
+        return ", " + prefixString + (numArgs - 1);
+      else
+        return " " + prefixString + (numArgs - 1);
+    }
+    return makeArgString(prefixString, leadingComma, numArgs - 1) +
+      ", " + prefixString + (numArgs - 1);
+  }
+
+  /**
+   * Returns the {@link String} containing the calculation of the
+   * error code.
+   *
+   * @param groupName the group of exception to which the code belongs.
+   * @param code the minor code number representing the exception within the group.
+   * @return the unique error code.
+   */
+  private String getBase(String groupName, int code) {
+    if (groupName.equals("OMG"))
+      return "OMGVMCID.value + " + code;
+    else
+      return "SUNVMCID.value + " + (code + getSunBaseNumber(groupName));
+  }
+
+  /**
+   * Returns the base number for Sun-specific exceptions.
+   *
+   * @return the base number.
+   */
+  private int getSunBaseNumber(String groupName) {
+    return 200 * SUN_EXCEPTION_GROUPS.indexOf(groupName);
+  }
+
+  /**
+   * Writes out a resource file using the data from the given
+   * {@link Input} object.  The result is written to {@code outDir}.
+   *
+   * @param outDir the directory to write the Java class to.
+   * @param input the parsed input data.
+   * @throws FileNotFoundException if the output file can't be written.
+   */
+  private void writeResource(String outDir, Input input)
+    throws FileNotFoundException {
+    FileOutputStream file = new FileOutputStream(outDir + File.separator +
+                                                 input.getClassName() + ".resource");
+    IndentingPrintWriter pw = new IndentingPrintWriter(file);
+    String groupName = input.getGroupName();
+    for (InputException e : input.getExceptions()) {
+      String exName = e.getName();
+      for (InputCode c : e.getCodes()) {
+        String ident = StringUtil.toMixedCase(c.getName());
+        pw.printMsg("@.@=\"@: (@) @\"", groupName, ident,
+                    getMessageID(groupName, exName, c.getCode()), exName, c.getMessage());
+      }
+      pw.flush();
+    }
+    pw.close();
+  }
+
+  /**
+   * Returns the message ID corresponding to the given group name,
+   * exception name and error code.
+   *
+   * @param groupName the name of the group of exceptions.
+   * @param exception the name of the particular exception.
+   * @param code an error code from the given exception.
+   * @return the message ID.
+   */
+  private String getMessageID(String groupName, String exceptionName, int code) {
+    if (groupName.equals("OMG"))
+      return getStandardMessageID(exceptionName, code);
+    else
+      return getSunMessageID(groupName, exceptionName, code);
+  }
+
+  /**
+   * Returns the standard (OMG) message ID corresponding to the given
+   * exception name and error code.
+   *
+   * @param exceptionName the name of the particular exception.
+   * @param code an error code from the given exception.
+   * @return the message ID.
+   */
+  private String getStandardMessageID(String exceptionName, int code) {
+    return new Formatter().format("IOP%s0%04d", getExceptionID(exceptionName),
+                                  code).toString();
+  }
+
+  /**
+   * Returns the Sun message ID corresponding to the given group name,
+   * exception name and error code.
+   *
+   * @param groupName the name of the group of exceptions.
+   * @param exceptionName the name of the particular exception.
+   * @param code an error code from the given exception.
+   * @return the message ID.
+   */
+  private String getSunMessageID(String groupName, String exceptionName, int code) {
+    return new Formatter().format("IOP%s1%04d", getExceptionID(exceptionName),
+                                  getSunBaseNumber(groupName) + code).toString();
+  }
+
+  /**
+   * Returns the exception ID corresponding to the given exception name.
+   *
+   * @param exceptionName the name of the particular exception.
+   * @return the message ID.
+   */
+  private String getExceptionID(String exceptionName) {
+    return new Formatter().format("%03d", EXCEPTIONS.indexOf(exceptionName)).toString();
+  }
+
+  /**
+   * Entry point for running the generator from the command
+   * line.  Users can specify either "make-class" or "make-resource"
+   * as the first argument to generate the specified type of file.
+   *
+   * @param args the command-line arguments.
+   * @throws FileNotFoundException if the input file can not be found.
+   * @throws IOException if an I/O error occurs.
+   */
+  public static void main(String[] args)
+    throws FileNotFoundException, IOException
+  {
+    if (args.length < 3)
+      {
+        System.err.println("(make-class|make-resource) <input file> <output dir>");
+        System.exit(-1);
+      }
+    if (args[0].equals("make-class"))
+      new MC().makeClass(args[1], args[2]);
+    else if (args[0].equals("make-resource"))
+      new MC().makeResource(args[1], args[2]);
+    else
+      System.err.println("Invalid command: " + args[0]);
+  }
+
+}
Binary file corba/src/share/classes/com/sun/tools/corba/se/logutil/lib/jscheme.jar has changed
Binary file corba/src/share/classes/com/sun/tools/corba/se/logutil/lib/jschemelogutil.jar has changed
--- a/corba/src/share/classes/com/sun/tools/corba/se/logutil/scripts/mc	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-#! /bin/sh
-java -cp lib/jscheme.jar:lib/util.jar jscheme.REPL mc.scm -main main $@
--- a/corba/src/share/classes/com/sun/tools/corba/se/logutil/scripts/mc.scm	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,662 +0,0 @@
-; Scheme program to produce CORBA standard exceptions class
-; requires Jscheme Java extensions
-; Makes use of some custom Java classes also
-
-(import "com.sun.tools.corba.se.logutil.IndentingPrintWriter" ) 
-(import "com.sun.tools.corba.se.logutil.StringUtil" ) 
-(import "java.io.FileOutputStream")
-
-(define version-string "1.3")
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Utility functions
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; reload this file (convenience definition)
-(define (reload) (load "mc.scm"))
-
-; Simple little function to report an error
-(define (error msg)
-    (throw (Error. msg)))
-
-; some debug support
-(define debug #f)
-
-(define (dprint msg)
-    (if debug
-	(.println System.out$ msg)))
-
-; Replace dprint with noprint to avoid seeing messages when debug is #t
-(define (noprint msg) ())
-
-; Helper function present so that a scheme method taking strings as args 
-; can be easily run from a command line.
-; arg:	    vector containing argument strings. Element 0 is the function name
-;	    to execute
-(define (main arg)
-    (let*
-	(
-	    (arg-list (vector->list arg))
-	    (function-symbol (string->symbol (car arg-list)))
-	    (args (cdr arg-list)))
-	(apply (eval function-symbol) args)))
-
-; Returns the position of key in lst, numbering from 0.  key is matched using eqv?
-(define (get-list-position key lst)
-    (letrec
-	(
-	    (helper (lambda (k l accum)
-		(cond 
-		    ((null? l) (error (string-append "Could not find " k)))
-		    ((eqv? k (car l)) accum)
-		    (else (helper k (cdr l) (+ accum 1))) ))))
-	(begin 
-	    (noprint (string-append "get-list-position called with key " key " lst " lst ))
-	    (helper key lst 0))))
-
-; Return a string representing number in decimal padded to length with leading 0s.
-(define (pad-number-string number length)
-    (let*
-	(
-	    (number-string (number->string number))
-	    (pad-length (- length (string-length number-string)))
-	)
-	(string-append (make-string pad-length #\0) number-string)))
-
-; Read an S-expression from a file that contains all of the data.
-;
-; The S-expression used for minor codes must have the structure
-;   (package-name class-name exception-group-name
-;	(exception
-;	    (name value level explanation)
-;	    ...
-;	)
-;	...
-;   )
-(define (read-file fname)
-    (read (open-input-file fname)))
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Functions for handling major system exceptions and exception groups
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; Function to find the base ID given an exception group name.  Result is a function that
-; maps the minor code into the Java expression for that minor code's actual value.
-(define (get-base group-name)
-	(if (eqv? group-name 'OMG)
-	    (lambda (minor-code)
-		(string-append "OMGVMCID.value + " (number->string minor-code)))
-	    (let  ; bind base-number outside the lambda so it is only evaluated once
-		(
-		    (base-number (get-sun-base-number group-name)))
-		(lambda (minor-code)
-		    (string-append "SUNVMCID.value + " (number->string (+ base-number minor-code)))))))
-
-; Function to get a base value for the group-name
-(define (get-sun-base-number group-name)
-    (let*
-	(
-	    (lst (list 'SUNBASE 'ORBUTIL 'ACTIVATION 'NAMING 'INTERCEPTORS 'POA 'IOR 'UTIL))
-	    (subsystem-size 200))
-	(* subsystem-size (get-list-position group-name lst))))
-
-; Function to get a 3 digit number for a system exception
-(define (get-exception-id exception-name)
-    (let
-	(
-	    (lst (list 'UNKNOWN 'BAD_PARAM 'NO_MEMORY 'IMP_LIMIT 'COMM_FAILURE 'INV_OBJREF 'NO_PERMISSION 
-		'INTERNAL 'MARSHAL 'INITIALIZE 'NO_IMPLEMENT 'BAD_TYPECODE 'BAD_OPERATION 'NO_RESOURCES 
-		'NO_RESPONSE 'PERSIST_STORE 'BAD_INV_ORDER 'TRANSIENT 'FREE_MEM 'INV_IDENT 'INV_FLAG 
-		'INTF_REPOS 'BAD_CONTEXT 'OBJ_ADAPTER 'DATA_CONVERSION 'OBJECT_NOT_EXIST 'TRANSACTION_REQUIRED 
-		'TRANSACTION_ROLLEDBACK 'INVALID_TRANSACTION 'INV_POLICY 'CODESET_INCOMPATIBLE 'REBIND 
-		'TIMEOUT 'TRANSACTION_UNAVAILABLE 'BAD_QOS 'INVALID_ACTIVITY 'ACTIVITY_COMPLETED 
-		'ACTIVITY_REQUIRED )))
-	(pad-number-string (get-list-position exception-name lst) 3)))
-
-; Return the message id string for any system exception
-;
-(define (get-message-id exception-type group-name minor)
-    (if (eqv? group-name 'OMG)
-	(get-standard-message-id exception-type minor)
-	(get-sun-message-id exception-type group-name minor)))
-
-; Return the message id string for a particular standard exception
-;
-(define (get-standard-message-id exception-type minor)
-    (string-append 
-	"IOP" 
-	(get-exception-id exception-type) 
-	"0" 
-	(pad-number-string (number->string minor) 4)))
-
-; Return the sun message id for this exception-type, group-name, and minor code.
-(define (get-sun-message-id exception-type group-name minor)
-    (string-append 
-	"IOP" 
-	(get-exception-id exception-type) 
-	"1"
-	(pad-number-string (+ (get-sun-base-number group-name) minor) 4)))
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-; visitor framework for the input file format
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-(define (visit-top obj func1)
-    (let*
-	(
-	    (package (car obj))
-	    (class (cadr obj))
-	    (group (caddr obj))
-	    (func2 (func1 package class group))
-	    (exceptions (cadddr obj)))
-	(visit-exceptions exceptions func2)))
-
-; visit the elements of an arbitrary list
-; lst:		the list to visit
-; func:		the function to apply to each element of lst
-; next-level	the function on lst element and func that visits the next level
-(define (visit-list lst func next-level)
-    (if (null? (cdr lst))
-	(next-level #t (car lst) func)
-	(begin
-	    (next-level #f (car lst) func)
-	    (visit-list (cdr lst) func next-level))))
-
-(define (visit-exceptions exceptions func2)
-    (visit-list exceptions func2 (lambda (last-flag element func) (visit-exception last-flag element func))))
-
-(define (visit-exception last-flag exception func2)
-    (let*
-	(
-	    (major (car exception))
-	    (minor-codes (cdr exception))
-	    (func3 (func2 last-flag major)))
-	(visit-minor-codes minor-codes func3)))
-
-(define (visit-minor-codes minor-codes func3)
-    (visit-list minor-codes func3 (lambda (last-flag element func) (visit-minor-code last-flag element func))))
-
-(define (visit-minor-code last-flag minor-code func3)
-    (let*   
-	(
-	    (name (car minor-code))
-	    (minor (cadr minor-code))
-	    (level (caddr minor-code))
-	    (msg (cadddr minor-code)))
-	(func3 last-flag name minor level msg)))
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; The visitors
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; A simple visitor that just echoes the input for test purposes
-(define (simple-visitor package class group)
-    (let* 
-	(
-	    (pw (IndentingPrintWriter. System.out$)))
-	(begin
-	    (.indent pw)
-	    (.printMsg pw "package=@ class=@ group=@" (list package class group))
-	    (.flush pw)
-	    (lambda (last-flag major)
-		(begin
-		    (.indent pw)
-		    (.printMsg pw "major=@" (list major))
-		    (.flush pw)
-		    (lambda (last-flag name minor level message)
-			(begin
-			    (if last-flag (.undent pw))
-			    (.printMsg pw "name=@ minor=@ level=@ message=@" (list name minor level message))
-			    (.flush pw))))))))
-
-; Function that returns a visitor that writes out the resource file in the form:
-;   id="MSGID: explanation"
-; outdir: Output directory 
-(define (resource-visitor outdir)
-    (lambda (package class group)
-	(let* 
-	    (
-		(file-name (string-append outdir java.io.File.separator$ class ".resource"))
-		(pw (IndentingPrintWriter. (FileOutputStream. file-name))))
-	    (begin 
-		(dprint (string-append "package= " package " class=" class " group=" group " file-name=" file-name))
-		(lambda (last-flag1 major)
-		    (begin
-			; (dprint (string-append "last-flag1=" last-flag1 " major=" major))
-			(lambda (last-flag2 name minor level message)
-			    (begin
-				; (dprint (string-append "last-flag2=" last-flag2 " name=" name 
-				    ; " minor=" minor " level=" level " message=" message))
-				(let*
-				    (
-					(msgid (get-message-id major group minor))
-					(ident (StringUtil.toMixedCase (symbol->string name))))
-				    (begin
-					; (dprint (string-append "msgid=" msgid " ident=" ident))
-					(.printMsg pw "@.@=\"@: (@) @\"" (list group ident msgid major message))
-					(.flush pw)
-					(if (and last-flag1 last-flag2) 
-					    (begin
-						; (dprint "closing file")
-						(.close pw)))))))))))))
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Top-level functions for creating the products.  All have names of the form make-xxx
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; Read the minor codes from the infile and write out a resource file. 
-(define (make-resource infile outdir)
-    (tryCatch 
-	(visit-top (read-file infile) (resource-visitor outdir))
-	(lambda (exc) 
-	    (begin
-		(.println System.out$ (string-append "make-resource failed with exception " (.toString exc)))
-		(System.exit 1)))))
-
-; Read the minor codes from the infile and write a Java implementation to
-; handle them to outfile under outdir
-(define (make-class infile outdir)
-    (tryCatch 
-	(write-class infile outdir (read-file infile))
-	(lambda (exc) 
-	    (begin
-		(.println System.out$ (string-append "make-class failed with exception " (.toString exc)))
-		(System.exit 1)))))
-	
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; The original make-class implementation (this should be replaced by two visitors)
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; Write out the Java source code for the StandardExceptions class
-; outdir:  Output directory to write the generated files
-; obj:	    the data from the input file
-(define (write-class infile outdir obj)
-    (let* 
-	( 
-	    (package-name (car obj))
-	    (class-name (cadr obj))
-	    (exception-group-name (caddr obj))
-	    (exceptions (cadddr obj))
-	    (file (FileOutputStream. (string-append outdir java.io.File.separator$  class-name ".java")))  
-	    (pw   (IndentingPrintWriter. file))
-	)
-	(begin
-	    (write-class-header infile package-name class-name exception-group-name pw)
-	    (.printMsg pw "package @ ;"
-		(list package-name))
-	    (.println pw)
-	    (.println pw "import java.util.logging.Logger ;")
-	    (.println pw "import java.util.logging.Level ;")
-	    (.println pw)
-	    (.println pw "import org.omg.CORBA.OMGVMCID ;")
-	    (.println pw "import com.sun.corba.se.impl.util.SUNVMCID ;")
-	    (.println pw "import org.omg.CORBA.CompletionStatus ;")
-	    (.println pw "import org.omg.CORBA.SystemException ;")
-	    (.println pw)
-	    (.println pw "import com.sun.corba.se.spi.orb.ORB ;")
-	    (.println pw)
-	    (.println pw "import com.sun.corba.se.spi.logging.LogWrapperFactory;")
-	    (.println pw)
-	    (.println pw "import com.sun.corba.se.spi.logging.LogWrapperBase;")
-	    (.println pw)
-	    (write-imports exceptions pw)
-	    (.println pw)
-	    (.indent pw)
-	    (.printMsg pw "public class @ extends LogWrapperBase {"
-		(list class-name))
-	    (.println pw)
-	    (.printMsg pw "public @( Logger logger )"
-		(list class-name))
-	    (.indent pw)
-	    (.println pw "{")
-	    (.undent pw)
-	    (.println pw "super( logger ) ;")
-	    (.println pw "}")
-	    (.println pw)
-	    (.flush pw)
-	    (write-factory-method class-name exception-group-name pw)
-	    (write-exceptions exception-group-name exceptions (get-base exception-group-name) class-name pw)
-	    (.undent pw)
-	    (.println pw )
-	    (.println pw "}")
-	    (.flush pw)
-	    (.close pw)
-	)))
-
-; Write out the header for the resource file
-(define (write-class-header infile package class group pw)
-    (begin
-	(if (eqv? group 'OMG)
-	    (.println pw "// Log wrapper class for standard exceptions")
-	    (.printMsg pw "// Log wrapper class for Sun private system exceptions in group @" (list group)))
-	(.println pw "//")
-	(.printMsg pw "// Generated by mc.scm version @, DO NOT EDIT BY HAND!" (list version-string))
-	(.printMsg pw "// Generated from input file @ on @" (list infile (java.util.Date.)))
-	(.println pw)))
-
-(define (write-factory-method class-name exception-group-name pw)
-    (begin
-	(.indent pw)
-	(.println pw "private static LogWrapperFactory factory = new LogWrapperFactory() {")
-	(.println pw "public LogWrapperBase create( Logger logger )" )
-	(.indent pw)
-	(.println pw "{")
-	(.undent pw)
-	(.printMsg pw "return new @( logger ) ;" (list class-name))
-	(.undent pw)
-	(.println pw "}" )
-	(.println pw "} ;" )
-	(.println pw)
-	(.printMsg pw "public static @ get( ORB orb, String logDomain )" (list class-name))
-	(.indent pw)	
-	(.println pw "{")
-	(.indent pw)	
-	(.printMsg pw "@ wrapper = "
-	    (list class-name))
-	(.indent pw)
-	(.printMsg pw "(@) orb.getLogWrapper( logDomain, " 
-	    (list class-name))
-	(.undent pw)	
-	(.undent pw)	
-	(.printMsg pw "\"@\", factory ) ;" 
-	    (list exception-group-name))
-	(.undent pw)	
-	(.println pw "return wrapper ;" )
-	(.println pw "} " )
-	(.println pw)
-	(.printMsg pw "public static @ get( String logDomain )" (list class-name))
-	(.indent pw)	
-	(.println pw "{")
-	(.indent pw)	
-	(.printMsg pw "@ wrapper = "
-	    (list class-name))
-	(.indent pw)
-	(.printMsg pw "(@) ORB.staticGetLogWrapper( logDomain, " 
-	    (list class-name))
-	(.undent pw)	
-	(.undent pw)	
-	(.printMsg pw "\"@\", factory ) ;" 
-	    (list exception-group-name))
-	(.undent pw)	
-	(.println pw "return wrapper ;" )
-	(.println pw "} " )
-	(.println pw)))
-
-; Write out the import list for the exceptions listed in obj
-; obj:	    the data from the input file
-; pw:	    an IndentingPrintWriter for the output file
-(define (write-imports obj pw)
-    (if (null? obj)
-	()
-	(let 
-	    (
-		(exception (caar obj))
-	    )
-	    (begin
-		(.print pw "import org.omg.CORBA.")
-		(.print pw exception)
-		(.println pw " ;")
-		(write-imports (cdr obj) pw)
-	    ))))
-
-; Write out the list of exceptions starting with the first one
-; obj:	    the data from the input file
-; base:	    the lambda that returns the string defining the minor code value
-; pw:	    an IndentingPrintWriter for the output file
-(define (write-exceptions group-name obj base class-name pw)
-    (if (null? obj) 
-	()
-	(let* 
-	    (
-		(record (car obj))
-		(exception (car record))
-	        (minor-codes (cdr record))
-	    )
-	    (begin
-		(write-exception group-name exception minor-codes base class-name pw)
-		(write-exceptions group-name (cdr obj) base class-name pw)
-	    ))))
-
-; Write out a single exception
-; exception:	the CORBA SystemException type
-; base:		the base for the minor code value
-; minor-codes:	a list of minor code data for each minor exception type
-; pw:		an IndentingPrintWriter for the output file
-(define (write-exception group-name exception minor-codes base class-name pw)
-    (begin
-	(.println pw "///////////////////////////////////////////////////////////")
-	(.printMsg pw "// @" (list exception))
-	(.println pw "///////////////////////////////////////////////////////////")
-	(.println pw)
-	(write-methods group-name exception minor-codes base class-name pw)
-	(.flush pw)))
-
-; Write all of the methods for a single exception
-; exception:	the CORBA SystemException type
-; base:		the base for the minor code value
-; minor-codes:	a list of minor code data for each minor exception type
-; pw:		an IndentingPrintWriter for the output file
-(define (write-methods group-name exception minor-codes base class-name pw)
-    (if (null? minor-codes)
-	()
-	(begin
-	    (write-method group-name exception (car minor-codes) base class-name pw)
-	    (write-methods group-name exception (cdr minor-codes) base class-name pw)
-	)))
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;; Code that writes out the Java methods for exception handling
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-; Write the methods for a single minor code within an exception
-; exception:	the CORBA SystemException type
-; minor-code:	minor code data for one minor exception type 
-;		(name value level explanation)
-; base:		the base for the minor code value
-; pw:		an IndentingPrintWriter for the output file
-(define (write-method group-name exception minor-code base class-name pw)
-    (let* 
-	(
-	    (x (symbol->string (car minor-code)))
-	    (ident (cons x (StringUtil.toMixedCase x)))
-	    (value (cadr minor-code))
-	    (level (symbol->string (caddr minor-code)))
-	    (explanation (cadddr minor-code))
-	    (num-params (StringUtil.countArgs explanation)))
-	(begin
-	    (.printMsg pw "public static final int @ = @ ;"
-		(list x (base value)))
-	    (.println pw )
-	    (.flush pw )
-	    (write-method-status-cause group-name exception ident level num-params class-name pw)
-	    (.println pw)
-	    (.flush pw)
-	    (write-method-status exception ident level num-params pw)
-	    (.println pw)
-	    (.flush pw)
-	    (write-method-cause exception ident level num-params pw)
-	    (.println pw)
-	    (.flush pw)
-	    (write-method-no-args exception ident level num-params pw)
-	    (.println pw)
-	    (.flush pw))))
-
-; Construct a string of the form arg1, ..., argn where n is num-params
-(define (make-arg-string fixed leading-comma-flag num-args)
-    (let
-	(
-	    (helper (lambda (lcf n)
-		(let*
-		    (
-			(numstr (number->string (- n 1))))
-		    (if (or lcf (> n 1))
-			(string-append ", " fixed numstr)
-			(string-append " " fixed numstr))))))
-	(cond 
-	    ((eqv? num-args 0) " ")
-	    ((eqv? num-args 1) (helper leading-comma-flag 1))
-	    (else (string-append 
-		(make-arg-string fixed leading-comma-flag (- num-args 1)) 
-		(helper leading-comma-flag num-args ))))))
-
-(define (make-decl-args leading-comma-flag num-args)
-    (make-arg-string "Object arg" leading-comma-flag num-args))
-
-(define (make-call-args leading-comma-flag num-args)
-    (make-arg-string "arg" leading-comma-flag num-args))
-
-; make-xxx-args patterns:
-; leading-comma-flag #t
-;
-;   0   " "
-;   1   ", arg0"
-;   2   ", arg0, arg1"
-;   3   ", arg0, arg1, arg2"
-;
-;   0   " "
-;   1   ", Object arg0"
-;   2   ", Object arg0, Object arg1"
-;   3   ", Object arg0, Object arg1, Object arg2"
-;
-; leading-comma-flag #f
-;
-;   0   " "
-;   1   " arg0"
-;   2   " arg0, arg1"
-;   3   " arg0, arg1, arg2"
-;
-;   0   " "
-;   1   " Object arg0"
-;   2   " Object arg0, Object arg1"
-;   3   " Object arg0, Object arg1, Object arg2"
-
-(define (emit-assignments num pw)
-    (let 
-	(
-	    (helper 
-		(lambda (n) 
-		    (.printMsg pw "parameters[@] = arg@ ;" (list n n)))))
-	(if (= num 1)
-	    (helper (- num 1))
-	    (begin
-		(emit-assignments (- num 1) pw)
-		(helper (- num 1))))))
-
-; Write a method for an exception that takes a CompletionStatus and a cause
-; exception:	the CORBA system exception type
-; id:		the identifier for this exception in the form ( ident . mixed-case-ident )
-; level:	the logging level
-; num-params:	number of parameters in the explanation string, which determines
-;		how many argn parameters we need
-; pw:		the indenting print writer we are using
-(define (write-method-status-cause group-name exception id level num-params class-name pw)
-    (let*
-	(
-	    (ident (car id))
-	    (ident-mc (cdr id)))
-    (begin
-	(.indent pw)
-	(.printMsg pw "public @ @( CompletionStatus cs, Throwable t@) {"
-	    (list exception ident-mc (make-decl-args #t num-params)))
-	(.printMsg pw "@ exc = new @( @, cs ) ;"
-	    (list exception exception ident ))
-
-	(.indent pw)
-	(.println pw "if (t != null)" )
-	(.undent pw)
-	(.println pw "exc.initCause( t ) ;" )	
-	(.println pw)
-
-	(.indent pw)
-	(.printMsg pw "if (logger.isLoggable( Level.@ )) {"
-	    (list level))
-	
-	(if (> num-params 0)
-	    (begin
-		(.printMsg pw "Object[] parameters = new Object[@] ;"
-		    (list (number->string num-params)))
-		(emit-assignments num-params pw)
-	    )
-	    (begin
-		(.println pw "Object[] parameters = null ;"
-	    )))
-
-	(.indent pw)
-	(.printMsg pw "doLog( Level.@, \"@.@\"," (list level group-name ident-mc))
-	(.undent pw)
-	(.undent pw)
-	(.printMsg pw "parameters, @.class, exc ) ;" (list class-name))
-	(.println pw "}")
-	(.println pw)
-
-	(.undent pw)
-	(.println pw "return exc ;")
-
-	(.println pw "}"))))
-
-; Write a method for an exception that takes a CompletionStatus.  The cause is null. 
-;
-; exception:	the CORBA system exception type
-; id:		the identifier for this exception in the form ( ident . mixed-case-ident )
-; level:	the logging level
-; num-params:	number of parameters in the explanation string, which determines
-;		how many argn parameters we need
-; pw:		the indenting print writer we are using
-(define (write-method-status exception id level num-params pw)
-    (let*
-	(
-	    (ident-mc (cdr id)))
-	(begin
-	    (.indent pw)
-	    (.printMsg pw "public @ @( CompletionStatus cs@) {"
-		(list exception ident-mc (make-decl-args #t num-params)))
-	    (.undent pw)
-	    (.printMsg pw "return @( cs, null@ ) ;"
-		(list ident-mc (make-call-args #t num-params)))
-	    (.println pw "}"))))
-
-; Write a method for an exception that takes a cause.  The status is COMPLETED_NO. 
-;
-; exception:	the CORBA system exception type
-; id:		the identifier for this exception in the form ( ident . mixed-case-ident )
-; level:	the logging level
-; num-params:	number of parameters in the explanation string, which determines
-;		how many argn parameters we need
-; pw:		the indenting print writer we are using
-(define (write-method-cause exception id level num-params pw)
-    (let*
-	(
-	    (ident-mc (cdr id)))
-	(begin
-	    (.indent pw)
-	    (.printMsg pw "public @ @( Throwable t@) {"
-		(list exception ident-mc (make-decl-args #t num-params)))
-	    (.undent pw)
-	    (.printMsg pw "return @( CompletionStatus.COMPLETED_NO, t@ ) ;"
-		(list ident-mc (make-call-args #t num-params)))
-	    (.println pw "}"))))
-
-; Write a method for an exception that takes no arguments.  This is COMPLETED_NO and
-; a null cause.
-;
-; exception:	the CORBA system exception type
-; id:		the identifier for this exception in the form ( ident . mixed-case-ident )
-; level:	the logging level
-; num-params:	number of parameters in the explanation string, which determines
-;		how many argn parameters we need
-; pw:		the indenting print writer we are using
-(define (write-method-no-args exception id level num-params pw)
-    (let*
-	(
-	    (ident-mc (cdr id)))
-	(begin
-	    (.indent pw)
-	    (.printMsg pw "public @ @( @) {"
-		(list exception ident-mc (make-decl-args #f num-params)))
-	    (.undent pw)
-	    (.printMsg pw "return @( CompletionStatus.COMPLETED_NO, null@ ) ;"
-		(list ident-mc (make-call-args #t num-params)))
-	    (.println pw "}"))))
-
-;;; end of file
--- a/corba/src/share/classes/com/sun/tools/corba/se/logutil/scripts/run	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-#! /bin/sh
-java -cp ${CLASSPATH}:lib/jscheme.jar:lib/util.jar jscheme.REPL mc.scm
--- a/corba/src/share/classes/org/omg/CORBA/ir.idl	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/src/share/classes/org/omg/CORBA/ir.idl	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/corba/src/share/classes/org/omg/DynamicAny/DynamicAny.idl	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/src/share/classes/org/omg/DynamicAny/DynamicAny.idl	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/corba/src/windows/resource/version.rc	Mon Mar 09 15:32:10 2009 -0700
+++ b/corba/src/windows/resource/version.rc	Fri Apr 10 13:05:12 2009 -0700
@@ -23,7 +23,7 @@
 // have any questions.
 //
 
-#include "afxres.h"
+#include "windows.h"
 
 // Need 2 defines so macro argument to XSTR will get expanded before quoting.
 #define XSTR(x) STR(x)
--- a/hotspot/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 fcb923bad68e2b10380a030ea83a723f4dc3d4d6 jdk7-b47
 bcb33806d186561c781992e5f4d8a90bb033f9f0 jdk7-b48
 8b22ccb5aba2c6c11bddf6488a7bb7ef5b4bf2be jdk7-b49
+dae503d9f04c1a11e182dbf7f770509c28dc0609 jdk7-b50
+2581d90c6c9b2012da930eb4742add94a03069a0 jdk7-b51
+1b1e8f1a4fe8cebc01c022484f78148e17b62a0d jdk7-b52
+032c6af894dae8d939b3dd31d82042549e7793e0 jdk7-b53
--- a/hotspot/agent/src/os/linux/ps_core.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/os/linux/ps_core.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/agent/src/os/solaris/proc/saproc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/os/solaris/proc/saproc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/Debugger.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/Debugger.java	Fri Apr 10 13:05:12 2009 -0700
@@ -118,9 +118,9 @@
   public long getJIntSize();
   public long getJLongSize();
   public long getJShortSize();
-  public long getHeapBase();
   public long getHeapOopSize();
-  public long getLogMinObjAlignmentInBytes();
+  public long getNarrowOopBase();
+  public int  getNarrowOopShift();
 
   public ReadResult readBytesFromProcess(long address, long numBytes)
     throws DebuggerException;
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/DebuggerBase.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/DebuggerBase.java	Fri Apr 10 13:05:12 2009 -0700
@@ -56,8 +56,8 @@
   // heap data.
   protected long oopSize;
   protected long heapOopSize;
-  protected long heapBase;                 // heap base for compressed oops.
-  protected long logMinObjAlignmentInBytes; // Used to decode compressed oops.
+  protected long narrowOopBase;  // heap base for compressed oops.
+  protected int  narrowOopShift; // shift to decode compressed oops.
   // Should be initialized if desired by calling initCache()
   private PageCache cache;
 
@@ -159,10 +159,10 @@
     javaPrimitiveTypesConfigured = true;
   }
 
-  public void putHeapConst(long heapBase, long heapOopSize, long logMinObjAlignmentInBytes) {
-    this.heapBase = heapBase;
+  public void putHeapConst(long heapOopSize, long narrowOopBase, int narrowOopShift) {
     this.heapOopSize = heapOopSize;
-    this.logMinObjAlignmentInBytes = logMinObjAlignmentInBytes;
+    this.narrowOopBase = narrowOopBase;
+    this.narrowOopShift = narrowOopShift;
   }
 
   /** May be called by subclasses if desired to initialize the page
@@ -459,7 +459,7 @@
     long value = readCInteger(address, getHeapOopSize(), true);
     if (value != 0) {
       // See oop.inline.hpp decode_heap_oop
-      value = (long)(heapBase + (long)(value << logMinObjAlignmentInBytes));
+      value = (long)(narrowOopBase + (long)(value << narrowOopShift));
     }
     return value;
   }
@@ -545,10 +545,10 @@
     return heapOopSize;
   }
 
-  public long getHeapBase() {
-    return heapBase;
+  public long getNarrowOopBase() {
+    return narrowOopBase;
   }
-  public long getLogMinObjAlignmentInBytes() {
-    return logMinObjAlignmentInBytes;
+  public int getNarrowOopShift() {
+    return narrowOopShift;
   }
 }
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/JVMDebugger.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/JVMDebugger.java	Fri Apr 10 13:05:12 2009 -0700
@@ -42,5 +42,5 @@
                                               long jintSize,
                                               long jlongSize,
                                               long jshortSize);
-  public void putHeapConst(long heapBase, long heapOopSize, long logMinObjAlignment);
+  public void putHeapConst(long heapOopSize, long narrowOopBase, int narrowOopShift);
 }
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebugger.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebugger.java	Fri Apr 10 13:05:12 2009 -0700
@@ -65,9 +65,10 @@
   public long      getJIntSize() throws RemoteException;
   public long      getJLongSize() throws RemoteException;
   public long      getJShortSize() throws RemoteException;
-  public long      getHeapBase() throws RemoteException;
   public long      getHeapOopSize() throws RemoteException;
-  public long      getLogMinObjAlignmentInBytes() throws RemoteException;
+  public long      getNarrowOopBase() throws RemoteException;
+  public int       getNarrowOopShift() throws RemoteException;
+
   public boolean   areThreadsEqual(long addrOrId1, boolean isAddress1,
                                    long addrOrId2, boolean isAddress2) throws RemoteException;
   public int       getThreadHashCode(long addrOrId, boolean isAddress) throws RemoteException;
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebuggerClient.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebuggerClient.java	Fri Apr 10 13:05:12 2009 -0700
@@ -85,9 +85,9 @@
       jlongSize    = remoteDebugger.getJLongSize();
       jshortSize   = remoteDebugger.getJShortSize();
       javaPrimitiveTypesConfigured = true;
-      heapBase     = remoteDebugger.getHeapBase();
+      narrowOopBase  = remoteDebugger.getNarrowOopBase();
+      narrowOopShift = remoteDebugger.getNarrowOopShift();
       heapOopSize  = remoteDebugger.getHeapOopSize();
-      logMinObjAlignmentInBytes  = remoteDebugger.getLogMinObjAlignmentInBytes();
     }
     catch (RemoteException e) {
       throw new DebuggerException(e);
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebuggerServer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/remote/RemoteDebuggerServer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -114,17 +114,18 @@
     return debugger.getJShortSize();
   }
 
-  public long getHeapBase() throws RemoteException {
-    return debugger.getHeapBase();
-  }
-
   public long getHeapOopSize() throws RemoteException {
     return debugger.getHeapOopSize();
   }
 
-  public long getLogMinObjAlignmentInBytes() throws RemoteException {
-    return debugger.getLogMinObjAlignmentInBytes();
+  public long getNarrowOopBase() throws RemoteException {
+    return debugger.getNarrowOopBase();
   }
+
+  public int  getNarrowOopShift() throws RemoteException {
+    return debugger.getNarrowOopShift();
+  }
+
   public boolean   areThreadsEqual(long addrOrId1, boolean isAddress1,
                                    long addrOrId2, boolean isAddress2) throws RemoteException {
     ThreadProxy t1 = getThreadProxy(addrOrId1, isAddress1);
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/Universe.java	Fri Apr 10 13:05:12 2009 -0700
@@ -53,7 +53,8 @@
   // system obj array klass object
   private static sun.jvm.hotspot.types.OopField systemObjArrayKlassObjField;
 
-  private static AddressField heapBaseField;
+  private static AddressField narrowOopBaseField;
+  private static CIntegerField narrowOopShiftField;
 
   static {
     VM.registerVMInitializedObserver(new Observer() {
@@ -86,7 +87,8 @@
 
     systemObjArrayKlassObjField = type.getOopField("_systemObjArrayKlassObj");
 
-    heapBaseField = type.getAddressField("_heap_base");
+    narrowOopBaseField = type.getAddressField("_narrow_oop._base");
+    narrowOopShiftField = type.getCIntegerField("_narrow_oop._shift");
   }
 
   public Universe() {
@@ -100,14 +102,18 @@
     }
   }
 
-  public static long getHeapBase() {
-    if (heapBaseField.getValue() == null) {
+  public static long getNarrowOopBase() {
+    if (narrowOopBaseField.getValue() == null) {
       return 0;
     } else {
-      return heapBaseField.getValue().minus(null);
+      return narrowOopBaseField.getValue().minus(null);
     }
   }
 
+  public static int getNarrowOopShift() {
+    return (int)narrowOopShiftField.getValue();
+  }
+
   /** Returns "TRUE" iff "p" points into the allocated area of the heap. */
   public boolean isIn(Address p) {
     return heap().isIn(p);
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/StubRoutines.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/StubRoutines.java	Fri Apr 10 13:05:12 2009 -0700
@@ -46,12 +46,18 @@
     Type type = db.lookupType("StubRoutines");
 
     callStubReturnAddressField = type.getAddressField("_call_stub_return_address");
-    // Only some platforms have specif return from compiled to call_stub
+    // Only some platforms have specific return from compiled to call_stub
     try {
-      callStubCompiledReturnAddressField = type.getAddressField("_call_stub_compiled_return");
+      type = db.lookupType("StubRoutines::x86");
+      if (type != null) {
+        callStubCompiledReturnAddressField = type.getAddressField("_call_stub_compiled_return");
+      }
     } catch (RuntimeException re) {
       callStubCompiledReturnAddressField = null;
     }
+    if (callStubCompiledReturnAddressField == null && VM.getVM().getCPU().equals("x86")) {
+      throw new InternalError("Missing definition for _call_stub_compiled_return");
+    }
   }
 
   public StubRoutines() {
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Fri Apr 10 13:05:12 2009 -0700
@@ -342,11 +342,14 @@
       throw new RuntimeException("Attempt to initialize VM twice");
     }
     soleInstance = new VM(db, debugger, debugger.getMachineDescription().isBigEndian());
-    debugger.putHeapConst(Universe.getHeapBase(), soleInstance.getHeapOopSize(),
-                          soleInstance.logMinObjAlignmentInBytes);
+
+    debugger.putHeapConst(soleInstance.getHeapOopSize(), Universe.getNarrowOopBase(),
+                          Universe.getNarrowOopShift());
+
     for (Iterator iter = vmInitializedObservers.iterator(); iter.hasNext(); ) {
       ((Observer) iter.next()).update(null, null);
     }
+
   }
 
   /** This is used by the debugging system */
--- a/hotspot/make/hotspot_version	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/hotspot_version	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 # 
-# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -31,11 +31,11 @@
 #
 
 # Don't put quotes (fail windows build).
-HOTSPOT_VM_COPYRIGHT=Copyright 2008
+HOTSPOT_VM_COPYRIGHT=Copyright 2009
 
 HS_MAJOR_VER=15
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=02
+HS_BUILD_NUMBER=05
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=7
--- a/hotspot/make/jprt.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/jprt.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -19,12 +19,12 @@
 # Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
-#  
+#
 #
 
 # Properties for jprt
 
-# All build result bundles are full jdks, so the 64bit testing does not 
+# All build result bundles are full jdks, so the 64bit testing does not
 #    need the 32bit sibling bundle installed.
 #    Note: If the hotspot/make/Makefile changed to only bundle the 64bit files
 #          when bundling 64bit, and stripped out the 64bit files from any 32bit
@@ -89,60 +89,52 @@
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jvm98, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-scimark, \
     ${jprt.my.solaris.sparc}-product-{c1|c2}-runThese, \
-    ${jprt.my.solaris.sparc}-product-{c1|c2}-runThese_Xcomp, \
-    ${jprt.my.solaris.sparc}-product-{c1|c2}-runThese_Xcomp_2, \
-    ${jprt.my.solaris.sparc}-product-{c1|c2}-runThese_Xcomp_3, \
     ${jprt.my.solaris.sparc}-fastdebug-c1-runThese_Xshare, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_default_2, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC_2, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC_2, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC_2, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_CMS_2, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParNewGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_CMS, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_G1, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParOldGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_ParallelGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_CMS, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-scimark_2, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-scimark_3
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_G1, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_ParOldGC
 
 jprt.my.solaris.sparcv9.test.targets= \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jvm98, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-scimark, \
     ${jprt.my.solaris.sparcv9}-product-c2-runThese, \
-    ${jprt.my.solaris.sparcv9}-product-c2-runThese_Xcomp, \
-    ${jprt.my.solaris.sparcv9}-product-c2-runThese_Xcomp_2, \
-    ${jprt.my.solaris.sparcv9}-product-c2-runThese_Xcomp_3, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_CMS, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_default_2, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_SerialGC_2, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParallelGC_2, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParNewGC_2, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_CMS_2, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_G1, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_CMS, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_G1, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParOldGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_ParallelGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_CMS, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-scimark_2, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-scimark_3
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_G1, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_ParOldGC
 
 jprt.my.solaris.x64.test.targets= \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jvm98, \
@@ -154,73 +146,80 @@
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_default_2, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_SerialGC_2, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC_2, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC_2, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_CMS_2, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_G1, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_CMS, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_G1, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_SerialGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_ParallelGC, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_CMS
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_CMS, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_G1, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParOldGC
 
 jprt.my.solaris.i586.test.targets= \
     ${jprt.my.solaris.i586}-{product|fastdebug}-{c1|c2}-jvm98, \
     ${jprt.my.solaris.i586}-{product|fastdebug}-{c1|c2}-scimark, \
     ${jprt.my.solaris.i586}-product-{c1|c2}-runThese_Xcomp, \
-    ${jprt.my.solaris.i586}-product-c2-runThese_Xcomp_2, \
-    ${jprt.my.solaris.i586}-fastdebug-c1-runThese_Xcomp_2, \
+    ${jprt.my.solaris.i586}-fastdebug-c1-runThese_Xcomp, \
     ${jprt.my.solaris.i586}-fastdebug-c1-runThese_Xshare, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_default, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_SerialGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_ParallelGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_ParNewGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_CMS, \
+    ${jprt.my.solaris.i586}-product-c1-GCBasher_G1, \
+    ${jprt.my.solaris.i586}-product-c1-GCBasher_ParOldGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_default, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_SerialGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_CMS, \
+    ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_G1, \
+    ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParOldGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_default, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_SerialGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_ParallelGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_ParNewGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_CMS, \
+    ${jprt.my.solaris.i586}-product-c1-GCOld_G1, \
+    ${jprt.my.solaris.i586}-product-c1-GCOld_ParOldGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_default, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_ParallelGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_CMS, \
-    ${jprt.my.solaris.i586}-{product|fastdebug}-{c1|c2}-scimark_2, \
-    ${jprt.my.solaris.i586}-{product|fastdebug}-{c1|c2}-scimark_3
+    ${jprt.my.solaris.i586}-fastdebug-c2-jbb_G1, \
+    ${jprt.my.solaris.i586}-fastdebug-c2-jbb_ParOldGC
 
 jprt.my.linux.i586.test.targets = \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-jvm98, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-scimark, \
     ${jprt.my.linux.i586}-product-c1-runThese_Xcomp, \
-    ${jprt.my.linux.i586}-product-c1-runThese_Xcomp_2, \
-    ${jprt.my.linux.i586}-product-c1-runThese_Xcomp_3, \
     ${jprt.my.linux.i586}-fastdebug-c1-runThese_Xshare, \
     ${jprt.my.linux.i586}-fastdebug-c2-runThese_Xcomp, \
-    ${jprt.my.linux.i586}-fastdebug-c2-runThese_Xcomp_2, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_default, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
+    ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
+    ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_default, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParNewGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_CMS, \
+    ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_G1, \
+    ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParOldGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_default, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_ParallelGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_CMS, \
-    ${jprt.my.linux.i586}-{product|fastdebug}-c2-scimark_2, \
-    ${jprt.my.linux.i586}-{product|fastdebug}-c2-scimark_3
+    ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_G1, \
+    ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_ParOldGC
 
 jprt.my.linux.x64.test.targets = \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jvm98, \
@@ -230,15 +229,19 @@
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_G1, \
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_CMS, \
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_G1, \
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_ParallelGC, \
-    ${jprt.my.linux.x64}-{product|fastdebug}-c2-scimark_2, \
-    ${jprt.my.linux.x64}-{product|fastdebug}-c2-scimark_3
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_G1, \
+    ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_ParOldGC
 
 jprt.my.windows.i586.test.targets = \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-jvm98, \
@@ -251,16 +254,20 @@
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
+    ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
+    ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_default, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_ParNewGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_CMS, \
+    ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_G1, \
+    ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_ParOldGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-jbb_default, \
     ${jprt.my.windows.i586}-product-{c1|c2}-jbb_ParallelGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-jbb_CMS, \
-    ${jprt.my.windows.i586}-product-{c1|c2}-scimark_2, \
-    ${jprt.my.windows.i586}-product-{c1|c2}-scimark_3
+    ${jprt.my.windows.i586}-product-{c1|c2}-jbb_G1, \
+    ${jprt.my.windows.i586}-product-{c1|c2}-jbb_ParOldGC
 
 jprt.my.windows.x64.test.targets = \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-jvm98, \
@@ -272,16 +279,20 @@
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
+    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_G1, \
+    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_CMS, \
+    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_G1, \
+    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.windows.x64}-product-c2-jbb_CMS, \
     ${jprt.my.windows.x64}-product-c2-jbb_ParallelGC, \
-    ${jprt.my.windows.x64}-{product|fastdebug}-c2-scimark_2, \
-    ${jprt.my.windows.x64}-{product|fastdebug}-c2-scimark_3
+    ${jprt.my.windows.x64}-product-c2-jbb_G1, \
+    ${jprt.my.windows.x64}-product-c2-jbb_ParOldGC
 
 # The complete list of test targets for jprt
 
--- a/hotspot/make/linux/makefiles/adlc.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/linux/makefiles/adlc.make	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -61,8 +61,8 @@
 CPPFLAGS += -DASSERT
 
 # CFLAGS_WARN holds compiler options to suppress/enable warnings.
-# Suppress warnings (for now)
-CFLAGS_WARN = -w
+# Compiler warnings are treated as errors
+CFLAGS_WARN = -Werror
 CFLAGS += $(CFLAGS_WARN)
 
 OBJECTNAMES = \
--- a/hotspot/make/linux/makefiles/gcc.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/linux/makefiles/gcc.make	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -131,6 +131,14 @@
 # Enable linker optimization
 LFLAGS += -Xlinker -O1
 
+# If this is a --hash-style=gnu system, use --hash-style=both
+#   The gnu .hash section won't work on some Linux systems like SuSE 10.
+_HAS_HASH_STYLE_GNU:=$(shell $(CC) -dumpspecs | grep -- '--hash-style=gnu')
+ifneq ($(_HAS_HASH_STYLE_GNU),)
+  LDFLAGS_HASH_STYLE = -Wl,--hash-style=both
+endif
+LFLAGS += $(LDFLAGS_HASH_STYLE)
+
 # Use $(MAPFLAG:FILENAME=real_file_name) to specify a map file.
 MAPFLAG = -Xlinker --version-script=FILENAME
 
--- a/hotspot/make/solaris/makefiles/adlc.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/solaris/makefiles/adlc.make	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -67,6 +67,8 @@
 endif
 
 # CFLAGS_WARN holds compiler options to suppress/enable warnings.
+# Compiler warnings are treated as errors
+CFLAGS_WARN = +w -errwarn
 CFLAGS += $(CFLAGS_WARN)
 
 ifeq ("${Platform_compiler}", "sparcWorks")
--- a/hotspot/make/windows/build_vm_def.sh	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/build_vm_def.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -52,6 +52,19 @@
 RM="$MKS_HOME/rm.exe"
 DUMPBIN="link.exe /dump"
 
+# When called from IDE the first param should contain the link version, otherwise may be nill
+if [ "x$1" != "x" ]; then
+LINK_VER="$1"
+fi
+
+if [ "x$LINK_VER" != "x800" -a  "x$LINK_VER" != "x900" ]; then
 $DUMPBIN /symbols *.obj | "$GREP" "??_7.*@@6B@" | "$AWK" '{print $7}' | "$SORT" | "$UNIQ" > vm2.def
+else
+# Can't use pipes when calling cl.exe or link.exe from IDE. Using transit file vm3.def
+$DUMPBIN /OUT:vm3.def /symbols *.obj 
+"$CAT" vm3.def | "$GREP" "??_7.*@@6B@" | "$AWK" '{print $7}' | "$SORT" | "$UNIQ" > vm2.def
+"$RM" -f vm3.def
+fi
+
 "$CAT" vm1.def vm2.def > vm.def
 "$RM" -f vm1.def vm2.def
--- a/hotspot/make/windows/create.bat	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/create.bat	Fri Apr 10 13:05:12 2009 -0700
@@ -72,12 +72,20 @@
 for /F %%i in ('sh %HotSpotWorkSpace%/make/windows/get_msc_ver.sh') do set %%i
 
 echo **************************************************************
+set ProjectFile=vm.vcproj
 if "%MSC_VER%" == "1200" (
 set ProjectFile=vm.dsp
 echo Will generate VC6 project {unsupported}
 ) else (
-set ProjectFile=vm.vcproj
-echo Will generate VC7 project
+if "%MSC_VER%" == "1400" (
+echo Will generate VC8 {Visual Studio 2005}
+) else (
+if "%MSC_VER%" == "1500" (
+echo Will generate VC9 {Visual Studio 2008}
+) else (
+echo Will generate VC7 project {Visual Studio 2003 .NET}
+)
+)
 )
 echo                            %ProjectFile%
 echo **************************************************************
--- a/hotspot/make/windows/get_msc_ver.sh	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/get_msc_ver.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -29,6 +29,7 @@
 # cl version 13.10.3077 returns "MSC_VER=1310"
 # cl version 14.00.30701 returns "MSC_VER=1399" (OLD_MSSDK version)
 # cl version 14.00.40310.41 returns "MSC_VER=1400"
+# cl version 15.00.21022.8 returns "MSC_VER=1500"
 
 # Note that we currently do not have a way to set HotSpotMksHome in
 # the batch build, but so far this has not seemed to be a problem. The
--- a/hotspot/make/windows/makefiles/adlc.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/adlc.make	Fri Apr 10 13:05:12 2009 -0700
@@ -46,6 +46,7 @@
 ADLCFLAGS=-q -T -U_LP64
 !endif
 
+CPP_FLAGS=$(CPP_FLAGS) /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE  
 
 CPP_INCLUDE_DIRS=\
   /I "..\generated"                          \
--- a/hotspot/make/windows/makefiles/compile.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/compile.make	Fri Apr 10 13:05:12 2009 -0700
@@ -170,10 +170,6 @@
 # Manifest Tool - used in VS2005 and later to adjust manifests stored
 # as resources inside build artifacts.
 MT=mt.exe
-!if "$(BUILDARCH)" == "i486"
-# VS2005 on x86 restricts the use of certain libc functions without this
-CPP_FLAGS=$(CPP_FLAGS) /D _CRT_SECURE_NO_DEPRECATE
-!endif
 !endif
 
 !if "$(COMPILER_NAME)" == "VS2008"
@@ -185,10 +181,6 @@
 # Manifest Tool - used in VS2005 and later to adjust manifests stored
 # as resources inside build artifacts.
 MT=mt.exe
-!if "$(BUILDARCH)" == "i486"
-# VS2005 on x86 restricts the use of certain libc functions without this
-CPP_FLAGS=$(CPP_FLAGS) /D _CRT_SECURE_NO_DEPRECATE
-!endif
 !endif
 
 # Compile for space above time.
--- a/hotspot/make/windows/makefiles/makedeps.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/makedeps.make	Fri Apr 10 13:05:12 2009 -0700
@@ -48,6 +48,8 @@
         $(WorkSpace)\src\share\tools\MakeDeps\WinGammaPlatform.java \
         $(WorkSpace)\src\share\tools\MakeDeps\WinGammaPlatformVC6.java \
         $(WorkSpace)\src\share\tools\MakeDeps\WinGammaPlatformVC7.java \
+        $(WorkSpace)\src\share\tools\MakeDeps\WinGammaPlatformVC8.java \
+        $(WorkSpace)\src\share\tools\MakeDeps\WinGammaPlatformVC9.java \
         $(WorkSpace)\src\share\tools\MakeDeps\Util.java \
         $(WorkSpace)\src\share\tools\MakeDeps\BuildConfig.java \
         $(WorkSpace)\src\share\tools\MakeDeps\ArgsParser.java
@@ -121,7 +123,7 @@
         -additionalFile includeDB_gc_shared \
         -additionalFile includeDB_gc_serial \
         -additionalGeneratedFile $(HOTSPOTBUILDSPACE)\%f\%b vm.def \
-        -prelink  "" "Generating vm.def..." "cd $(HOTSPOTBUILDSPACE)\%f\%b	$(HOTSPOTMKSHOME)\sh $(HOTSPOTWORKSPACE)\make\windows\build_vm_def.sh" \
+        -prelink  "" "Generating vm.def..." "cd $(HOTSPOTBUILDSPACE)\%f\%b	set HOTSPOTMKSHOME=$(HOTSPOTMKSHOME)	$(HOTSPOTMKSHOME)\sh $(HOTSPOTWORKSPACE)\make\windows\build_vm_def.sh $(LINK_VER)" \
        $(MakeDepsIncludesPRIVATE)
 
 # Add in build-specific options
--- a/hotspot/make/windows/makefiles/rules.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/rules.make	Fri Apr 10 13:05:12 2009 -0700
@@ -42,10 +42,23 @@
 BOOT_JAVA_HOME=
 !endif
 
+ProjectFile=vm.vcproj
+
 !if "$(MSC_VER)" == "1200"
+
 VcVersion=VC6
 ProjectFile=vm.dsp
+
+!elseif "$(MSC_VER)" == "1400"
+
+VcVersion=VC8
+
+!elseif "$(MSC_VER)" == "1500"
+
+VcVersion=VC9
+
 !else
+
 VcVersion=VC7
-ProjectFile=vm.vcproj
+
 !endif
--- a/hotspot/make/windows/makefiles/sa.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/sa.make	Fri Apr 10 13:05:12 2009 -0700
@@ -89,9 +89,11 @@
 SA_CFLAGS = /nologo $(MS_RUNTIME_OPTION) /W3 $(GX_OPTION) /Od /D "WIN32" /D "WIN64" /D "_WINDOWS" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
 !elseif "$(BUILDARCH)" == "amd64"
 SA_CFLAGS = /nologo $(MS_RUNTIME_OPTION) /W3 $(GX_OPTION) /Od /D "WIN32" /D "WIN64" /D "_WINDOWS" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+!if "$(COMPILER_NAME)" == "VS2005"
 # On amd64, VS2005 compiler requires bufferoverflowU.lib on the link command line, 
 # otherwise we get missing __security_check_cookie externals at link time. 
 SA_LINK_FLAGS = bufferoverflowU.lib
+!endif
 !else
 SA_CFLAGS = /nologo $(MS_RUNTIME_OPTION) /W3 /Gm $(GX_OPTION) /ZI /Od /D "WIN32" /D "_WINDOWS" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
 !endif
--- a/hotspot/make/windows/makefiles/sanity.make	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/make/windows/makefiles/sanity.make	Fri Apr 10 13:05:12 2009 -0700
@@ -27,9 +27,9 @@
 all: checkCL checkLink
 
 checkCL:
-	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" \
+	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" \
 	echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)).  Use FORCE_MSC_VER to override automatic detection.
 
 checkLink:
-	@ if "$(LINK_VER)" NEQ "710" if "$(LINK_VER)" NEQ "800" \
+	@ if "$(LINK_VER)" NEQ "710" if "$(LINK_VER)" NEQ "800" if "$(LINK_VER)" NEQ "900" \
 	echo *** WARNING *** unrecognized link.exe version $(LINK_VER) ($(RAW_LINK_VER)).  Use FORCE_LINK_VER to override automatic detection.
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2615,6 +2615,420 @@
   }
 }
 
+RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
+                                                      Register tmp,
+                                                      int offset) {
+  intptr_t value = *delayed_value_addr;
+  if (value != 0)
+    return RegisterOrConstant(value + offset);
+
+  // load indirectly to solve generation ordering problem
+  Address a(tmp, (address) delayed_value_addr);
+  load_ptr_contents(a, tmp);
+
+#ifdef ASSERT
+  tst(tmp);
+  breakpoint_trap(zero, xcc);
+#endif
+
+  if (offset != 0)
+    add(tmp, offset, tmp);
+
+  return RegisterOrConstant(tmp);
+}
+
+
+void MacroAssembler::regcon_inc_ptr( RegisterOrConstant& dest, RegisterOrConstant src, Register temp ) {
+  assert(dest.register_or_noreg() != G0, "lost side effect");
+  if ((src.is_constant() && src.as_constant() == 0) ||
+      (src.is_register() && src.as_register() == G0)) {
+    // do nothing
+  } else if (dest.is_register()) {
+    add(dest.as_register(), ensure_rs2(src, temp), dest.as_register());
+  } else if (src.is_constant()) {
+    intptr_t res = dest.as_constant() + src.as_constant();
+    dest = RegisterOrConstant(res); // side effect seen by caller
+  } else {
+    assert(temp != noreg, "cannot handle constant += register");
+    add(src.as_register(), ensure_rs2(dest, temp), temp);
+    dest = RegisterOrConstant(temp); // side effect seen by caller
+  }
+}
+
+void MacroAssembler::regcon_sll_ptr( RegisterOrConstant& dest, RegisterOrConstant src, Register temp ) {
+  assert(dest.register_or_noreg() != G0, "lost side effect");
+  if (!is_simm13(src.constant_or_zero()))
+    src = (src.as_constant() & 0xFF);
+  if ((src.is_constant() && src.as_constant() == 0) ||
+      (src.is_register() && src.as_register() == G0)) {
+    // do nothing
+  } else if (dest.is_register()) {
+    sll_ptr(dest.as_register(), src, dest.as_register());
+  } else if (src.is_constant()) {
+    intptr_t res = dest.as_constant() << src.as_constant();
+    dest = RegisterOrConstant(res); // side effect seen by caller
+  } else {
+    assert(temp != noreg, "cannot handle constant <<= register");
+    set(dest.as_constant(), temp);
+    sll_ptr(temp, src, temp);
+    dest = RegisterOrConstant(temp); // side effect seen by caller
+  }
+}
+
+
+// Look up the method for a megamorphic invokeinterface call.
+// The target method is determined by <intf_klass, itable_index>.
+// The receiver klass is in recv_klass.
+// On success, the result will be in method_result, and execution falls through.
+// On failure, execution transfers to the given label.
+void MacroAssembler::lookup_interface_method(Register recv_klass,
+                                             Register intf_klass,
+                                             RegisterOrConstant itable_index,
+                                             Register method_result,
+                                             Register scan_temp,
+                                             Register sethi_temp,
+                                             Label& L_no_such_interface) {
+  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
+         "caller must use same register for non-constant itable index as for method");
+
+  // Compute start of first itableOffsetEntry (which is at the end of the vtable)
+  int vtable_base = instanceKlass::vtable_start_offset() * wordSize;
+  int scan_step   = itableOffsetEntry::size() * wordSize;
+  int vte_size    = vtableEntry::size() * wordSize;
+
+  lduw(recv_klass, instanceKlass::vtable_length_offset() * wordSize, scan_temp);
+  // %%% We should store the aligned, prescaled offset in the klassoop.
+  // Then the next several instructions would fold away.
+
+  int round_to_unit = ((HeapWordsPerLong > 1) ? BytesPerLong : 0);
+  int itb_offset = vtable_base;
+  if (round_to_unit != 0) {
+    // hoist first instruction of round_to(scan_temp, BytesPerLong):
+    itb_offset += round_to_unit - wordSize;
+  }
+  int itb_scale = exact_log2(vtableEntry::size() * wordSize);
+  sll(scan_temp, itb_scale,  scan_temp);
+  add(scan_temp, itb_offset, scan_temp);
+  if (round_to_unit != 0) {
+    // Round up to align_object_offset boundary
+    // see code for instanceKlass::start_of_itable!
+    // Was: round_to(scan_temp, BytesPerLong);
+    // Hoisted: add(scan_temp, BytesPerLong-1, scan_temp);
+    and3(scan_temp, -round_to_unit, scan_temp);
+  }
+  add(recv_klass, scan_temp, scan_temp);
+
+  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+  RegisterOrConstant itable_offset = itable_index;
+  regcon_sll_ptr(itable_offset, exact_log2(itableMethodEntry::size() * wordSize));
+  regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes());
+  add(recv_klass, ensure_rs2(itable_offset, sethi_temp), recv_klass);
+
+  // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
+  //   if (scan->interface() == intf) {
+  //     result = (klass + scan->offset() + itable_index);
+  //   }
+  // }
+  Label search, found_method;
+
+  for (int peel = 1; peel >= 0; peel--) {
+    // %%%% Could load both offset and interface in one ldx, if they were
+    // in the opposite order.  This would save a load.
+    ld_ptr(scan_temp, itableOffsetEntry::interface_offset_in_bytes(), method_result);
+
+    // Check that this entry is non-null.  A null entry means that
+    // the receiver class doesn't implement the interface, and wasn't the
+    // same as when the caller was compiled.
+    bpr(Assembler::rc_z, false, Assembler::pn, method_result, L_no_such_interface);
+    delayed()->cmp(method_result, intf_klass);
+
+    if (peel) {
+      brx(Assembler::equal,    false, Assembler::pt, found_method);
+    } else {
+      brx(Assembler::notEqual, false, Assembler::pn, search);
+      // (invert the test to fall through to found_method...)
+    }
+    delayed()->add(scan_temp, scan_step, scan_temp);
+
+    if (!peel)  break;
+
+    bind(search);
+  }
+
+  bind(found_method);
+
+  // Got a hit.
+  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+  // scan_temp[-scan_step] points to the vtable offset we need
+  ito_offset -= scan_step;
+  lduw(scan_temp, ito_offset, scan_temp);
+  ld_ptr(recv_klass, scan_temp, method_result);
+}
+
+
+void MacroAssembler::check_klass_subtype(Register sub_klass,
+                                         Register super_klass,
+                                         Register temp_reg,
+                                         Register temp2_reg,
+                                         Label& L_success) {
+  Label L_failure, L_pop_to_failure;
+  check_klass_subtype_fast_path(sub_klass, super_klass,
+                                temp_reg, temp2_reg,
+                                &L_success, &L_failure, NULL);
+  Register sub_2 = sub_klass;
+  Register sup_2 = super_klass;
+  if (!sub_2->is_global())  sub_2 = L0;
+  if (!sup_2->is_global())  sup_2 = L1;
+
+  save_frame_and_mov(0, sub_klass, sub_2, super_klass, sup_2);
+  check_klass_subtype_slow_path(sub_2, sup_2,
+                                L2, L3, L4, L5,
+                                NULL, &L_pop_to_failure);
+
+  // on success:
+  restore();
+  ba(false, L_success);
+  delayed()->nop();
+
+  // on failure:
+  bind(L_pop_to_failure);
+  restore();
+  bind(L_failure);
+}
+
+
+void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
+                                                   Register super_klass,
+                                                   Register temp_reg,
+                                                   Register temp2_reg,
+                                                   Label* L_success,
+                                                   Label* L_failure,
+                                                   Label* L_slow_path,
+                                        RegisterOrConstant super_check_offset,
+                                        Register instanceof_hack) {
+  int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_super_cache_offset_in_bytes());
+  int sco_offset = (klassOopDesc::header_size() * HeapWordSize +
+                    Klass::super_check_offset_offset_in_bytes());
+
+  bool must_load_sco  = (super_check_offset.constant_or_zero() == -1);
+  bool need_slow_path = (must_load_sco ||
+                         super_check_offset.constant_or_zero() == sco_offset);
+
+  assert_different_registers(sub_klass, super_klass, temp_reg);
+  if (super_check_offset.is_register()) {
+    assert_different_registers(sub_klass, super_klass,
+                               super_check_offset.as_register());
+  } else if (must_load_sco) {
+    assert(temp2_reg != noreg, "supply either a temp or a register offset");
+  }
+
+  Label L_fallthrough;
+  int label_nulls = 0;
+  if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
+  if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
+  if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
+  assert(label_nulls <= 1 || instanceof_hack != noreg ||
+         (L_slow_path == &L_fallthrough && label_nulls <= 2 && !need_slow_path),
+         "at most one NULL in the batch, usually");
+
+  // Support for the instanceof hack, which uses delay slots to
+  // set a destination register to zero or one.
+  bool do_bool_sets = (instanceof_hack != noreg);
+#define BOOL_SET(bool_value)                            \
+  if (do_bool_sets && bool_value >= 0)                  \
+    set(bool_value, instanceof_hack)
+#define DELAYED_BOOL_SET(bool_value)                    \
+  if (do_bool_sets && bool_value >= 0)                  \
+    delayed()->set(bool_value, instanceof_hack);        \
+  else delayed()->nop()
+  // Hacked ba(), which may only be used just before L_fallthrough.
+#define FINAL_JUMP(label, bool_value)                   \
+  if (&(label) == &L_fallthrough) {                     \
+    BOOL_SET(bool_value);                               \
+  } else {                                              \
+    ba((do_bool_sets && bool_value >= 0), label);       \
+    DELAYED_BOOL_SET(bool_value);                       \
+  }
+
+  // If the pointers are equal, we are done (e.g., String[] elements).
+  // This self-check enables sharing of secondary supertype arrays among
+  // non-primary types such as array-of-interface.  Otherwise, each such
+  // type would need its own customized SSA.
+  // We move this check to the front of the fast path because many
+  // type checks are in fact trivially successful in this manner,
+  // so we get a nicely predicted branch right at the start of the check.
+  cmp(super_klass, sub_klass);
+  brx(Assembler::equal, do_bool_sets, Assembler::pn, *L_success);
+  DELAYED_BOOL_SET(1);
+
+  // Check the supertype display:
+  if (must_load_sco) {
+    // The super check offset is always positive...
+    lduw(super_klass, sco_offset, temp2_reg);
+    super_check_offset = RegisterOrConstant(temp2_reg);
+  }
+  ld_ptr(sub_klass, super_check_offset, temp_reg);
+  cmp(super_klass, temp_reg);
+
+  // This check has worked decisively for primary supers.
+  // Secondary supers are sought in the super_cache ('super_cache_addr').
+  // (Secondary supers are interfaces and very deeply nested subtypes.)
+  // This works in the same check above because of a tricky aliasing
+  // between the super_cache and the primary super display elements.
+  // (The 'super_check_addr' can address either, as the case requires.)
+  // Note that the cache is updated below if it does not help us find
+  // what we need immediately.
+  // So if it was a primary super, we can just fail immediately.
+  // Otherwise, it's the slow path for us (no success at this point).
+
+  if (super_check_offset.is_register()) {
+    brx(Assembler::equal, do_bool_sets, Assembler::pn, *L_success);
+    delayed(); if (do_bool_sets)  BOOL_SET(1);
+    // if !do_bool_sets, sneak the next cmp into the delay slot:
+    cmp(super_check_offset.as_register(), sc_offset);
+
+    if (L_failure == &L_fallthrough) {
+      brx(Assembler::equal, do_bool_sets, Assembler::pt, *L_slow_path);
+      delayed()->nop();
+      BOOL_SET(0);  // fallthrough on failure
+    } else {
+      brx(Assembler::notEqual, do_bool_sets, Assembler::pn, *L_failure);
+      DELAYED_BOOL_SET(0);
+      FINAL_JUMP(*L_slow_path, -1);  // -1 => vanilla delay slot
+    }
+  } else if (super_check_offset.as_constant() == sc_offset) {
+    // Need a slow path; fast failure is impossible.
+    if (L_slow_path == &L_fallthrough) {
+      brx(Assembler::equal, do_bool_sets, Assembler::pt, *L_success);
+      DELAYED_BOOL_SET(1);
+    } else {
+      brx(Assembler::notEqual, false, Assembler::pn, *L_slow_path);
+      delayed()->nop();
+      FINAL_JUMP(*L_success, 1);
+    }
+  } else {
+    // No slow path; it's a fast decision.
+    if (L_failure == &L_fallthrough) {
+      brx(Assembler::equal, do_bool_sets, Assembler::pt, *L_success);
+      DELAYED_BOOL_SET(1);
+      BOOL_SET(0);
+    } else {
+      brx(Assembler::notEqual, do_bool_sets, Assembler::pn, *L_failure);
+      DELAYED_BOOL_SET(0);
+      FINAL_JUMP(*L_success, 1);
+    }
+  }
+
+  bind(L_fallthrough);
+
+#undef final_jump
+#undef bool_set
+#undef DELAYED_BOOL_SET
+#undef final_jump
+}
+
+
+void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
+                                                   Register super_klass,
+                                                   Register count_temp,
+                                                   Register scan_temp,
+                                                   Register scratch_reg,
+                                                   Register coop_reg,
+                                                   Label* L_success,
+                                                   Label* L_failure) {
+  assert_different_registers(sub_klass, super_klass,
+                             count_temp, scan_temp, scratch_reg, coop_reg);
+
+  Label L_fallthrough, L_loop;
+  int label_nulls = 0;
+  if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
+  if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
+  assert(label_nulls <= 1, "at most one NULL in the batch");
+
+  // a couple of useful fields in sub_klass:
+  int ss_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_supers_offset_in_bytes());
+  int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_super_cache_offset_in_bytes());
+
+  // Do a linear scan of the secondary super-klass chain.
+  // This code is rarely used, so simplicity is a virtue here.
+
+#ifndef PRODUCT
+  int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
+  inc_counter((address) pst_counter, count_temp, scan_temp);
+#endif
+
+  // We will consult the secondary-super array.
+  ld_ptr(sub_klass, ss_offset, scan_temp);
+
+  // Compress superclass if necessary.
+  Register search_key = super_klass;
+  bool decode_super_klass = false;
+  if (UseCompressedOops) {
+    if (coop_reg != noreg) {
+      encode_heap_oop_not_null(super_klass, coop_reg);
+      search_key = coop_reg;
+    } else {
+      encode_heap_oop_not_null(super_klass);
+      decode_super_klass = true; // scarce temps!
+    }
+    // The superclass is never null; it would be a basic system error if a null
+    // pointer were to sneak in here.  Note that we have already loaded the
+    // Klass::super_check_offset from the super_klass in the fast path,
+    // so if there is a null in that register, we are already in the afterlife.
+  }
+
+  // Load the array length.  (Positive movl does right thing on LP64.)
+  lduw(scan_temp, arrayOopDesc::length_offset_in_bytes(), count_temp);
+
+  // Check for empty secondary super list
+  tst(count_temp);
+
+  // Top of search loop
+  bind(L_loop);
+  br(Assembler::equal, false, Assembler::pn, *L_failure);
+  delayed()->add(scan_temp, heapOopSize, scan_temp);
+  assert(heapOopSize != 0, "heapOopSize should be initialized");
+
+  // Skip the array header in all array accesses.
+  int elem_offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
+  elem_offset -= heapOopSize;   // the scan pointer was pre-incremented also
+
+  // Load next super to check
+  if (UseCompressedOops) {
+    // Don't use load_heap_oop; we don't want to decode the element.
+    lduw(   scan_temp, elem_offset, scratch_reg );
+  } else {
+    ld_ptr( scan_temp, elem_offset, scratch_reg );
+  }
+
+  // Look for Rsuper_klass on Rsub_klass's secondary super-class-overflow list
+  cmp(scratch_reg, search_key);
+
+  // A miss means we are NOT a subtype and need to keep looping
+  brx(Assembler::notEqual, false, Assembler::pn, L_loop);
+  delayed()->deccc(count_temp); // decrement trip counter in delay slot
+
+  // Falling out the bottom means we found a hit; we ARE a subtype
+  if (decode_super_klass) decode_heap_oop(super_klass);
+
+  // Success.  Cache the super we found and proceed in triumph.
+  st_ptr(super_klass, sub_klass, sc_offset);
+
+  if (L_success != &L_fallthrough) {
+    ba(false, *L_success);
+    delayed()->nop();
+  }
+
+  bind(L_fallthrough);
+}
+
+
+
+
 void MacroAssembler::biased_locking_enter(Register obj_reg, Register mark_reg,
                                           Register temp_reg,
                                           Label& done, Label* slow_case,
@@ -3820,7 +4234,6 @@
 static jint num_ct_writes = 0;
 static jint num_ct_writes_filtered_in_hr = 0;
 static jint num_ct_writes_filtered_null = 0;
-static jint num_ct_writes_filtered_pop = 0;
 static G1CollectedHeap* g1 = NULL;
 
 static Thread* count_ct_writes(void* filter_val, void* new_val) {
@@ -3833,25 +4246,19 @@
     if (g1 == NULL) {
       g1 = G1CollectedHeap::heap();
     }
-    if ((HeapWord*)new_val < g1->popular_object_boundary()) {
-      Atomic::inc(&num_ct_writes_filtered_pop);
-    }
   }
   if ((num_ct_writes % 1000000) == 0) {
     jint num_ct_writes_filtered =
       num_ct_writes_filtered_in_hr +
-      num_ct_writes_filtered_null +
-      num_ct_writes_filtered_pop;
+      num_ct_writes_filtered_null;
 
     tty->print_cr("%d potential CT writes: %5.2f%% filtered\n"
-                  "   (%5.2f%% intra-HR, %5.2f%% null, %5.2f%% popular).",
+                  "   (%5.2f%% intra-HR, %5.2f%% null).",
                   num_ct_writes,
                   100.0*(float)num_ct_writes_filtered/(float)num_ct_writes,
                   100.0*(float)num_ct_writes_filtered_in_hr/
                   (float)num_ct_writes,
                   100.0*(float)num_ct_writes_filtered_null/
-                  (float)num_ct_writes,
-                  100.0*(float)num_ct_writes_filtered_pop/
                   (float)num_ct_writes);
   }
   return Thread::current();
@@ -4057,6 +4464,24 @@
   card_table_write(bs->byte_map_base, tmp, store_addr);
 }
 
+// Loading values by size and signed-ness
+void MacroAssembler::load_sized_value(Register s1, RegisterOrConstant s2, Register d,
+                                      int size_in_bytes, bool is_signed) {
+  switch (size_in_bytes ^ (is_signed ? -1 : 0)) {
+  case ~8:  // fall through:
+  case  8:  ld_long( s1, s2, d ); break;
+  case ~4:  ldsw(    s1, s2, d ); break;
+  case  4:  lduw(    s1, s2, d ); break;
+  case ~2:  ldsh(    s1, s2, d ); break;
+  case  2:  lduh(    s1, s2, d ); break;
+  case ~1:  ldsb(    s1, s2, d ); break;
+  case  1:  ldub(    s1, s2, d ); break;
+  default:  ShouldNotReachHere();
+  }
+}
+
+
+
 void MacroAssembler::load_klass(Register src_oop, Register klass) {
   // The number of bytes in this code is used by
   // MachCallDynamicJavaNode::ret_addr_offset()
@@ -4146,7 +4571,13 @@
 
 void MacroAssembler::encode_heap_oop(Register src, Register dst) {
   assert (UseCompressedOops, "must be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   verify_oop(src);
+  if (Universe::narrow_oop_base() == NULL) {
+    srlx(src, LogMinObjAlignmentInBytes, dst);
+    return;
+  }
   Label done;
   if (src == dst) {
     // optimize for frequent case src == dst
@@ -4168,26 +4599,39 @@
 
 void MacroAssembler::encode_heap_oop_not_null(Register r) {
   assert (UseCompressedOops, "must be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   verify_oop(r);
-  sub(r, G6_heapbase, r);
+  if (Universe::narrow_oop_base() != NULL)
+    sub(r, G6_heapbase, r);
   srlx(r, LogMinObjAlignmentInBytes, r);
 }
 
 void MacroAssembler::encode_heap_oop_not_null(Register src, Register dst) {
   assert (UseCompressedOops, "must be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   verify_oop(src);
-  sub(src, G6_heapbase, dst);
-  srlx(dst, LogMinObjAlignmentInBytes, dst);
+  if (Universe::narrow_oop_base() == NULL) {
+    srlx(src, LogMinObjAlignmentInBytes, dst);
+  } else {
+    sub(src, G6_heapbase, dst);
+    srlx(dst, LogMinObjAlignmentInBytes, dst);
+  }
 }
 
 // Same algorithm as oops.inline.hpp decode_heap_oop.
 void  MacroAssembler::decode_heap_oop(Register src, Register dst) {
   assert (UseCompressedOops, "must be compressed");
-  Label done;
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   sllx(src, LogMinObjAlignmentInBytes, dst);
-  bpr(rc_nz, true, Assembler::pt, dst, done);
-  delayed() -> add(dst, G6_heapbase, dst); // annuled if not taken
-  bind(done);
+  if (Universe::narrow_oop_base() != NULL) {
+    Label done;
+    bpr(rc_nz, true, Assembler::pt, dst, done);
+    delayed() -> add(dst, G6_heapbase, dst); // annuled if not taken
+    bind(done);
+  }
   verify_oop(dst);
 }
 
@@ -4196,8 +4640,11 @@
   // pd_code_size_limit.
   // Also do not verify_oop as this is called by verify_oop.
   assert (UseCompressedOops, "must be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   sllx(r, LogMinObjAlignmentInBytes, r);
-  add(r, G6_heapbase, r);
+  if (Universe::narrow_oop_base() != NULL)
+    add(r, G6_heapbase, r);
 }
 
 void  MacroAssembler::decode_heap_oop_not_null(Register src, Register dst) {
@@ -4205,14 +4652,17 @@
   // pd_code_size_limit.
   // Also do not verify_oop as this is called by verify_oop.
   assert (UseCompressedOops, "must be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
   sllx(src, LogMinObjAlignmentInBytes, dst);
-  add(dst, G6_heapbase, dst);
+  if (Universe::narrow_oop_base() != NULL)
+    add(dst, G6_heapbase, dst);
 }
 
 void MacroAssembler::reinit_heapbase() {
   if (UseCompressedOops) {
     // call indirectly to solve generation ordering problem
-    Address base(G6_heapbase, (address)Universe::heap_base_addr());
+    Address base(G6_heapbase, (address)Universe::narrow_oop_base_addr());
     load_ptr_contents(base, G6_heapbase);
   }
 }
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -384,6 +384,12 @@
 
   inline bool is_simm13(int offset = 0);  // check disp+offset for overflow
 
+  Address plus_disp(int disp) const {     // bump disp by a small amount
+    Address a = (*this);
+    a._disp += disp;
+    return a;
+  }
+
   Address split_disp() const {            // deal with disp overflow
     Address a = (*this);
     int hi_disp = _disp & ~0x3ff;
@@ -1082,7 +1088,8 @@
   inline void add(    Register s1, Register s2, Register d );
   inline void add(    Register s1, int simm13a, Register d, relocInfo::relocType rtype = relocInfo::none);
   inline void add(    Register s1, int simm13a, Register d, RelocationHolder const& rspec);
-  inline void add(    const Address&  a,              Register d, int offset = 0);
+  inline void add(    Register s1, RegisterOrConstant s2, Register d, int offset = 0);
+  inline void add(    const Address&  a,                  Register d, int offset = 0);
 
   void addcc(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
   void addcc(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
@@ -1298,6 +1305,16 @@
   inline void ld(   const Address& a, Register d, int offset = 0 );
   inline void ldd(  const Address& a, Register d, int offset = 0 );
 
+  inline void ldub(  Register s1, RegisterOrConstant s2, Register d );
+  inline void ldsb(  Register s1, RegisterOrConstant s2, Register d );
+  inline void lduh(  Register s1, RegisterOrConstant s2, Register d );
+  inline void ldsh(  Register s1, RegisterOrConstant s2, Register d );
+  inline void lduw(  Register s1, RegisterOrConstant s2, Register d );
+  inline void ldsw(  Register s1, RegisterOrConstant s2, Register d );
+  inline void ldx(   Register s1, RegisterOrConstant s2, Register d );
+  inline void ld(    Register s1, RegisterOrConstant s2, Register d );
+  inline void ldd(   Register s1, RegisterOrConstant s2, Register d );
+
   // pp 177
 
   void ldsba(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldsb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
@@ -1518,6 +1535,13 @@
   inline void st(   Register d, const Address& a, int offset = 0 );
   inline void std(  Register d, const Address& a, int offset = 0 );
 
+  inline void stb(  Register d, Register s1, RegisterOrConstant s2 );
+  inline void sth(  Register d, Register s1, RegisterOrConstant s2 );
+  inline void stw(  Register d, Register s1, RegisterOrConstant s2 );
+  inline void stx(  Register d, Register s1, RegisterOrConstant s2 );
+  inline void std(  Register d, Register s1, RegisterOrConstant s2 );
+  inline void st(   Register d, Register s1, RegisterOrConstant s2 );
+
   // pp 177
 
   void stba(  Register d, Register s1, Register s2, int ia ) {             emit_long( op(ldst_op) | rd(d) | op3(stb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
@@ -1835,6 +1859,7 @@
   // Functions for isolating 64 bit shifts for LP64
   inline void sll_ptr( Register s1, Register s2, Register d );
   inline void sll_ptr( Register s1, int imm6a,   Register d );
+  inline void sll_ptr( Register s1, RegisterOrConstant s2, Register d );
   inline void srl_ptr( Register s1, Register s2, Register d );
   inline void srl_ptr( Register s1, int imm6a,   Register d );
 
@@ -1940,20 +1965,47 @@
   // st_ptr will perform st for 32 bit VM's and stx for 64 bit VM's
   inline void ld_ptr(   Register s1, Register s2, Register d );
   inline void ld_ptr(   Register s1, int simm13a, Register d);
+  inline void ld_ptr(   Register s1, RegisterOrConstant s2, Register d );
   inline void ld_ptr(  const Address& a, Register d, int offset = 0 );
   inline void st_ptr(  Register d, Register s1, Register s2 );
   inline void st_ptr(  Register d, Register s1, int simm13a);
+  inline void st_ptr(  Register d, Register s1, RegisterOrConstant s2 );
   inline void st_ptr(  Register d, const Address& a, int offset = 0 );
 
   // ld_long will perform ld for 32 bit VM's and ldx for 64 bit VM's
   // st_long will perform st for 32 bit VM's and stx for 64 bit VM's
   inline void ld_long( Register s1, Register s2, Register d );
   inline void ld_long( Register s1, int simm13a, Register d );
+  inline void ld_long( Register s1, RegisterOrConstant s2, Register d );
   inline void ld_long( const Address& a, Register d, int offset = 0 );
   inline void st_long( Register d, Register s1, Register s2 );
   inline void st_long( Register d, Register s1, int simm13a );
+  inline void st_long( Register d, Register s1, RegisterOrConstant s2 );
   inline void st_long( Register d, const Address& a, int offset = 0 );
 
+  // Loading values by size and signed-ness
+  void load_sized_value(Register s1, RegisterOrConstant s2, Register d,
+                        int size_in_bytes, bool is_signed);
+
+  // Helpers for address formation.
+  // They update the dest in place, whether it is a register or constant.
+  // They emit no code at all if src is a constant zero.
+  // If dest is a constant and src is a register, the temp argument
+  // is required, and becomes the result.
+  // If dest is a register and src is a non-simm13 constant,
+  // the temp argument is required, and is used to materialize the constant.
+  void regcon_inc_ptr( RegisterOrConstant& dest, RegisterOrConstant src,
+                       Register temp = noreg );
+  void regcon_sll_ptr( RegisterOrConstant& dest, RegisterOrConstant src,
+                       Register temp = noreg );
+  RegisterOrConstant ensure_rs2(RegisterOrConstant rs2, Register sethi_temp) {
+    guarantee(sethi_temp != noreg, "constant offset overflow");
+    if (is_simm13(rs2.constant_or_zero()))
+      return rs2;               // register or short constant
+    set(rs2.as_constant(), sethi_temp);
+    return sethi_temp;
+  }
+
   // --------------------------------------------------
 
  public:
@@ -2267,6 +2319,54 @@
   );
   void tlab_refill(Label& retry_tlab, Label& try_eden, Label& slow_case);
 
+  // interface method calling
+  void lookup_interface_method(Register recv_klass,
+                               Register intf_klass,
+                               RegisterOrConstant itable_index,
+                               Register method_result,
+                               Register temp_reg, Register temp2_reg,
+                               Label& no_such_interface);
+
+  // Test sub_klass against super_klass, with fast and slow paths.
+
+  // The fast path produces a tri-state answer: yes / no / maybe-slow.
+  // One of the three labels can be NULL, meaning take the fall-through.
+  // If super_check_offset is -1, the value is loaded up from super_klass.
+  // No registers are killed, except temp_reg and temp2_reg.
+  // If super_check_offset is not -1, temp2_reg is not used and can be noreg.
+  void check_klass_subtype_fast_path(Register sub_klass,
+                                     Register super_klass,
+                                     Register temp_reg,
+                                     Register temp2_reg,
+                                     Label* L_success,
+                                     Label* L_failure,
+                                     Label* L_slow_path,
+                RegisterOrConstant super_check_offset = RegisterOrConstant(-1),
+                Register instanceof_hack = noreg);
+
+  // The rest of the type check; must be wired to a corresponding fast path.
+  // It does not repeat the fast path logic, so don't use it standalone.
+  // The temp_reg can be noreg, if no temps are available.
+  // It can also be sub_klass or super_klass, meaning it's OK to kill that one.
+  // Updates the sub's secondary super cache as necessary.
+  void check_klass_subtype_slow_path(Register sub_klass,
+                                     Register super_klass,
+                                     Register temp_reg,
+                                     Register temp2_reg,
+                                     Register temp3_reg,
+                                     Register temp4_reg,
+                                     Label* L_success,
+                                     Label* L_failure);
+
+  // Simplified, combined version, good for typical uses.
+  // Falls through on failure.
+  void check_klass_subtype(Register sub_klass,
+                           Register super_klass,
+                           Register temp_reg,
+                           Register temp2_reg,
+                           Label& L_success);
+
+
   // Stack overflow checking
 
   // Note: this clobbers G3_scratch
@@ -2281,6 +2381,8 @@
   // stack overflow + shadow pages.  Clobbers tsp and scratch registers.
   void bang_stack_size(Register Rsize, Register Rtsp, Register Rscratch);
 
+  virtual RegisterOrConstant delayed_value_impl(intptr_t* delayed_value_addr, Register tmp, int offset);
+
   void verify_tlab();
 
   Condition negate_condition(Condition cond);
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -143,6 +143,49 @@
 inline void Assembler::ld(  Register s1, int simm13a, Register d) { lduw( s1, simm13a, d); }
 #endif
 
+inline void Assembler::ldub(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsb(s1, s2.as_register(), d);
+  else                   ldsb(s1, s2.as_constant(), d);
+}
+inline void Assembler::ldsb(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsb(s1, s2.as_register(), d);
+  else                   ldsb(s1, s2.as_constant(), d);
+}
+inline void Assembler::lduh(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsh(s1, s2.as_register(), d);
+  else                   ldsh(s1, s2.as_constant(), d);
+}
+inline void Assembler::ldsh(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsh(s1, s2.as_register(), d);
+  else                   ldsh(s1, s2.as_constant(), d);
+}
+inline void Assembler::lduw(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsw(s1, s2.as_register(), d);
+  else                   ldsw(s1, s2.as_constant(), d);
+}
+inline void Assembler::ldsw(  Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldsw(s1, s2.as_register(), d);
+  else                   ldsw(s1, s2.as_constant(), d);
+}
+inline void Assembler::ldx(   Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldx(s1, s2.as_register(), d);
+  else                   ldx(s1, s2.as_constant(), d);
+}
+inline void Assembler::ld(    Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ld(s1, s2.as_register(), d);
+  else                   ld(s1, s2.as_constant(), d);
+}
+inline void Assembler::ldd(   Register s1, RegisterOrConstant s2, Register d) {
+  if (s2.is_register())  ldd(s1, s2.as_register(), d);
+  else                   ldd(s1, s2.as_constant(), d);
+}
+
+// form effective addresses this way:
+inline void Assembler::add(   Register s1, RegisterOrConstant s2, Register d, int offset) {
+  if (s2.is_register())  add(s1, s2.as_register(), d);
+  else                 { add(s1, s2.as_constant() + offset, d); offset = 0; }
+  if (offset != 0)       add(d,  offset,                    d);
+}
 
 inline void Assembler::ld(   const Address& a, Register d, int offset ) { relocate(a.rspec(offset)); ld(   a.base(), a.disp() + offset, d ); }
 inline void Assembler::ldsb( const Address& a, Register d, int offset ) { relocate(a.rspec(offset)); ldsb( a.base(), a.disp() + offset, d ); }
@@ -200,6 +243,27 @@
 inline void Assembler::st(  Register d, Register s1, Register s2) { stw(d, s1, s2); }
 inline void Assembler::st(  Register d, Register s1, int simm13a) { stw(d, s1, simm13a); }
 
+inline void Assembler::stb(  Register d, Register s1, RegisterOrConstant s2) {
+  if (s2.is_register())  stb(d, s1, s2.as_register());
+  else                   stb(d, s1, s2.as_constant());
+}
+inline void Assembler::sth(  Register d, Register s1, RegisterOrConstant s2) {
+  if (s2.is_register())  sth(d, s1, s2.as_register());
+  else                   sth(d, s1, s2.as_constant());
+}
+inline void Assembler::stx(  Register d, Register s1, RegisterOrConstant s2) {
+  if (s2.is_register())  stx(d, s1, s2.as_register());
+  else                   stx(d, s1, s2.as_constant());
+}
+inline void Assembler::std( Register d, Register s1, RegisterOrConstant s2) {
+  if (s2.is_register())  std(d, s1, s2.as_register());
+  else                   std(d, s1, s2.as_constant());
+}
+inline void Assembler::st(  Register d, Register s1, RegisterOrConstant s2) {
+  if (s2.is_register())  st(d, s1, s2.as_register());
+  else                   st(d, s1, s2.as_constant());
+}
+
 inline void Assembler::stb( Register d, const Address& a, int offset) { relocate(a.rspec(offset)); stb( d, a.base(), a.disp() + offset); }
 inline void Assembler::sth( Register d, const Address& a, int offset) { relocate(a.rspec(offset)); sth( d, a.base(), a.disp() + offset); }
 inline void Assembler::stw( Register d, const Address& a, int offset) { relocate(a.rspec(offset)); stw( d, a.base(), a.disp() + offset); }
@@ -244,6 +308,14 @@
 #endif
 }
 
+inline void MacroAssembler::ld_ptr( Register s1, RegisterOrConstant s2, Register d ) {
+#ifdef _LP64
+  Assembler::ldx( s1, s2, d);
+#else
+  Assembler::ld(  s1, s2, d);
+#endif
+}
+
 inline void MacroAssembler::ld_ptr( const Address& a, Register d, int offset ) {
 #ifdef _LP64
   Assembler::ldx(  a, d, offset );
@@ -268,6 +340,14 @@
 #endif
 }
 
+inline void MacroAssembler::st_ptr( Register d, Register s1, RegisterOrConstant s2 ) {
+#ifdef _LP64
+  Assembler::stx( d, s1, s2);
+#else
+  Assembler::st( d, s1, s2);
+#endif
+}
+
 inline void MacroAssembler::st_ptr(  Register d, const Address& a, int offset) {
 #ifdef _LP64
   Assembler::stx(  d, a, offset);
@@ -293,6 +373,14 @@
 #endif
 }
 
+inline void MacroAssembler::ld_long( Register s1, RegisterOrConstant s2, Register d ) {
+#ifdef _LP64
+  Assembler::ldx(s1, s2, d);
+#else
+  Assembler::ldd(s1, s2, d);
+#endif
+}
+
 inline void MacroAssembler::ld_long( const Address& a, Register d, int offset ) {
 #ifdef _LP64
   Assembler::ldx(a, d, offset );
@@ -317,6 +405,14 @@
 #endif
 }
 
+inline void MacroAssembler::st_long( Register d, Register s1, RegisterOrConstant s2 ) {
+#ifdef _LP64
+  Assembler::stx(d, s1, s2);
+#else
+  Assembler::std(d, s1, s2);
+#endif
+}
+
 inline void MacroAssembler::st_long( Register d, const Address& a, int offset ) {
 #ifdef _LP64
   Assembler::stx(d, a, offset);
@@ -359,6 +455,11 @@
 #endif
 }
 
+inline void MacroAssembler::sll_ptr( Register s1, RegisterOrConstant s2, Register d ) {
+  if (s2.is_register())  sll_ptr(s1, s2.as_register(), d);
+  else                   sll_ptr(s1, s2.as_constant(), d);
+}
+
 // Use the right branch for the platform
 
 inline void MacroAssembler::br( Condition c, bool a, Predict p, address d, relocInfo::relocType rt ) {
--- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2393,23 +2393,11 @@
 
     // get instance klass
     load(k_RInfo, objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc), k_RInfo, T_OBJECT, NULL);
-    // get super_check_offset
-    load(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes(), Rtmp1, T_INT, NULL);
-    // See if we get an immediate positive hit
-    __ ld_ptr(klass_RInfo, Rtmp1, FrameMap::O7_oop_opr->as_register());
-    __ cmp(k_RInfo, O7);
-    __ br(Assembler::equal, false, Assembler::pn, done);
-    __ delayed()->nop();
-    // check for immediate negative hit
-    __ cmp(Rtmp1, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-    __ br(Assembler::notEqual, false, Assembler::pn, *stub->entry());
-    __ delayed()->nop();
-    // check for self
-    __ cmp(klass_RInfo, k_RInfo);
-    __ br(Assembler::equal, false, Assembler::pn, done);
-    __ delayed()->nop();
-
-    // assert(sub.is_same(FrameMap::G3_RInfo) && super.is_same(FrameMap::G1_RInfo), "incorrect call setup");
+    // perform the fast part of the checking logic
+    __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, O7, &done, stub->entry(), NULL);
+
+    // call out-of-line instance of __ check_klass_subtype_slow_path(...):
+    assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
     __ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
     __ delayed()->nop();
     __ cmp(G3, 0);
@@ -2493,58 +2481,30 @@
       __ delayed()->nop();
       __ bind(done);
     } else {
+      bool need_slow_path = true;
       if (k->is_loaded()) {
-        load(klass_RInfo, k->super_check_offset(), Rtmp1, T_OBJECT, NULL);
-
-        if (sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() != k->super_check_offset()) {
-          // See if we get an immediate positive hit
-          __ cmp(Rtmp1, k_RInfo );
-          __ br(Assembler::notEqual, false, Assembler::pn, *stub->entry());
-          __ delayed()->nop();
-        } else {
-          // See if we get an immediate positive hit
-          assert_different_registers(Rtmp1, k_RInfo, klass_RInfo);
-          __ cmp(Rtmp1, k_RInfo );
-          __ br(Assembler::equal, false, Assembler::pn, done);
-          // check for self
-          __ delayed()->cmp(klass_RInfo, k_RInfo);
-          __ br(Assembler::equal, false, Assembler::pn, done);
-          __ delayed()->nop();
-
-          // assert(sub.is_same(FrameMap::G3_RInfo) && super.is_same(FrameMap::G1_RInfo), "incorrect call setup");
-          __ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
-          __ delayed()->nop();
-          __ cmp(G3, 0);
-          __ br(Assembler::equal, false, Assembler::pn, *stub->entry());
-          __ delayed()->nop();
-        }
-        __ bind(done);
+        if (k->super_check_offset() != sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes())
+          need_slow_path = false;
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, noreg,
+                                         (need_slow_path ? &done : NULL),
+                                         stub->entry(), NULL,
+                                         RegisterOrConstant(k->super_check_offset()));
       } else {
-        assert_different_registers(Rtmp1, klass_RInfo, k_RInfo);
-
-        load(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes(), Rtmp1, T_INT, NULL);
-        // See if we get an immediate positive hit
-        load(klass_RInfo, Rtmp1, FrameMap::O7_oop_opr, T_OBJECT);
-        __ cmp(k_RInfo, O7);
-        __ br(Assembler::equal, false, Assembler::pn, done);
-        __ delayed()->nop();
-        // check for immediate negative hit
-        __ cmp(Rtmp1, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-        __ br(Assembler::notEqual, false, Assembler::pn, *stub->entry());
-        // check for self
-        __ delayed()->cmp(klass_RInfo, k_RInfo);
-        __ br(Assembler::equal, false, Assembler::pn, done);
-        __ delayed()->nop();
-
-        // assert(sub.is_same(FrameMap::G3_RInfo) && super.is_same(FrameMap::G1_RInfo), "incorrect call setup");
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, O7,
+                                         &done, stub->entry(), NULL);
+      }
+      if (need_slow_path) {
+        // call out-of-line instance of __ check_klass_subtype_slow_path(...):
+        assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
         __ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
         __ delayed()->nop();
         __ cmp(G3, 0);
         __ br(Assembler::equal, false, Assembler::pn, *stub->entry());
         __ delayed()->nop();
-        __ bind(done);
       }
-
+      __ bind(done);
     }
     __ mov(obj, dst);
   } else if (code == lir_instanceof) {
@@ -2582,58 +2542,32 @@
       __ set(0, dst);
       __ bind(done);
     } else {
+      bool need_slow_path = true;
       if (k->is_loaded()) {
-        assert_different_registers(Rtmp1, klass_RInfo, k_RInfo);
-        load(klass_RInfo, k->super_check_offset(), Rtmp1, T_OBJECT, NULL);
-
-        if (sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() != k->super_check_offset()) {
-          // See if we get an immediate positive hit
-          __ cmp(Rtmp1, k_RInfo );
-          __ br(Assembler::equal, true, Assembler::pt, done);
-          __ delayed()->set(1, dst);
-          __ set(0, dst);
-          __ bind(done);
-        } else {
-          // See if we get an immediate positive hit
-          assert_different_registers(Rtmp1, k_RInfo, klass_RInfo);
-          __ cmp(Rtmp1, k_RInfo );
-          __ br(Assembler::equal, true, Assembler::pt, done);
-          __ delayed()->set(1, dst);
-          // check for self
-          __ cmp(klass_RInfo, k_RInfo);
-          __ br(Assembler::equal, true, Assembler::pt, done);
-          __ delayed()->set(1, dst);
-
-          // assert(sub.is_same(FrameMap::G3_RInfo) && super.is_same(FrameMap::G1_RInfo), "incorrect call setup");
-          __ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
-          __ delayed()->nop();
-          __ mov(G3, dst);
-          __ bind(done);
-        }
+        if (k->super_check_offset() != sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes())
+          need_slow_path = false;
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, O7, noreg,
+                                         (need_slow_path ? &done : NULL),
+                                         (need_slow_path ? &done : NULL), NULL,
+                                         RegisterOrConstant(k->super_check_offset()),
+                                         dst);
       } else {
         assert(dst != klass_RInfo && dst != k_RInfo, "need 3 registers");
-
-        load(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes(), dst, T_INT, NULL);
-        // See if we get an immediate positive hit
-        load(klass_RInfo, dst, FrameMap::O7_oop_opr, T_OBJECT);
-        __ cmp(k_RInfo, O7);
-        __ br(Assembler::equal, true, Assembler::pt, done);
-        __ delayed()->set(1, dst);
-        // check for immediate negative hit
-        __ cmp(dst, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-        __ br(Assembler::notEqual, true, Assembler::pt, done);
-        __ delayed()->set(0, dst);
-        // check for self
-        __ cmp(klass_RInfo, k_RInfo);
-        __ br(Assembler::equal, true, Assembler::pt, done);
-        __ delayed()->set(1, dst);
-
-        // assert(sub.is_same(FrameMap::G3_RInfo) && super.is_same(FrameMap::G1_RInfo), "incorrect call setup");
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, O7, dst,
+                                         &done, &done, NULL,
+                                         RegisterOrConstant(-1),
+                                         dst);
+      }
+      if (need_slow_path) {
+        // call out-of-line instance of __ check_klass_subtype_slow_path(...):
+        assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
         __ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
         __ delayed()->nop();
         __ mov(G3, dst);
-        __ bind(done);
       }
+      __ bind(done);
     }
   } else {
     ShouldNotReachHere();
--- a/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -714,38 +714,19 @@
         //      sub  : G3, argument, destroyed
         //      super: G1, argument, not changed
         //      raddr: O7, blown by call
-        Label loop, miss;
+        Label miss;
 
         __ save_frame(0);               // Blow no registers!
 
-        __ ld_ptr( G3, sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes(), L3 );
-        __ lduw(L3,arrayOopDesc::length_offset_in_bytes(),L0); // length in l0
-        __ add(L3,arrayOopDesc::base_offset_in_bytes(T_OBJECT),L1); // ptr into array
-        __ clr(L4);                     // Index
-        // Load a little early; will load 1 off the end of the array.
-        // Ok for now; revisit if we have other uses of this routine.
-        __ ld_ptr(L1,0,L2);             // Will load a little early
-
-        // The scan loop
-        __ bind(loop);
-        __ add(L1,wordSize,L1); // Bump by OOP size
-        __ cmp(L4,L0);
-        __ br(Assembler::equal,false,Assembler::pn,miss);
-        __ delayed()->inc(L4);  // Bump index
-        __ subcc(L2,G1,L3);             // Check for match; zero in L3 for a hit
-        __ brx( Assembler::notEqual, false, Assembler::pt, loop );
-        __ delayed()->ld_ptr(L1,0,L2); // Will load a little early
-
-        // Got a hit; report success; set cache
-        __ st_ptr( G1, G3, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() );
+        __ check_klass_subtype_slow_path(G3, G1, L0, L1, L2, L4, NULL, &miss);
 
         __ mov(1, G3);
-        __ ret();                       // Result in G5 is ok; flags set
+        __ ret();                       // Result in G5 is 'true'
         __ delayed()->restore();        // free copy or add can go here
 
         __ bind(miss);
         __ mov(0, G3);
-        __ ret();                       // Result in G5 is ok; flags set
+        __ ret();                       // Result in G5 is 'false'
         __ delayed()->restore();        // free copy or add can go here
       }
 
--- a/hotspot/src/cpu/sparc/vm/globals_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/globals_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -46,6 +46,7 @@
 define_pd_global(uintx, NewSize, ScaleForWordSize((2048 * K) + (2 * (64 * K))));
 define_pd_global(intx,  SurvivorRatio,         8);
 define_pd_global(intx,  InlineFrequencyCount,  50);  // we can use more inlining on the SPARC
+define_pd_global(intx,  InlineSmallCode,       1500);
 #ifdef _LP64
 // Stack slots are 2X larger in LP64 than in the 32 bit VM.
 define_pd_global(intx,  ThreadStackSize,       1024);
--- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -866,65 +866,18 @@
                                                   Register Rtmp2,
                                                   Register Rtmp3,
                                                   Label &ok_is_subtype ) {
-  Label not_subtype, loop;
+  Label not_subtype;
 
   // Profile the not-null value's klass.
   profile_typecheck(Rsub_klass, Rtmp1);
 
-  // Load the super-klass's check offset into Rtmp1
-  ld( Rsuper_klass, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes(), Rtmp1 );
-  // Load from the sub-klass's super-class display list, or a 1-word cache of
-  // the secondary superclass list, or a failing value with a sentinel offset
-  // if the super-klass is an interface or exceptionally deep in the Java
-  // hierarchy and we have to scan the secondary superclass list the hard way.
-  ld_ptr( Rsub_klass, Rtmp1, Rtmp2 );
-  // See if we get an immediate positive hit
-  cmp( Rtmp2, Rsuper_klass );
-  brx( Assembler::equal, false, Assembler::pt, ok_is_subtype );
-  // In the delay slot, check for immediate negative hit
-  delayed()->cmp( Rtmp1, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() );
-  br( Assembler::notEqual, false, Assembler::pt, not_subtype );
-  // In the delay slot, check for self
-  delayed()->cmp( Rsub_klass, Rsuper_klass );
-  brx( Assembler::equal, false, Assembler::pt, ok_is_subtype );
-
-  // Now do a linear scan of the secondary super-klass chain.
-  delayed()->ld_ptr( Rsub_klass, sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes(), Rtmp2 );
-
-  // compress superclass
-  if (UseCompressedOops) encode_heap_oop(Rsuper_klass);
-
-  // Rtmp2 holds the objArrayOop of secondary supers.
-  ld( Rtmp2, arrayOopDesc::length_offset_in_bytes(), Rtmp1 );// Load the array length
-  // Check for empty secondary super list
-  tst(Rtmp1);
-
-  // Top of search loop
-  bind( loop );
-  br( Assembler::equal, false, Assembler::pn, not_subtype );
-  delayed()->nop();
-
-  // load next super to check
-  if (UseCompressedOops) {
-    lduw( Rtmp2, arrayOopDesc::base_offset_in_bytes(T_OBJECT), Rtmp3);
-    // Bump array pointer forward one oop
-    add( Rtmp2, 4, Rtmp2 );
-  } else {
-    ld_ptr( Rtmp2, arrayOopDesc::base_offset_in_bytes(T_OBJECT), Rtmp3);
-    // Bump array pointer forward one oop
-    add( Rtmp2, wordSize, Rtmp2);
-  }
-  // Look for Rsuper_klass on Rsub_klass's secondary super-class-overflow list
-  cmp( Rtmp3, Rsuper_klass );
-  // A miss means we are NOT a subtype and need to keep looping
-  brx( Assembler::notEqual, false, Assembler::pt, loop );
-  delayed()->deccc( Rtmp1 );    // dec trip counter in delay slot
-  // Falling out the bottom means we found a hit; we ARE a subtype
-  if (UseCompressedOops) decode_heap_oop(Rsuper_klass);
-  br( Assembler::always, false, Assembler::pt, ok_is_subtype );
-  // Update the cache
-  delayed()->st_ptr( Rsuper_klass, Rsub_klass,
-                     sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() );
+  check_klass_subtype_fast_path(Rsub_klass, Rsuper_klass,
+                                Rtmp1, Rtmp2,
+                                &ok_is_subtype, &not_subtype, NULL);
+
+  check_klass_subtype_slow_path(Rsub_klass, Rsuper_klass,
+                                Rtmp1, Rtmp2, Rtmp3, /*hack:*/ noreg,
+                                &ok_is_subtype, NULL);
 
   bind(not_subtype);
   profile_typecheck_failed(Rtmp1);
@@ -2465,7 +2418,10 @@
 //   InterpreterRuntime::post_method_entry();
 // }
 // if (DTraceMethodProbes) {
-//   SharedRuntime::dtrace_method_entry(method, reciever);
+//   SharedRuntime::dtrace_method_entry(method, receiver);
+// }
+// if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+//   SharedRuntime::rc_trace_method_entry(method, receiver);
 // }
 
 void InterpreterMacroAssembler::notify_method_entry() {
@@ -2497,6 +2453,13 @@
       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
       G2_thread, Lmethod);
   }
+
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    call_VM_leaf(noreg,
+      CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+      G2_thread, Lmethod);
+  }
 }
 
 
--- a/hotspot/src/cpu/sparc/vm/jni_sparc.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/jni_sparc.h	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -243,7 +243,7 @@
 
   // Regenerate the instruction sequence that performs the 64 bit
   // sethi.  This only does the sethi.  The disp field (bottom 10 bits)
-  // must be handled seperately.
+  // must be handled separately.
   static void set_data64_sethi(address instaddr, intptr_t x);
 
   // combine the fields of a sethi/simm13 pair (simm13 = or, add, jmpl, ld/st)
--- a/hotspot/src/cpu/sparc/vm/sharedRuntime_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/sharedRuntime_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -2161,6 +2161,18 @@
     __ restore();
   }
 
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    // create inner frame
+    __ save_frame(0);
+    __ mov(G2_thread, L7_thread_cache);
+    __ set_oop_constant(JNIHandles::make_local(method()), O1);
+    __ call_VM_leaf(L7_thread_cache,
+         CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+         G2_thread, O1);
+    __ restore();
+  }
+
   // We are in the jni frame unless saved_frame is true in which case
   // we are in one frame deeper (the "inner" frame). If we are in the
   // "inner" frames the args are in the Iregs and if the jni frame then
--- a/hotspot/src/cpu/sparc/vm/sparc.ad	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/sparc.ad	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -189,7 +189,7 @@
 // double fp register numbers.  FloatRegisterImpl in register_sparc.hpp
 // wants 0-63, so we have to convert every time we want to use fp regs
 // with the macroassembler, using reg_to_DoubleFloatRegister_object().
-// 255 is a flag meaning 'dont go here'.
+// 255 is a flag meaning "don't go here".
 // I believe we can't handle callee-save doubles D32 and up until
 // the place in the sparc stack crawler that asserts on the 255 is
 // fixed up.
@@ -462,7 +462,7 @@
 
 // Macros to extract hi & lo halves from a long pair.
 // G0 is not part of any long pair, so assert on that.
-// Prevents accidently using G1 instead of G0.
+// Prevents accidentally using G1 instead of G0.
 #define LONG_HI_REG(x) (x)
 #define LONG_LO_REG(x) (x)
 
@@ -547,7 +547,11 @@
     int v_off = entry_offset*wordSize + vtableEntry::method_offset_in_bytes();
     int klass_load_size;
     if (UseCompressedOops) {
-      klass_load_size = 3*BytesPerInstWord; // see MacroAssembler::load_klass()
+      assert(Universe::heap() != NULL, "java heap should be initialized");
+      if (Universe::narrow_oop_base() == NULL)
+        klass_load_size = 2*BytesPerInstWord; // see MacroAssembler::load_klass()
+      else
+        klass_load_size = 3*BytesPerInstWord;
     } else {
       klass_load_size = 1*BytesPerInstWord;
     }
@@ -1431,7 +1435,7 @@
 
 #ifndef _LP64
   // In the LP64 build, all registers can be moved as aligned/adjacent
-  // pairs, so there's never any need to move the high bits seperately.
+  // pairs, so there's never any need to move the high bits separately.
   // The 32-bit builds have to deal with the 32-bit ABI which can force
   // all sorts of silly alignment problems.
 
@@ -1601,9 +1605,11 @@
   st->print_cr("\nUEP:");
 #ifdef    _LP64
   if (UseCompressedOops) {
+    assert(Universe::heap() != NULL, "java heap should be initialized");
     st->print_cr("\tLDUW   [R_O0 + oopDesc::klass_offset_in_bytes],R_G5\t! Inline cache check - compressed klass");
     st->print_cr("\tSLL    R_G5,3,R_G5");
-    st->print_cr("\tADD    R_G5,R_G6_heap_base,R_G5");
+    if (Universe::narrow_oop_base() != NULL)
+      st->print_cr("\tADD    R_G5,R_G6_heap_base,R_G5");
   } else {
     st->print_cr("\tLDX    [R_O0 + oopDesc::klass_offset_in_bytes],R_G5\t! Inline cache check");
   }
@@ -1624,7 +1630,7 @@
   Register temp_reg   = G3;
   assert( G5_ic_reg != temp_reg, "conflicting registers" );
 
-  // Load klass from reciever
+  // Load klass from receiver
   __ load_klass(O0, temp_reg);
   // Compare against expected klass
   __ cmp(temp_reg, G5_ic_reg);
@@ -2502,7 +2508,11 @@
       __ load_klass(O0, G3_scratch);
       int klass_load_size;
       if (UseCompressedOops) {
-        klass_load_size = 3*BytesPerInstWord;
+        assert(Universe::heap() != NULL, "java heap should be initialized");
+        if (Universe::narrow_oop_base() == NULL)
+          klass_load_size = 2*BytesPerInstWord;
+        else
+          klass_load_size = 3*BytesPerInstWord;
       } else {
         klass_load_size = 1*BytesPerInstWord;
       }
@@ -2993,6 +3003,202 @@
     __ bind(Ldone);
   %}
 
+enc_class enc_String_Equals(o0RegP str1, o1RegP str2, g3RegP tmp1, g4RegP tmp2, notemp_iRegI result) %{
+    Label Lword, Lword_loop, Lpost_word, Lchar, Lchar_loop, Ldone;
+    MacroAssembler _masm(&cbuf);
+
+    Register   str1_reg = reg_to_register_object($str1$$reg);
+    Register   str2_reg = reg_to_register_object($str2$$reg);
+    Register   tmp1_reg = reg_to_register_object($tmp1$$reg);
+    Register   tmp2_reg = reg_to_register_object($tmp2$$reg);
+    Register result_reg = reg_to_register_object($result$$reg);
+
+    // Get the first character position in both strings
+    //         [8] char array, [12] offset, [16] count
+    int  value_offset = java_lang_String:: value_offset_in_bytes();
+    int offset_offset = java_lang_String::offset_offset_in_bytes();
+    int  count_offset = java_lang_String:: count_offset_in_bytes();
+
+    // load str1 (jchar*) base address into tmp1_reg
+    __ load_heap_oop(Address(str1_reg, 0,  value_offset), tmp1_reg);
+    __ ld(Address(str1_reg, 0, offset_offset), result_reg);
+    __ add(tmp1_reg, arrayOopDesc::base_offset_in_bytes(T_CHAR), tmp1_reg);
+    __    ld(Address(str1_reg, 0, count_offset), str1_reg); // hoisted
+    __ sll(result_reg, exact_log2(sizeof(jchar)), result_reg);
+    __    load_heap_oop(Address(str2_reg, 0,  value_offset), tmp2_reg); // hoisted
+    __ add(result_reg, tmp1_reg, tmp1_reg);
+
+    // load str2 (jchar*) base address into tmp2_reg
+    // __ ld_ptr(Address(str2_reg, 0,  value_offset), tmp2_reg); // hoisted
+    __ ld(Address(str2_reg, 0, offset_offset), result_reg);
+    __ add(tmp2_reg, arrayOopDesc::base_offset_in_bytes(T_CHAR), tmp2_reg);
+    __    ld(Address(str2_reg, 0, count_offset), str2_reg); // hoisted
+    __ sll(result_reg, exact_log2(sizeof(jchar)), result_reg);
+    __   cmp(str1_reg, str2_reg); // hoisted
+    __ add(result_reg, tmp2_reg, tmp2_reg);
+
+    __ sll(str1_reg, exact_log2(sizeof(jchar)), str1_reg);
+    __ br(Assembler::notEqual, true, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg);    // not equal
+
+    __ br_zero(Assembler::equal, true, Assembler::pn, str1_reg, Ldone);
+    __ delayed()->add(G0, 1, result_reg); //equals
+
+    __ cmp(tmp1_reg, tmp2_reg); //same string ?
+    __ brx(Assembler::equal, true, Assembler::pn, Ldone);
+    __ delayed()->add(G0, 1, result_reg);
+
+    //rename registers
+    Register limit_reg =   str1_reg;
+    Register  chr2_reg =   str2_reg;
+    Register  chr1_reg = result_reg;
+    // tmp{12} are the base pointers
+
+    //check for alignment and position the pointers to the ends
+    __ or3(tmp1_reg, tmp2_reg, chr1_reg);
+    __ andcc(chr1_reg, 0x3, chr1_reg); // notZero means at least one not 4-byte aligned
+    __ br(Assembler::notZero, false, Assembler::pn, Lchar);
+    __ delayed()->nop();
+
+    __ bind(Lword);
+    __ and3(limit_reg, 0x2, O7); //remember the remainder (either 0 or 2)
+    __ andn(limit_reg, 0x3, limit_reg);
+    __ br_zero(Assembler::zero, false, Assembler::pn, limit_reg, Lpost_word);
+    __ delayed()->nop();
+
+    __ add(tmp1_reg, limit_reg, tmp1_reg);
+    __ add(tmp2_reg, limit_reg, tmp2_reg);
+    __ neg(limit_reg);
+
+    __ lduw(tmp1_reg, limit_reg, chr1_reg);
+    __ bind(Lword_loop);
+    __ lduw(tmp2_reg, limit_reg, chr2_reg);
+    __ cmp(chr1_reg, chr2_reg);
+    __ br(Assembler::notEqual, true, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg);
+    __ inccc(limit_reg, 2*sizeof(jchar));
+    // annul LDUW if branch i  s not taken to prevent access past end of string
+    __ br(Assembler::notZero, true, Assembler::pt, Lword_loop); //annul on taken
+    __ delayed()->lduw(tmp1_reg, limit_reg, chr1_reg); // hoisted
+
+    __ bind(Lpost_word);
+    __ br_zero(Assembler::zero, true, Assembler::pt, O7, Ldone);
+    __ delayed()->add(G0, 1, result_reg);
+
+    __ lduh(tmp1_reg, 0, chr1_reg);
+    __ lduh(tmp2_reg, 0, chr2_reg);
+    __ cmp (chr1_reg, chr2_reg);
+    __ br(Assembler::notEqual, true, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg);
+    __ ba(false,Ldone);
+    __ delayed()->add(G0, 1, result_reg);
+
+    __ bind(Lchar);
+    __ add(tmp1_reg, limit_reg, tmp1_reg);
+    __ add(tmp2_reg, limit_reg, tmp2_reg);
+    __ neg(limit_reg); //negate count
+
+    __ lduh(tmp1_reg, limit_reg, chr1_reg);
+    __ bind(Lchar_loop);
+    __ lduh(tmp2_reg, limit_reg, chr2_reg);
+    __ cmp(chr1_reg, chr2_reg);
+    __ br(Assembler::notEqual, true, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg); //not equal
+    __ inccc(limit_reg, sizeof(jchar));
+    // annul LDUH if branch is not taken to prevent access past end of string
+    __ br(Assembler::notZero, true, Assembler::pt, Lchar_loop); //annul on taken
+    __ delayed()->lduh(tmp1_reg, limit_reg, chr1_reg); // hoisted
+
+    __ add(G0, 1, result_reg);  //equal
+
+    __ bind(Ldone);
+  %}
+
+enc_class enc_Array_Equals(o0RegP ary1, o1RegP ary2, g3RegP tmp1, g4RegP tmp2, notemp_iRegI result) %{
+    Label Lvector, Ldone, Lloop;
+    MacroAssembler _masm(&cbuf);
+
+    Register   ary1_reg = reg_to_register_object($ary1$$reg);
+    Register   ary2_reg = reg_to_register_object($ary2$$reg);
+    Register   tmp1_reg = reg_to_register_object($tmp1$$reg);
+    Register   tmp2_reg = reg_to_register_object($tmp2$$reg);
+    Register result_reg = reg_to_register_object($result$$reg);
+
+    int length_offset  = arrayOopDesc::length_offset_in_bytes();
+    int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
+
+    // return true if the same array
+    __ cmp(ary1_reg, ary2_reg);
+    __ br(Assembler::equal, true, Assembler::pn, Ldone);
+    __ delayed()->add(G0, 1, result_reg); // equal
+
+    __ br_null(ary1_reg, true, Assembler::pn, Ldone);
+    __ delayed()->mov(G0, result_reg);    // not equal
+
+    __ br_null(ary2_reg, true, Assembler::pn, Ldone);
+    __ delayed()->mov(G0, result_reg);    // not equal
+
+    //load the lengths of arrays
+    __ ld(Address(ary1_reg, 0, length_offset), tmp1_reg);
+    __ ld(Address(ary2_reg, 0, length_offset), tmp2_reg);
+
+    // return false if the two arrays are not equal length
+    __ cmp(tmp1_reg, tmp2_reg);
+    __ br(Assembler::notEqual, true, Assembler::pn, Ldone);
+    __ delayed()->mov(G0, result_reg);     // not equal
+
+    __ br_zero(Assembler::zero, true, Assembler::pn, tmp1_reg, Ldone);
+    __ delayed()->add(G0, 1, result_reg); // zero-length arrays are equal
+
+    // load array addresses
+    __ add(ary1_reg, base_offset, ary1_reg);
+    __ add(ary2_reg, base_offset, ary2_reg);
+
+    // renaming registers
+    Register chr1_reg  =  tmp2_reg;   // for characters in ary1
+    Register chr2_reg  =  result_reg; // for characters in ary2
+    Register limit_reg =  tmp1_reg;   // length
+
+    // set byte count
+    __ sll(limit_reg, exact_log2(sizeof(jchar)), limit_reg);
+    __ andcc(limit_reg, 0x2, chr1_reg); //trailing character ?
+    __ br(Assembler::zero, false, Assembler::pt, Lvector);
+    __ delayed()->nop();
+
+    //compare the trailing char
+    __ sub(limit_reg, sizeof(jchar), limit_reg);
+    __ lduh(ary1_reg, limit_reg, chr1_reg);
+    __ lduh(ary2_reg, limit_reg, chr2_reg);
+    __ cmp(chr1_reg, chr2_reg);
+    __ br(Assembler::notEqual, true, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg);     // not equal
+
+    // only one char ?
+    __ br_zero(Assembler::zero, true, Assembler::pn, limit_reg, Ldone);
+    __ delayed()->add(G0, 1, result_reg); // zero-length arrays are equal
+
+    __ bind(Lvector);
+    // Shift ary1_reg and ary2_reg to the end of the arrays, negate limit
+    __ add(ary1_reg, limit_reg, ary1_reg);
+    __ add(ary2_reg, limit_reg, ary2_reg);
+    __ neg(limit_reg, limit_reg);
+
+    __ lduw(ary1_reg, limit_reg, chr1_reg);
+    __ bind(Lloop);
+    __ lduw(ary2_reg, limit_reg, chr2_reg);
+    __ cmp(chr1_reg, chr2_reg);
+    __ br(Assembler::notEqual, false, Assembler::pt, Ldone);
+    __ delayed()->mov(G0, result_reg);     // not equal
+    __ inccc(limit_reg, 2*sizeof(jchar));
+    // annul LDUW if branch is not taken to prevent access past end of string
+    __ br(Assembler::notZero, true, Assembler::pt, Lloop); //annul on taken
+    __ delayed()->lduw(ary1_reg, limit_reg, chr1_reg); // hoisted
+
+    __ add(G0, 1, result_reg); // equals
+
+    __ bind(Ldone);
+  %}
+
   enc_class enc_rethrow() %{
     cbuf.set_inst_mark();
     Register temp_reg = G3;
@@ -4149,7 +4355,7 @@
 
 //----------OPERAND CLASSES----------------------------------------------------
 // Operand Classes are groups of operands that are used to simplify
-// instruction definitions by not requiring the AD writer to specify seperate
+// instruction definitions by not requiring the AD writer to specify separate
 // instructions for every form of operand when the instruction accepts
 // multiple operand types with the same basic encoding and format.  The classic
 // case of this is memory operands.
@@ -5286,55 +5492,91 @@
   ins_cost(MEMORY_REF_COST);
 
   size(4);
-  format %{ "LDSB   $mem,$dst" %}
+  format %{ "LDSB   $mem,$dst\t! byte" %}
+  opcode(Assembler::ldsb_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mask_mem);
+%}
+
+// Load Byte (8bit signed) into a Long Register
+instruct loadB2L(iRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadB mem)));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDSB   $mem,$dst\t! byte -> long" %}
   opcode(Assembler::ldsb_op3);
   ins_encode(simple_form3_mem_reg( mem, dst ) );
   ins_pipe(iload_mask_mem);
 %}
 
-// Load Byte (8bit UNsigned) into an int reg
-instruct loadUB(iRegI dst, memory mem, immI_255 bytemask) %{
-  match(Set dst (AndI (LoadB mem) bytemask));
+// Load Unsigned Byte (8bit UNsigned) into an int reg
+instruct loadUB(iRegI dst, memory mem) %{
+  match(Set dst (LoadUB mem));
   ins_cost(MEMORY_REF_COST);
 
   size(4);
-  format %{ "LDUB   $mem,$dst" %}
+  format %{ "LDUB   $mem,$dst\t! ubyte" %}
+  opcode(Assembler::ldub_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mask_mem);
+%}
+
+// Load Unsigned Byte (8bit UNsigned) into a Long Register
+instruct loadUB2L(iRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadUB mem)));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDUB   $mem,$dst\t! ubyte -> long" %}
   opcode(Assembler::ldub_op3);
   ins_encode(simple_form3_mem_reg( mem, dst ) );
   ins_pipe(iload_mask_mem);
 %}
 
-// Load Byte (8bit UNsigned) into a Long Register
-instruct loadUBL(iRegL dst, memory mem, immL_FF bytemask) %{
-  match(Set dst (AndL (ConvI2L (LoadB mem)) bytemask));
+// Load Short (16bit signed)
+instruct loadS(iRegI dst, memory mem) %{
+  match(Set dst (LoadS mem));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDSH   $mem,$dst\t! short" %}
+  opcode(Assembler::ldsh_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mask_mem);
+%}
+
+// Load Short (16bit signed) into a Long Register
+instruct loadS2L(iRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadS mem)));
   ins_cost(MEMORY_REF_COST);
 
   size(4);
-  format %{ "LDUB   $mem,$dst" %}
-  opcode(Assembler::ldub_op3);
+  format %{ "LDSH   $mem,$dst\t! short -> long" %}
+  opcode(Assembler::ldsh_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mask_mem);
+%}
+
+// Load Unsigned Short/Char (16bit UNsigned)
+instruct loadUS(iRegI dst, memory mem) %{
+  match(Set dst (LoadUS mem));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDUH   $mem,$dst\t! ushort/char" %}
+  opcode(Assembler::lduh_op3);
   ins_encode(simple_form3_mem_reg( mem, dst ) );
   ins_pipe(iload_mask_mem);
 %}
 
 // Load Unsigned Short/Char (16bit UNsigned) into a Long Register
-instruct loadUS2L(iRegL dst, memory mem, immL_FFFF bytemask) %{
-  match(Set dst (AndL (ConvI2L (LoadUS mem)) bytemask));
+instruct loadUS2L(iRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadUS mem)));
   ins_cost(MEMORY_REF_COST);
 
   size(4);
-  format %{ "LDUH   $mem,$dst" %}
-  opcode(Assembler::lduh_op3);
-  ins_encode(simple_form3_mem_reg( mem, dst ) );
-  ins_pipe(iload_mask_mem);
-%}
-
-// Load Unsigned Short/Char (16bit unsigned)
-instruct loadUS(iRegI dst, memory mem) %{
-  match(Set dst (LoadUS mem));
-  ins_cost(MEMORY_REF_COST);
-
-  size(4);
-  format %{ "LDUH   $mem,$dst" %}
+  format %{ "LDUH   $mem,$dst\t! ushort/char -> long" %}
   opcode(Assembler::lduh_op3);
   ins_encode(simple_form3_mem_reg( mem, dst ) );
   ins_pipe(iload_mask_mem);
@@ -5344,9 +5586,33 @@
 instruct loadI(iRegI dst, memory mem) %{
   match(Set dst (LoadI mem));
   ins_cost(MEMORY_REF_COST);
-  size(4);
-
-  format %{ "LDUW   $mem,$dst" %}
+
+  size(4);
+  format %{ "LDUW   $mem,$dst\t! int" %}
+  opcode(Assembler::lduw_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mem);
+%}
+
+// Load Integer into a Long Register
+instruct loadI2L(iRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadI mem)));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDSW   $mem,$dst\t! int -> long" %}
+  opcode(Assembler::ldsw_op3);
+  ins_encode(simple_form3_mem_reg( mem, dst ) );
+  ins_pipe(iload_mem);
+%}
+
+// Load Unsigned Integer into a Long Register
+instruct loadUI2L(iRegL dst, memory mem) %{
+  match(Set dst (LoadUI2L mem));
+  ins_cost(MEMORY_REF_COST);
+
+  size(4);
+  format %{ "LDUW   $mem,$dst\t! uint -> long" %}
   opcode(Assembler::lduw_op3);
   ins_encode(simple_form3_mem_reg( mem, dst ) );
   ins_pipe(iload_mem);
@@ -5356,6 +5622,7 @@
 instruct loadL(iRegL dst, memory mem ) %{
   match(Set dst (LoadL mem));
   ins_cost(MEMORY_REF_COST);
+
   size(4);
   format %{ "LDX    $mem,$dst\t! long" %}
   opcode(Assembler::ldx_op3);
@@ -5471,13 +5738,11 @@
 
    format %{ "LDUW   $mem,$dst\t! compressed ptr" %}
    ins_encode %{
-     Register base = as_Register($mem$$base);
-     Register index = as_Register($mem$$index);
-     Register dst = $dst$$Register;
+     Register index = $mem$$index$$Register;
      if (index != G0) {
-       __ lduw(base, index, dst);
+       __ lduw($mem$$base$$Register, index, $dst$$Register);
      } else {
-       __ lduw(base, $mem$$disp, dst);
+       __ lduw($mem$$base$$Register, $mem$$disp, $dst$$Register);
      }
    %}
    ins_pipe(iload_mem);
@@ -5521,18 +5786,6 @@
   ins_pipe(iload_mem);
 %}
 
-// Load Short (16bit signed)
-instruct loadS(iRegI dst, memory mem) %{
-  match(Set dst (LoadS mem));
-  ins_cost(MEMORY_REF_COST);
-
-  size(4);
-  format %{ "LDSH   $mem,$dst" %}
-  opcode(Assembler::ldsh_op3);
-  ins_encode(simple_form3_mem_reg( mem, dst ) );
-  ins_pipe(iload_mask_mem);
-%}
-
 // Load Double
 instruct loadD(regD dst, memory mem) %{
   match(Set dst (LoadD mem));
@@ -6847,7 +7100,7 @@
   ins_pipe(sdiv_reg_reg);
 %}
 
-// Magic constant, reciprical of 10
+// Magic constant, reciprocal of 10
 instruct loadConI_x66666667(iRegIsafe dst) %{
   effect( DEF dst );
 
@@ -6857,7 +7110,7 @@
   ins_pipe(ialu_hi_lo_reg);
 %}
 
-// Register Shift Right Arithmatic Long by 32-63
+// Register Shift Right Arithmetic Long by 32-63
 instruct sra_31( iRegI dst, iRegI src ) %{
   effect( DEF dst, USE src );
   format %{ "SRA    $src,31,$dst\t! Used in div-by-10" %}
@@ -8958,6 +9211,52 @@
   ins_pipe(long_memory_op);
 %}
 
+instruct string_equals(o0RegP str1, o1RegP str2, g3RegP tmp1, g4RegP tmp2, notemp_iRegI result,
+                       o7RegI tmp3, flagsReg ccr) %{
+  match(Set result (StrEquals str1 str2));
+  effect(USE_KILL str1, USE_KILL str2, KILL tmp1, KILL tmp2, KILL ccr, KILL tmp3);
+  ins_cost(300);
+  format %{ "String Equals $str1,$str2 -> $result" %}
+  ins_encode( enc_String_Equals(str1, str2, tmp1, tmp2, result) );
+  ins_pipe(long_memory_op);
+%}
+
+instruct array_equals(o0RegP ary1, o1RegP ary2, g3RegP tmp1, g4RegP tmp2, notemp_iRegI result,
+                        flagsReg ccr) %{
+  match(Set result (AryEq ary1 ary2));
+  effect(USE_KILL ary1, USE_KILL ary2, KILL tmp1, KILL tmp2, KILL ccr);
+  ins_cost(300);
+  format %{ "Array Equals $ary1,$ary2 -> $result" %}
+  ins_encode( enc_Array_Equals(ary1, ary2, tmp1, tmp2, result));
+  ins_pipe(long_memory_op);
+%}
+
+//---------- Population Count Instructions -------------------------------------
+
+instruct popCountI(iRegI dst, iRegI src) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountI src));
+
+  format %{ "POPC   $src, $dst" %}
+  ins_encode %{
+    __ popc($src$$Register, $dst$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+// Note: Long.bitCount(long) returns an int.
+instruct popCountL(iRegI dst, iRegL src) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountL src));
+
+  format %{ "POPC   $src, $dst" %}
+  ins_encode %{
+    __ popc($src$$Register, $dst$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+
 // ============================================================================
 //------------Bytes reverse--------------------------------------------------
 
@@ -9048,7 +9347,7 @@
 // These must follow all instruction definitions as they use the names
 // defined in the instructions definitions.
 //
-// peepmatch ( root_instr_name [preceeding_instruction]* );
+// peepmatch ( root_instr_name [preceding_instruction]* );
 //
 // peepconstraint %{
 // (instruction_number.operand_name relational_op instruction_number.operand_name
--- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -817,21 +817,6 @@
   Label _atomic_add_stub;  // called from other stubs
 
 
-  // Support for void OrderAccess::fence().
-  //
-  address generate_fence() {
-    StubCodeMark mark(this, "StubRoutines", "fence");
-    address start = __ pc();
-
-    __ membar(Assembler::Membar_mask_bits(Assembler::LoadLoad  | Assembler::LoadStore |
-                                          Assembler::StoreLoad | Assembler::StoreStore));
-    __ retl(false);
-    __ delayed()->nop();
-
-    return start;
-  }
-
-
   //------------------------------------------------------------------------------------------------------------------------
   // The following routine generates a subroutine to throw an asynchronous
   // UnknownError when an unsafe access gets a fault that could not be
@@ -900,19 +885,7 @@
     __ align(CodeEntryAlignment);
     StubCodeMark mark(this, "StubRoutines", "partial_subtype_check");
     address start = __ pc();
-    Label loop, miss;
-
-    // Compare super with sub directly, since super is not in its own SSA.
-    // The compiler used to emit this test, but we fold it in here,
-    // to increase overall code density, with no real loss of speed.
-    { Label L;
-      __ cmp(O1, O2);
-      __ brx(Assembler::notEqual, false, Assembler::pt, L);
-      __ delayed()->nop();
-      __ retl();
-      __ delayed()->addcc(G0,0,O0); // set Z flags, zero result
-      __ bind(L);
-    }
+    Label miss;
 
 #if defined(COMPILER2) && !defined(_LP64)
     // Do not use a 'save' because it blows the 64-bit O registers.
@@ -936,56 +909,12 @@
     Register L2_super   = L2;
     Register L3_index   = L3;
 
-#ifdef _LP64
-    Register L4_ooptmp  = L4;
-
-    if (UseCompressedOops) {
-      // this must be under UseCompressedOops check, as we rely upon fact
-      // that L4 not clobbered in C2 on 32-bit platforms, where we do explicit save
-      // on stack, see several lines above
-      __ encode_heap_oop(Rsuper, L4_ooptmp);
-    }
-#endif
-
-    inc_counter_np(SharedRuntime::_partial_subtype_ctr, L0, L1);
-
-    __ ld_ptr( Rsub, sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes(), L3 );
-    __ lduw(L3,arrayOopDesc::length_offset_in_bytes(),L0_ary_len);
-    __ add(L3,arrayOopDesc::base_offset_in_bytes(T_OBJECT),L1_ary_ptr);
-    __ clr(L3_index);           // zero index
-    // Load a little early; will load 1 off the end of the array.
-    // Ok for now; revisit if we have other uses of this routine.
-    if (UseCompressedOops) {
-      __ lduw(L1_ary_ptr,0,L2_super);// Will load a little early
-    } else {
-      __ ld_ptr(L1_ary_ptr,0,L2_super);// Will load a little early
-    }
-
-    assert(heapOopSize != 0, "heapOopSize should be initialized");
-    // The scan loop
-    __ BIND(loop);
-    __ add(L1_ary_ptr, heapOopSize, L1_ary_ptr); // Bump by OOP size
-    __ cmp(L3_index,L0_ary_len);
-    __ br(Assembler::equal,false,Assembler::pn,miss);
-    __ delayed()->inc(L3_index); // Bump index
-
-    if (UseCompressedOops) {
-#ifdef  _LP64
-      __ subcc(L2_super,L4_ooptmp,Rret);   // Check for match; zero in Rret for a hit
-      __ br( Assembler::notEqual, false, Assembler::pt, loop );
-      __ delayed()->lduw(L1_ary_ptr,0,L2_super);// Will load a little early
-#else
-      ShouldNotReachHere();
-#endif
-    } else {
-      __ subcc(L2_super,Rsuper,Rret);   // Check for match; zero in Rret for a hit
-      __ brx( Assembler::notEqual, false, Assembler::pt, loop );
-      __ delayed()->ld_ptr(L1_ary_ptr,0,L2_super);// Will load a little early
-    }
-
-    // Got a hit; report success; set cache.  Cache load doesn't
-    // happen here; for speed it is directly emitted by the compiler.
-    __ st_ptr( Rsuper, Rsub, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() );
+    __ check_klass_subtype_slow_path(Rsub, Rsuper,
+                                     L0, L1, L2, L3,
+                                     NULL, &miss);
+
+    // Match falls through here.
+    __ addcc(G0,0,Rret);        // set Z flags, Z result
 
 #if defined(COMPILER2) && !defined(_LP64)
     __ ld_ptr(SP,(frame::register_save_words+0)*wordSize,L0);
@@ -999,7 +928,6 @@
     __ delayed()->restore();
 #endif
 
-    // Hit or miss falls through here
     __ BIND(miss);
     __ addcc(G0,1,Rret);        // set NZ flags, NZ result
 
@@ -2330,51 +2258,31 @@
                            Register super_check_offset,
                            Register super_klass,
                            Register temp,
-                           Label& L_success,
-                           Register deccc_hack = noreg) {
+                           Label& L_success) {
     assert_different_registers(sub_klass, super_check_offset, super_klass, temp);
 
     BLOCK_COMMENT("type_check:");
 
-    Label L_miss;
+    Label L_miss, L_pop_to_miss;
 
     assert_clean_int(super_check_offset, temp);
 
-    // maybe decrement caller's trip count:
-#define DELAY_SLOT delayed();   \
-    { if (deccc_hack == noreg) __ nop(); else __ deccc(deccc_hack); }
-
-    // if the pointers are equal, we are done (e.g., String[] elements)
-    __ cmp(sub_klass, super_klass);
-    __ brx(Assembler::equal, true, Assembler::pt, L_success);
-    __ DELAY_SLOT;
-
-    // check the supertype display:
-    __ ld_ptr(sub_klass, super_check_offset, temp); // query the super type
-    __ cmp(super_klass,                      temp); // test the super type
-    __ brx(Assembler::equal, true, Assembler::pt, L_success);
-    __ DELAY_SLOT;
-
-    int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
-                     Klass::secondary_super_cache_offset_in_bytes());
-    __ cmp(super_klass, sc_offset);
-    __ brx(Assembler::notEqual, true, Assembler::pt, L_miss);
-    __ delayed()->nop();
-
+    __ check_klass_subtype_fast_path(sub_klass, super_klass, temp, noreg,
+                                     &L_success, &L_miss, NULL,
+                                     super_check_offset);
+
+    BLOCK_COMMENT("type_check_slow_path:");
     __ save_frame(0);
-    __ mov(sub_klass->after_save(), O1);
-    // mov(super_klass->after_save(), O2); //fill delay slot
-    assert(StubRoutines::Sparc::_partial_subtype_check != NULL, "order of generation");
-    __ call(StubRoutines::Sparc::_partial_subtype_check);
-    __ delayed()->mov(super_klass->after_save(), O2);
+    __ check_klass_subtype_slow_path(sub_klass->after_save(),
+                                     super_klass->after_save(),
+                                     L0, L1, L2, L4,
+                                     NULL, &L_pop_to_miss);
+    __ ba(false, L_success);
+    __ delayed()->restore();
+
+    __ bind(L_pop_to_miss);
     __ restore();
 
-    // Upon return, the condition codes are already set.
-    __ brx(Assembler::equal, true, Assembler::pt, L_success);
-    __ DELAY_SLOT;
-
-#undef DELAY_SLOT
-
     // Fall through on failure!
     __ BIND(L_miss);
   }
@@ -2411,7 +2319,7 @@
     gen_write_ref_array_pre_barrier(O1, O2);
 
 #ifdef ASSERT
-    // We sometimes save a frame (see partial_subtype_check below).
+    // We sometimes save a frame (see generate_type_check below).
     // If this will cause trouble, let's fail now instead of later.
     __ save_frame(0);
     __ restore();
@@ -2455,41 +2363,39 @@
     //   G3, G4, G5 --- current oop, oop.klass, oop.klass.super
     __ align(16);
 
-    __ bind(store_element);
-    // deccc(G1_remain);                // decrement the count (hoisted)
+    __ BIND(store_element);
+    __ deccc(G1_remain);                // decrement the count
     __ store_heap_oop(G3_oop, O1_to, O5_offset); // store the oop
     __ inc(O5_offset, heapOopSize);     // step to next offset
     __ brx(Assembler::zero, true, Assembler::pt, do_card_marks);
     __ delayed()->set(0, O0);           // return -1 on success
 
     // ======== loop entry is here ========
-    __ bind(load_element);
+    __ BIND(load_element);
     __ load_heap_oop(O0_from, O5_offset, G3_oop);  // load the oop
     __ br_null(G3_oop, true, Assembler::pt, store_element);
-    __ delayed()->deccc(G1_remain);     // decrement the count
+    __ delayed()->nop();
 
     __ load_klass(G3_oop, G4_klass); // query the object klass
 
     generate_type_check(G4_klass, O3_ckoff, O4_ckval, G5_super,
                         // branch to this on success:
-                        store_element,
-                        // decrement this on success:
-                        G1_remain);
+                        store_element);
     // ======== end loop ========
 
     // It was a real error; we must depend on the caller to finish the job.
     // Register G1 has number of *remaining* oops, O2 number of *total* oops.
     // Emit GC store barriers for the oops we have copied (O2 minus G1),
     // and report their number to the caller.
-    __ bind(fail);
+    __ BIND(fail);
     __ subcc(O2_count, G1_remain, O2_count);
     __ brx(Assembler::zero, false, Assembler::pt, done);
     __ delayed()->not1(O2_count, O0);   // report (-1^K) to caller
 
-    __ bind(do_card_marks);
+    __ BIND(do_card_marks);
     gen_write_ref_array_post_barrier(O1_to, O2_count, O3);   // store check on O1[0..O2]
 
-    __ bind(done);
+    __ BIND(done);
     inc_counter_np(SharedRuntime::_checkcast_array_copy_ctr, O3, O4);
     __ retl();
     __ delayed()->nop();             // return value in 00
@@ -2940,16 +2846,16 @@
     StubRoutines::_atomic_cmpxchg_ptr_entry  = StubRoutines::_atomic_cmpxchg_entry;
     StubRoutines::_atomic_cmpxchg_long_entry = generate_atomic_cmpxchg_long();
     StubRoutines::_atomic_add_ptr_entry      = StubRoutines::_atomic_add_entry;
-    StubRoutines::_fence_entry               = generate_fence();
 #endif  // COMPILER2 !=> _LP64
-
-    StubRoutines::Sparc::_partial_subtype_check                = generate_partial_subtype_check();
   }
 
 
   void generate_all() {
     // Generates all stubs and initializes the entry points
 
+    // Generate partial_subtype_check first here since its code depends on
+    // UseZeroBaseCompressedOops which is defined after heap initialization.
+    StubRoutines::Sparc::_partial_subtype_check                = generate_partial_subtype_check();
     // These entry points require SharedInfo::stack0 to be set up in non-core builds
     StubRoutines::_throw_AbstractMethodError_entry         = generate_throw_exception("AbstractMethodError throw_exception",          CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError),  false);
     StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError),  false);
--- a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1545,7 +1545,7 @@
 
   // Handle all the JSR stuff here, then exit.
   // It's much shorter and cleaner than intermingling with the
-  // non-JSR normal-branch stuff occuring below.
+  // non-JSR normal-branch stuff occurring below.
   if( is_jsr ) {
     // compute return address as bci in Otos_i
     __ ld_ptr(Address(Lmethod, 0, in_bytes(methodOopDesc::const_offset())), G3_scratch);
@@ -3079,7 +3079,7 @@
     Label ok;
 
     // Check that entry is non-null.  Null entries are probably a bytecode
-    // problem.  If the interface isn't implemented by the reciever class,
+    // problem.  If the interface isn't implemented by the receiver class,
     // the VM should throw IncompatibleClassChangeError.  linkResolver checks
     // this too but that's only if the entry isn't already resolved, so we
     // need to check again.
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -62,7 +62,7 @@
   if (is_niagara1()) {
     // Indirect branch is the same cost as direct
     if (FLAG_IS_DEFAULT(UseInlineCaches)) {
-      UseInlineCaches         = false;
+      FLAG_SET_DEFAULT(UseInlineCaches, false);
     }
 #ifdef _LP64
     // Single issue niagara1 is slower for CompressedOops
@@ -72,33 +72,50 @@
         FLAG_SET_ERGO(bool, UseCompressedOops, false);
       }
     }
+    // 32-bit oops don't make sense for the 64-bit VM on sparc
+    // since the 32-bit VM has the same registers and smaller objects.
+    Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
 #endif // _LP64
 #ifdef COMPILER2
     // Indirect branch is the same cost as direct
     if (FLAG_IS_DEFAULT(UseJumpTables)) {
-      UseJumpTables           = true;
+      FLAG_SET_DEFAULT(UseJumpTables, true);
     }
     // Single-issue, so entry and loop tops are
     // aligned on a single instruction boundary
     if (FLAG_IS_DEFAULT(InteriorEntryAlignment)) {
-      InteriorEntryAlignment  = 4;
+      FLAG_SET_DEFAULT(InteriorEntryAlignment, 4);
     }
     if (FLAG_IS_DEFAULT(OptoLoopAlignment)) {
-      OptoLoopAlignment       = 4;
+      FLAG_SET_DEFAULT(OptoLoopAlignment, 4);
+    }
+    if (is_niagara1_plus() && FLAG_IS_DEFAULT(AllocatePrefetchDistance)) {
+      // Use smaller prefetch distance on N2
+      FLAG_SET_DEFAULT(AllocatePrefetchDistance, 256);
     }
 #endif
   }
 
+  // Use hardware population count instruction if available.
+  if (has_hardware_popc()) {
+    if (FLAG_IS_DEFAULT(UsePopCountInstruction)) {
+      FLAG_SET_DEFAULT(UsePopCountInstruction, true);
+    }
+  }
+
   char buf[512];
-  jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s",
+  jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s%s%s%s",
                (has_v8() ? ", has_v8" : ""),
                (has_v9() ? ", has_v9" : ""),
+               (has_hardware_popc() ? ", popc" : ""),
                (has_vis1() ? ", has_vis1" : ""),
                (has_vis2() ? ", has_vis2" : ""),
                (is_ultra3() ? ", is_ultra3" : ""),
                (is_sun4v() ? ", is_sun4v" : ""),
                (is_niagara1() ? ", is_niagara1" : ""),
-               (!has_hardware_int_muldiv() ? ", no-muldiv" : ""),
+               (is_niagara1_plus() ? ", is_niagara1_plus" : ""),
+               (!has_hardware_mul32() ? ", no-mul32" : ""),
+               (!has_hardware_div32() ? ", no-div32" : ""),
                (!has_hardware_fsmuld() ? ", no-fsmuld" : ""));
 
   // buf is started with ", " or is empty
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,34 +25,38 @@
 class VM_Version: public Abstract_VM_Version {
 protected:
   enum Feature_Flag {
-    v8_instructions     = 0,
-    hardware_int_muldiv = 1,
-    hardware_fsmuld     = 2,
-    v9_instructions     = 3,
-    vis1_instructions   = 4,
-    vis2_instructions   = 5,
-    sun4v_instructions  = 6
+    v8_instructions    = 0,
+    hardware_mul32     = 1,
+    hardware_div32     = 2,
+    hardware_fsmuld    = 3,
+    hardware_popc      = 4,
+    v9_instructions    = 5,
+    vis1_instructions  = 6,
+    vis2_instructions  = 7,
+    sun4v_instructions = 8
   };
 
   enum Feature_Flag_Set {
-    unknown_m             = 0,
-    all_features_m        = -1,
+    unknown_m           = 0,
+    all_features_m      = -1,
 
-    v8_instructions_m     = 1 << v8_instructions,
-    hardware_int_muldiv_m = 1 << hardware_int_muldiv,
-    hardware_fsmuld_m     = 1 << hardware_fsmuld,
-    v9_instructions_m     = 1 << v9_instructions,
-    vis1_instructions_m   = 1 << vis1_instructions,
-    vis2_instructions_m   = 1 << vis2_instructions,
-    sun4v_m               = 1 << sun4v_instructions,
+    v8_instructions_m   = 1 << v8_instructions,
+    hardware_mul32_m    = 1 << hardware_mul32,
+    hardware_div32_m    = 1 << hardware_div32,
+    hardware_fsmuld_m   = 1 << hardware_fsmuld,
+    hardware_popc_m     = 1 << hardware_popc,
+    v9_instructions_m   = 1 << v9_instructions,
+    vis1_instructions_m = 1 << vis1_instructions,
+    vis2_instructions_m = 1 << vis2_instructions,
+    sun4v_m             = 1 << sun4v_instructions,
 
-    generic_v8_m          = v8_instructions_m | hardware_int_muldiv_m | hardware_fsmuld_m,
-    generic_v9_m          = generic_v8_m | v9_instructions_m | vis1_instructions_m,
-    ultra3_m              = generic_v9_m | vis2_instructions_m,
+    generic_v8_m        = v8_instructions_m | hardware_mul32_m | hardware_div32_m | hardware_fsmuld_m,
+    generic_v9_m        = generic_v8_m | v9_instructions_m,
+    ultra3_m            = generic_v9_m | vis1_instructions_m | vis2_instructions_m,
 
     // Temporary until we have something more accurate
-    niagara1_unique_m     = sun4v_m,
-    niagara1_m            = generic_v9_m | niagara1_unique_m
+    niagara1_unique_m   = sun4v_m,
+    niagara1_m          = generic_v9_m | niagara1_unique_m
   };
 
   static int  _features;
@@ -62,7 +66,7 @@
   static int  determine_features();
   static int  platform_features(int features);
 
-  static bool is_niagara1(int features) { return (features & niagara1_m) == niagara1_m; }
+  static bool is_niagara1(int features) { return (features & sun4v_m) != 0; }
 
   static int maximum_niagara1_processor_count() { return 32; }
   // Returns true if the platform is in the niagara line and
@@ -76,8 +80,10 @@
   // Instruction support
   static bool has_v8()                  { return (_features & v8_instructions_m) != 0; }
   static bool has_v9()                  { return (_features & v9_instructions_m) != 0; }
-  static bool has_hardware_int_muldiv() { return (_features & hardware_int_muldiv_m) != 0; }
+  static bool has_hardware_mul32()      { return (_features & hardware_mul32_m) != 0; }
+  static bool has_hardware_div32()      { return (_features & hardware_div32_m) != 0; }
   static bool has_hardware_fsmuld()     { return (_features & hardware_fsmuld_m) != 0; }
+  static bool has_hardware_popc()       { return (_features & hardware_popc_m) != 0; }
   static bool has_vis1()                { return (_features & vis1_instructions_m) != 0; }
   static bool has_vis2()                { return (_features & vis2_instructions_m) != 0; }
 
--- a/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -106,6 +106,15 @@
   __ delayed()->nop();
 
   masm->flush();
+
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  vtable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
+  guarantee(__ pc() <= s->code_end(), "overflowed buffer");
+
   s->set_exception_points(npe_addr, ame_addr);
   return s;
 }
@@ -113,9 +122,9 @@
 
 // NOTE:  %%%% if any change is made to this stub make sure that the function
 //             pd_code_size_limit is changed to ensure the correct size for VtableStub
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   const int sparc_code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new(sparc_code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new(sparc_code_length) VtableStub(false, itable_index);
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), sparc_code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -139,7 +148,6 @@
   // are passed in the %o registers.  Instead, longs are passed in G1 and G4
   // and so those registers are not available here.
   __ save(SP,-frame::register_save_words*wordSize,SP);
-  Register I0_receiver = I0;    // Location of receiver after save
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
@@ -151,63 +159,31 @@
   }
 #endif /* PRODUCT */
 
-  // load start of itable entries into L0 register
-  const int base = instanceKlass::vtable_start_offset() * wordSize;
-  __ ld(Address(G3_klassOop, 0, instanceKlass::vtable_length_offset() * wordSize), L0);
-
-  // %%% Could store the aligned, prescaled offset in the klassoop.
-  __ sll(L0, exact_log2(vtableEntry::size() * wordSize), L0);
-  // see code for instanceKlass::start_of_itable!
-  const int vtable_alignment = align_object_offset(1);
-  assert(vtable_alignment == 1 || vtable_alignment == 2, "");
-  const int odd_bit = vtableEntry::size() * wordSize;
-  if (vtable_alignment == 2) {
-    __ and3(L0, odd_bit, L1);   // isolate the odd bit
-  }
-  __ add(G3_klassOop, L0, L0);
-  if (vtable_alignment == 2) {
-    __ add(L0, L1, L0);         // double the odd bit, to align up
-  }
+  Label throw_icce;
 
-  // Loop over all itable entries until desired interfaceOop (G5_interface) found
-  __ bind(search);
-
-  // %%%% Could load both offset and interface in one ldx, if they were
-  // in the opposite order.  This would save a load.
-  __ ld_ptr(L0, base + itableOffsetEntry::interface_offset_in_bytes(), L1);
-
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception
-  Label throw_icce;
-  __ bpr(Assembler::rc_z, false, Assembler::pn, L1, throw_icce);
-  __ delayed()->cmp(G5_interface, L1);
-  __ brx(Assembler::notEqual, true, Assembler::pn, search);
-  __ delayed()->add(L0, itableOffsetEntry::size() * wordSize, L0);
-
-  // entry found and L0 points to it, move offset of vtable for interface into L0
-  __ ld(L0, base + itableOffsetEntry::offset_offset_in_bytes(), L0);
-
-  // Compute itableMethodEntry and get methodOop(G5_method) and entrypoint(L0) for compiler
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) + itableMethodEntry::method_offset_in_bytes();
-  __ add(G3_klassOop, L0, L1);
-  __ ld_ptr(L1, method_offset, G5_method);
+  Register L5_method = L5;
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             G3_klassOop, G5_interface, itable_index,
+                             // outputs: method, scan temp. reg
+                             L5_method, L2, L3,
+                             throw_icce);
 
 #ifndef PRODUCT
   if (DebugVtables) {
     Label L01;
-    __ ld_ptr(L1, method_offset, G5_method);
-    __ bpr(Assembler::rc_nz, false, Assembler::pt, G5_method, L01);
+    __ bpr(Assembler::rc_nz, false, Assembler::pt, L5_method, L01);
     __ delayed()->nop();
     __ stop("methodOop is null");
     __ bind(L01);
-    __ verify_oop(G5_method);
+    __ verify_oop(L5_method);
   }
 #endif
 
   // If the following load is through a NULL pointer, we'll take an OS
   // exception that should translate into an AbstractMethodError.  We need the
   // window count to be correct at that time.
-  __ restore();                 // Restore registers BEFORE the AME point
+  __ restore(L5_method, 0, G5_method);
+  // Restore registers *before* the AME point.
 
   address ame_addr = __ pc();   // if the vtable entry is null, the method is abstract
   __ ld_ptr(G5_method, in_bytes(methodOopDesc::from_compiled_offset()), G3_scratch);
@@ -225,6 +201,12 @@
 
   masm->flush();
 
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  itable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
 
   s->set_exception_points(npe_addr, ame_addr);
@@ -239,14 +221,15 @@
     if (is_vtable_stub) {
       // ld;ld;ld,jmp,nop
       const int basic = 5*BytesPerInstWord +
-                        // shift;add for load_klass
-                        (UseCompressedOops ? 2*BytesPerInstWord : 0);
+                        // shift;add for load_klass (only shift with zero heap based)
+                        (UseCompressedOops ?
+                         ((Universe::narrow_oop_base() == NULL) ? BytesPerInstWord : 2*BytesPerInstWord) : 0);
       return basic + slop;
     } else {
-      // save, ld, ld, sll, and, add, add, ld, cmp, br, add, ld, add, ld, ld, jmp, restore, sethi, jmpl, restore
-      const int basic = (20 LP64_ONLY(+ 6)) * BytesPerInstWord +
-                        // shift;add for load_klass
-                        (UseCompressedOops ? 2*BytesPerInstWord : 0);
+      const int basic = (28 LP64_ONLY(+ 6)) * BytesPerInstWord +
+                        // shift;add for load_klass (only shift with zero heap based)
+                        (UseCompressedOops ?
+                         ((Universe::narrow_oop_base() == NULL) ? BytesPerInstWord : 2*BytesPerInstWord) : 0);
       return (basic + slop);
     }
   }
--- a/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -129,13 +129,19 @@
 // Convert the raw encoding form into the form expected by the constructor for
 // Address.  An index of 4 (rsp) corresponds to having no index, so convert
 // that to noreg for the Address constructor.
-Address Address::make_raw(int base, int index, int scale, int disp) {
+Address Address::make_raw(int base, int index, int scale, int disp, bool disp_is_oop) {
+  RelocationHolder rspec;
+  if (disp_is_oop) {
+    rspec = Relocation::spec_simple(relocInfo::oop_type);
+  }
   bool valid_index = index != rsp->encoding();
   if (valid_index) {
     Address madr(as_Register(base), as_Register(index), (Address::ScaleFactor)scale, in_ByteSize(disp));
+    madr._rspec = rspec;
     return madr;
   } else {
     Address madr(as_Register(base), noreg, Address::no_scale, in_ByteSize(disp));
+    madr._rspec = rspec;
     return madr;
   }
 }
@@ -721,7 +727,7 @@
   }
 
 #ifdef _LP64
-  assert(false, "fix locate_operand");
+  assert(which == narrow_oop_operand && !is_64bit, "instruction is not a movl adr, imm32");
 #else
   assert(which == imm_operand, "instruction has only an imm field");
 #endif // LP64
@@ -1432,26 +1438,12 @@
   }
 }
 
-// Serializes memory.
+// Emit mfence instruction
 void Assembler::mfence() {
-    // Memory barriers are only needed on multiprocessors
-  if (os::is_MP()) {
-    if( LP64_ONLY(true ||) VM_Version::supports_sse2() ) {
-      emit_byte( 0x0F );                // MFENCE; faster blows no regs
-      emit_byte( 0xAE );
-      emit_byte( 0xF0 );
-    } else {
-      // All usable chips support "locked" instructions which suffice
-      // as barriers, and are much faster than the alternative of
-      // using cpuid instruction. We use here a locked add [esp],0.
-      // This is conveniently otherwise a no-op except for blowing
-      // flags (which we save and restore.)
-      pushf();                // Save eflags register
-      lock();
-      addl(Address(rsp, 0), 0);// Assert the lock# signal here
-      popf();                 // Restore eflags register
-    }
-  }
+  NOT_LP64(assert(VM_Version::supports_sse2(), "unsupported");)
+  emit_byte( 0x0F );
+  emit_byte( 0xAE );
+  emit_byte( 0xF0 );
 }
 
 void Assembler::mov(Register dst, Register src) {
@@ -2181,12 +2173,56 @@
   emit_arith(0x0B, 0xC0, dst, src);
 }
 
+void Assembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
+  assert(VM_Version::supports_sse4_2(), "");
+
+  InstructionMark im(this);
+  emit_byte(0x66);
+  prefix(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0x3A);
+  emit_byte(0x61);
+  emit_operand(dst, src);
+  emit_byte(imm8);
+}
+
+void Assembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
+  assert(VM_Version::supports_sse4_2(), "");
+
+  emit_byte(0x66);
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0x3A);
+  emit_byte(0x61);
+  emit_byte(0xC0 | encode);
+  emit_byte(imm8);
+}
+
 // generic
 void Assembler::pop(Register dst) {
   int encode = prefix_and_encode(dst->encoding());
   emit_byte(0x58 | encode);
 }
 
+void Assembler::popcntl(Register dst, Address src) {
+  assert(VM_Version::supports_popcnt(), "must support");
+  InstructionMark im(this);
+  emit_byte(0xF3);
+  prefix(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xB8);
+  emit_operand(dst, src);
+}
+
+void Assembler::popcntl(Register dst, Register src) {
+  assert(VM_Version::supports_popcnt(), "must support");
+  emit_byte(0xF3);
+  int encode = prefix_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xB8);
+  emit_byte(0xC0 | encode);
+}
+
 void Assembler::popf() {
   emit_byte(0x9D);
 }
@@ -2319,6 +2355,29 @@
   emit_byte(shift);
 }
 
+void Assembler::ptest(XMMRegister dst, Address src) {
+  assert(VM_Version::supports_sse4_1(), "");
+
+  InstructionMark im(this);
+  emit_byte(0x66);
+  prefix(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0x38);
+  emit_byte(0x17);
+  emit_operand(dst, src);
+}
+
+void Assembler::ptest(XMMRegister dst, XMMRegister src) {
+  assert(VM_Version::supports_sse4_1(), "");
+
+  emit_byte(0x66);
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0x38);
+  emit_byte(0x17);
+  emit_byte(0xC0 | encode);
+}
+
 void Assembler::punpcklbw(XMMRegister dst, XMMRegister src) {
   NOT_LP64(assert(VM_Version::supports_sse2(), ""));
   emit_byte(0x66);
@@ -3218,12 +3277,6 @@
   emit_byte(0xF1);
 }
 
-void Assembler::mov_literal32(Register dst, int32_t imm32, RelocationHolder const& rspec, int format) {
-  InstructionMark im(this);
-  int encode = prefix_and_encode(dst->encoding());
-  emit_byte(0xB8 | encode);
-  emit_data((int)imm32, rspec, format);
-}
 
 #ifndef _LP64
 
@@ -3243,6 +3296,12 @@
   emit_data((int)imm32, rspec, 0);
 }
 
+void Assembler::mov_literal32(Register dst, int32_t imm32, RelocationHolder const& rspec) {
+  InstructionMark im(this);
+  int encode = prefix_and_encode(dst->encoding());
+  emit_byte(0xB8 | encode);
+  emit_data((int)imm32, rspec, 0);
+}
 
 void Assembler::popa() { // 32bit
   emit_byte(0x61);
@@ -3851,6 +3910,37 @@
   emit_data64(imm64, rspec);
 }
 
+void Assembler::mov_narrow_oop(Register dst, int32_t imm32, RelocationHolder const& rspec) {
+  InstructionMark im(this);
+  int encode = prefix_and_encode(dst->encoding());
+  emit_byte(0xB8 | encode);
+  emit_data((int)imm32, rspec, narrow_oop_operand);
+}
+
+void Assembler::mov_narrow_oop(Address dst, int32_t imm32,  RelocationHolder const& rspec) {
+  InstructionMark im(this);
+  prefix(dst);
+  emit_byte(0xC7);
+  emit_operand(rax, dst, 4);
+  emit_data((int)imm32, rspec, narrow_oop_operand);
+}
+
+void Assembler::cmp_narrow_oop(Register src1, int32_t imm32, RelocationHolder const& rspec) {
+  InstructionMark im(this);
+  int encode = prefix_and_encode(src1->encoding());
+  emit_byte(0x81);
+  emit_byte(0xF8 | encode);
+  emit_data((int)imm32, rspec, narrow_oop_operand);
+}
+
+void Assembler::cmp_narrow_oop(Address src1, int32_t imm32, RelocationHolder const& rspec) {
+  InstructionMark im(this);
+  prefix(src1);
+  emit_byte(0x81);
+  emit_operand(rax, src1, 4);
+  emit_data((int)imm32, rspec, narrow_oop_operand);
+}
+
 void Assembler::movdq(XMMRegister dst, Register src) {
   // table D-1 says MMX/SSE2
   NOT_LP64(assert(VM_Version::supports_sse2() || VM_Version::supports_mmx(), ""));
@@ -3892,6 +3982,21 @@
   emit_operand(src, dst);
 }
 
+void Assembler::movsbq(Register dst, Address src) {
+  InstructionMark im(this);
+  prefixq(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xBE);
+  emit_operand(dst, src);
+}
+
+void Assembler::movsbq(Register dst, Register src) {
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xBE);
+  emit_byte(0xC0 | encode);
+}
+
 void Assembler::movslq(Register dst, int32_t imm32) {
   // dbx shows movslq(rcx, 3) as movq     $0x0000000049000000,(%rbx)
   // and movslq(r8, 3); as movl     $0x0000000048000000,(%rbx)
@@ -3925,6 +4030,51 @@
   emit_byte(0xC0 | encode);
 }
 
+void Assembler::movswq(Register dst, Address src) {
+  InstructionMark im(this);
+  prefixq(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xBF);
+  emit_operand(dst, src);
+}
+
+void Assembler::movswq(Register dst, Register src) {
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xBF);
+  emit_byte(0xC0 | encode);
+}
+
+void Assembler::movzbq(Register dst, Address src) {
+  InstructionMark im(this);
+  prefixq(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xB6);
+  emit_operand(dst, src);
+}
+
+void Assembler::movzbq(Register dst, Register src) {
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xB6);
+  emit_byte(0xC0 | encode);
+}
+
+void Assembler::movzwq(Register dst, Address src) {
+  InstructionMark im(this);
+  prefixq(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xB7);
+  emit_operand(dst, src);
+}
+
+void Assembler::movzwq(Register dst, Register src) {
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xB7);
+  emit_byte(0xC0 | encode);
+}
+
 void Assembler::negq(Register dst) {
   int encode = prefixq_and_encode(dst->encoding());
   emit_byte(0xF7);
@@ -3983,6 +4133,25 @@
   addq(rsp, 16 * wordSize);
 }
 
+void Assembler::popcntq(Register dst, Address src) {
+  assert(VM_Version::supports_popcnt(), "must support");
+  InstructionMark im(this);
+  emit_byte(0xF3);
+  prefixq(src, dst);
+  emit_byte(0x0F);
+  emit_byte(0xB8);
+  emit_operand(dst, src);
+}
+
+void Assembler::popcntq(Register dst, Register src) {
+  assert(VM_Version::supports_popcnt(), "must support");
+  emit_byte(0xF3);
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_byte(0x0F);
+  emit_byte(0xB8);
+  emit_byte(0xC0 | encode);
+}
+
 void Assembler::popq(Address dst) {
   InstructionMark im(this);
   prefixq(dst);
@@ -6197,8 +6366,11 @@
   return off;
 }
 
-// word => int32 which seems bad for 64bit
-int MacroAssembler::load_signed_word(Register dst, Address src) {
+// Note: load_signed_short used to be called load_signed_word.
+// Although the 'w' in x86 opcodes refers to the term "word" in the assembler
+// manual, which means 16 bits, that usage is found nowhere in HotSpot code.
+// The term "word" in HotSpot means a 32- or 64-bit machine word.
+int MacroAssembler::load_signed_short(Register dst, Address src) {
   int off;
   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
@@ -6207,7 +6379,7 @@
     off = offset();
     movswl(dst, src); // movsxw
   } else {
-    off = load_unsigned_word(dst, src);
+    off = load_unsigned_short(dst, src);
     shll(dst, 16);
     sarl(dst, 16);
   }
@@ -6229,7 +6401,8 @@
   return off;
 }
 
-int MacroAssembler::load_unsigned_word(Register dst, Address src) {
+// Note: load_unsigned_short used to be called load_unsigned_word.
+int MacroAssembler::load_unsigned_short(Register dst, Address src) {
   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
   // and "3.9 Partial Register Penalties", p. 22).
   int off;
@@ -6244,6 +6417,28 @@
   return off;
 }
 
+void MacroAssembler::load_sized_value(Register dst, Address src,
+                                      int size_in_bytes, bool is_signed) {
+  switch (size_in_bytes ^ (is_signed ? -1 : 0)) {
+#ifndef _LP64
+  // For case 8, caller is responsible for manually loading
+  // the second word into another register.
+  case ~8:  // fall through:
+  case  8:  movl(                dst, src ); break;
+#else
+  case ~8:  // fall through:
+  case  8:  movq(                dst, src ); break;
+#endif
+  case ~4:  // fall through:
+  case  4:  movl(                dst, src ); break;
+  case ~2:  load_signed_short(   dst, src ); break;
+  case  2:  load_unsigned_short( dst, src ); break;
+  case ~1:  load_signed_byte(    dst, src ); break;
+  case  1:  load_unsigned_byte(  dst, src ); break;
+  default:  ShouldNotReachHere();
+  }
+}
+
 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
   if (reachable(dst)) {
     movl(as_Address(dst), src);
@@ -6463,7 +6658,8 @@
   Address index(noreg, tmp, Address::times_1);
   ExternalAddress page(os::get_memory_serialize_page());
 
-  movptr(ArrayAddress(page, index), tmp);
+  // Size of store must match masking code above
+  movl(as_Address(ArrayAddress(page, index)), tmp);
 }
 
 // Calls to C land
@@ -7049,6 +7245,300 @@
 }
 
 
+// Look up the method for a megamorphic invokeinterface call.
+// The target method is determined by <intf_klass, itable_index>.
+// The receiver klass is in recv_klass.
+// On success, the result will be in method_result, and execution falls through.
+// On failure, execution transfers to the given label.
+void MacroAssembler::lookup_interface_method(Register recv_klass,
+                                             Register intf_klass,
+                                             RegisterOrConstant itable_index,
+                                             Register method_result,
+                                             Register scan_temp,
+                                             Label& L_no_such_interface) {
+  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
+         "caller must use same register for non-constant itable index as for method");
+
+  // Compute start of first itableOffsetEntry (which is at the end of the vtable)
+  int vtable_base = instanceKlass::vtable_start_offset() * wordSize;
+  int itentry_off = itableMethodEntry::method_offset_in_bytes();
+  int scan_step   = itableOffsetEntry::size() * wordSize;
+  int vte_size    = vtableEntry::size() * wordSize;
+  Address::ScaleFactor times_vte_scale = Address::times_ptr;
+  assert(vte_size == wordSize, "else adjust times_vte_scale");
+
+  movl(scan_temp, Address(recv_klass, instanceKlass::vtable_length_offset() * wordSize));
+
+  // %%% Could store the aligned, prescaled offset in the klassoop.
+  lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
+  if (HeapWordsPerLong > 1) {
+    // Round up to align_object_offset boundary
+    // see code for instanceKlass::start_of_itable!
+    round_to(scan_temp, BytesPerLong);
+  }
+
+  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+  assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
+  lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+
+  // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
+  //   if (scan->interface() == intf) {
+  //     result = (klass + scan->offset() + itable_index);
+  //   }
+  // }
+  Label search, found_method;
+
+  for (int peel = 1; peel >= 0; peel--) {
+    movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
+    cmpptr(intf_klass, method_result);
+
+    if (peel) {
+      jccb(Assembler::equal, found_method);
+    } else {
+      jccb(Assembler::notEqual, search);
+      // (invert the test to fall through to found_method...)
+    }
+
+    if (!peel)  break;
+
+    bind(search);
+
+    // Check that the previous entry is non-null.  A null entry means that
+    // the receiver class doesn't implement the interface, and wasn't the
+    // same as when the caller was compiled.
+    testptr(method_result, method_result);
+    jcc(Assembler::zero, L_no_such_interface);
+    addptr(scan_temp, scan_step);
+  }
+
+  bind(found_method);
+
+  // Got a hit.
+  movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
+  movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+}
+
+
+void MacroAssembler::check_klass_subtype(Register sub_klass,
+                           Register super_klass,
+                           Register temp_reg,
+                           Label& L_success) {
+  Label L_failure;
+  check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
+  check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
+  bind(L_failure);
+}
+
+
+void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
+                                                   Register super_klass,
+                                                   Register temp_reg,
+                                                   Label* L_success,
+                                                   Label* L_failure,
+                                                   Label* L_slow_path,
+                                        RegisterOrConstant super_check_offset) {
+  assert_different_registers(sub_klass, super_klass, temp_reg);
+  bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
+  if (super_check_offset.is_register()) {
+    assert_different_registers(sub_klass, super_klass,
+                               super_check_offset.as_register());
+  } else if (must_load_sco) {
+    assert(temp_reg != noreg, "supply either a temp or a register offset");
+  }
+
+  Label L_fallthrough;
+  int label_nulls = 0;
+  if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
+  if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
+  if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
+  assert(label_nulls <= 1, "at most one NULL in the batch");
+
+  int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_super_cache_offset_in_bytes());
+  int sco_offset = (klassOopDesc::header_size() * HeapWordSize +
+                    Klass::super_check_offset_offset_in_bytes());
+  Address super_check_offset_addr(super_klass, sco_offset);
+
+  // Hacked jcc, which "knows" that L_fallthrough, at least, is in
+  // range of a jccb.  If this routine grows larger, reconsider at
+  // least some of these.
+#define local_jcc(assembler_cond, label)                                \
+  if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
+  else                             jcc( assembler_cond, label) /*omit semi*/
+
+  // Hacked jmp, which may only be used just before L_fallthrough.
+#define final_jmp(label)                                                \
+  if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
+  else                            jmp(label)                /*omit semi*/
+
+  // If the pointers are equal, we are done (e.g., String[] elements).
+  // This self-check enables sharing of secondary supertype arrays among
+  // non-primary types such as array-of-interface.  Otherwise, each such
+  // type would need its own customized SSA.
+  // We move this check to the front of the fast path because many
+  // type checks are in fact trivially successful in this manner,
+  // so we get a nicely predicted branch right at the start of the check.
+  cmpptr(sub_klass, super_klass);
+  local_jcc(Assembler::equal, *L_success);
+
+  // Check the supertype display:
+  if (must_load_sco) {
+    // Positive movl does right thing on LP64.
+    movl(temp_reg, super_check_offset_addr);
+    super_check_offset = RegisterOrConstant(temp_reg);
+  }
+  Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
+  cmpptr(super_klass, super_check_addr); // load displayed supertype
+
+  // This check has worked decisively for primary supers.
+  // Secondary supers are sought in the super_cache ('super_cache_addr').
+  // (Secondary supers are interfaces and very deeply nested subtypes.)
+  // This works in the same check above because of a tricky aliasing
+  // between the super_cache and the primary super display elements.
+  // (The 'super_check_addr' can address either, as the case requires.)
+  // Note that the cache is updated below if it does not help us find
+  // what we need immediately.
+  // So if it was a primary super, we can just fail immediately.
+  // Otherwise, it's the slow path for us (no success at this point).
+
+  if (super_check_offset.is_register()) {
+    local_jcc(Assembler::equal, *L_success);
+    cmpl(super_check_offset.as_register(), sc_offset);
+    if (L_failure == &L_fallthrough) {
+      local_jcc(Assembler::equal, *L_slow_path);
+    } else {
+      local_jcc(Assembler::notEqual, *L_failure);
+      final_jmp(*L_slow_path);
+    }
+  } else if (super_check_offset.as_constant() == sc_offset) {
+    // Need a slow path; fast failure is impossible.
+    if (L_slow_path == &L_fallthrough) {
+      local_jcc(Assembler::equal, *L_success);
+    } else {
+      local_jcc(Assembler::notEqual, *L_slow_path);
+      final_jmp(*L_success);
+    }
+  } else {
+    // No slow path; it's a fast decision.
+    if (L_failure == &L_fallthrough) {
+      local_jcc(Assembler::equal, *L_success);
+    } else {
+      local_jcc(Assembler::notEqual, *L_failure);
+      final_jmp(*L_success);
+    }
+  }
+
+  bind(L_fallthrough);
+
+#undef local_jcc
+#undef final_jmp
+}
+
+
+void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
+                                                   Register super_klass,
+                                                   Register temp_reg,
+                                                   Register temp2_reg,
+                                                   Label* L_success,
+                                                   Label* L_failure,
+                                                   bool set_cond_codes) {
+  assert_different_registers(sub_klass, super_klass, temp_reg);
+  if (temp2_reg != noreg)
+    assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
+#define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
+
+  Label L_fallthrough;
+  int label_nulls = 0;
+  if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
+  if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
+  assert(label_nulls <= 1, "at most one NULL in the batch");
+
+  // a couple of useful fields in sub_klass:
+  int ss_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_supers_offset_in_bytes());
+  int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
+                   Klass::secondary_super_cache_offset_in_bytes());
+  Address secondary_supers_addr(sub_klass, ss_offset);
+  Address super_cache_addr(     sub_klass, sc_offset);
+
+  // Do a linear scan of the secondary super-klass chain.
+  // This code is rarely used, so simplicity is a virtue here.
+  // The repne_scan instruction uses fixed registers, which we must spill.
+  // Don't worry too much about pre-existing connections with the input regs.
+
+  assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
+  assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
+
+  // Get super_klass value into rax (even if it was in rdi or rcx).
+  bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
+  if (super_klass != rax || UseCompressedOops) {
+    if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
+    mov(rax, super_klass);
+  }
+  if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
+  if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
+
+#ifndef PRODUCT
+  int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
+  ExternalAddress pst_counter_addr((address) pst_counter);
+  NOT_LP64(  incrementl(pst_counter_addr) );
+  LP64_ONLY( lea(rcx, pst_counter_addr) );
+  LP64_ONLY( incrementl(Address(rcx, 0)) );
+#endif //PRODUCT
+
+  // We will consult the secondary-super array.
+  movptr(rdi, secondary_supers_addr);
+  // Load the array length.  (Positive movl does right thing on LP64.)
+  movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
+  // Skip to start of data.
+  addptr(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
+
+  // Scan RCX words at [RDI] for an occurrence of RAX.
+  // Set NZ/Z based on last compare.
+#ifdef _LP64
+  // This part is tricky, as values in supers array could be 32 or 64 bit wide
+  // and we store values in objArrays always encoded, thus we need to encode
+  // the value of rax before repne.  Note that rax is dead after the repne.
+  if (UseCompressedOops) {
+    encode_heap_oop_not_null(rax);
+    // The superclass is never null; it would be a basic system error if a null
+    // pointer were to sneak in here.  Note that we have already loaded the
+    // Klass::super_check_offset from the super_klass in the fast path,
+    // so if there is a null in that register, we are already in the afterlife.
+    repne_scanl();
+  } else
+#endif // _LP64
+    repne_scan();
+
+  // Unspill the temp. registers:
+  if (pushed_rdi)  pop(rdi);
+  if (pushed_rcx)  pop(rcx);
+  if (pushed_rax)  pop(rax);
+
+  if (set_cond_codes) {
+    // Special hack for the AD files:  rdi is guaranteed non-zero.
+    assert(!pushed_rdi, "rdi must be left non-NULL");
+    // Also, the condition codes are properly set Z/NZ on succeed/failure.
+  }
+
+  if (L_failure == &L_fallthrough)
+        jccb(Assembler::notEqual, *L_failure);
+  else  jcc(Assembler::notEqual, *L_failure);
+
+  // Success.  Cache the super we found and proceed in triumph.
+  movptr(super_cache_addr, super_klass);
+
+  if (L_success != &L_fallthrough) {
+    jmp(*L_success);
+  }
+
+#undef IS_A_TEMP
+
+  bind(L_fallthrough);
+}
+
+
 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
   ucomisd(dst, as_Address(src));
 }
@@ -7094,6 +7584,31 @@
 }
 
 
+RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
+                                                      Register tmp,
+                                                      int offset) {
+  intptr_t value = *delayed_value_addr;
+  if (value != 0)
+    return RegisterOrConstant(value + offset);
+
+  // load indirectly to solve generation ordering problem
+  movptr(tmp, ExternalAddress((address) delayed_value_addr));
+
+#ifdef ASSERT
+  Label L;
+  testl(tmp, tmp);
+  jccb(Assembler::notZero, L);
+  hlt();
+  bind(L);
+#endif
+
+  if (offset != 0)
+    addptr(tmp, offset);
+
+  return RegisterOrConstant(tmp);
+}
+
+
 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
   if (!VerifyOops) return;
 
@@ -7517,14 +8032,21 @@
 void MacroAssembler::load_prototype_header(Register dst, Register src) {
 #ifdef _LP64
   if (UseCompressedOops) {
+    assert (Universe::heap() != NULL, "java heap should be initialized");
     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
-    movq(dst, Address(r12_heapbase, dst, Address::times_8, Klass::prototype_header_offset_in_bytes() + klassOopDesc::klass_part_offset_in_bytes()));
+    if (Universe::narrow_oop_shift() != 0) {
+      assert(Address::times_8 == LogMinObjAlignmentInBytes &&
+             Address::times_8 == Universe::narrow_oop_shift(), "decode alg wrong");
+      movq(dst, Address(r12_heapbase, dst, Address::times_8, Klass::prototype_header_offset_in_bytes() + klassOopDesc::klass_part_offset_in_bytes()));
+    } else {
+      movq(dst, Address(dst, Klass::prototype_header_offset_in_bytes() + klassOopDesc::klass_part_offset_in_bytes()));
+    }
   } else
 #endif
-    {
-      movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
-      movptr(dst, Address(dst, Klass::prototype_header_offset_in_bytes() + klassOopDesc::klass_part_offset_in_bytes()));
-    }
+  {
+    movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
+    movptr(dst, Address(dst, Klass::prototype_header_offset_in_bytes() + klassOopDesc::klass_part_offset_in_bytes()));
+  }
 }
 
 void MacroAssembler::store_klass(Register dst, Register src) {
@@ -7567,11 +8089,20 @@
 // Algorithm must match oop.inline.hpp encode_heap_oop.
 void MacroAssembler::encode_heap_oop(Register r) {
   assert (UseCompressedOops, "should be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  if (Universe::narrow_oop_base() == NULL) {
+    verify_oop(r, "broken oop in encode_heap_oop");
+    if (Universe::narrow_oop_shift() != 0) {
+      assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
+      shrq(r, LogMinObjAlignmentInBytes);
+    }
+    return;
+  }
 #ifdef ASSERT
   if (CheckCompressedOops) {
     Label ok;
     push(rscratch1); // cmpptr trashes rscratch1
-    cmpptr(r12_heapbase, ExternalAddress((address)Universe::heap_base_addr()));
+    cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_oop_base_addr()));
     jcc(Assembler::equal, ok);
     stop("MacroAssembler::encode_heap_oop: heap base corrupted?");
     bind(ok);
@@ -7587,6 +8118,7 @@
 
 void MacroAssembler::encode_heap_oop_not_null(Register r) {
   assert (UseCompressedOops, "should be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
 #ifdef ASSERT
   if (CheckCompressedOops) {
     Label ok;
@@ -7597,12 +8129,18 @@
   }
 #endif
   verify_oop(r, "broken oop in encode_heap_oop_not_null");
-  subq(r, r12_heapbase);
-  shrq(r, LogMinObjAlignmentInBytes);
+  if (Universe::narrow_oop_base() != NULL) {
+    subq(r, r12_heapbase);
+  }
+  if (Universe::narrow_oop_shift() != 0) {
+    assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
+    shrq(r, LogMinObjAlignmentInBytes);
+  }
 }
 
 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
   assert (UseCompressedOops, "should be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
 #ifdef ASSERT
   if (CheckCompressedOops) {
     Label ok;
@@ -7616,18 +8154,32 @@
   if (dst != src) {
     movq(dst, src);
   }
-  subq(dst, r12_heapbase);
-  shrq(dst, LogMinObjAlignmentInBytes);
+  if (Universe::narrow_oop_base() != NULL) {
+    subq(dst, r12_heapbase);
+  }
+  if (Universe::narrow_oop_shift() != 0) {
+    assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
+    shrq(dst, LogMinObjAlignmentInBytes);
+  }
 }
 
 void  MacroAssembler::decode_heap_oop(Register r) {
   assert (UseCompressedOops, "should be compressed");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  if (Universe::narrow_oop_base() == NULL) {
+    if (Universe::narrow_oop_shift() != 0) {
+      assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
+      shlq(r, LogMinObjAlignmentInBytes);
+    }
+    verify_oop(r, "broken oop in decode_heap_oop");
+    return;
+  }
 #ifdef ASSERT
   if (CheckCompressedOops) {
     Label ok;
     push(rscratch1);
     cmpptr(r12_heapbase,
-           ExternalAddress((address)Universe::heap_base_addr()));
+           ExternalAddress((address)Universe::narrow_oop_base_addr()));
     jcc(Assembler::equal, ok);
     stop("MacroAssembler::decode_heap_oop: heap base corrupted?");
     bind(ok);
@@ -7651,32 +8203,76 @@
 
 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
   assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
   // Cannot assert, unverified entry point counts instructions (see .ad file)
   // vtableStubs also counts instructions in pd_code_size_limit.
   // Also do not verify_oop as this is called by verify_oop.
-  assert(Address::times_8 == LogMinObjAlignmentInBytes, "decode alg wrong");
-  leaq(r, Address(r12_heapbase, r, Address::times_8, 0));
+  if (Universe::narrow_oop_base() == NULL) {
+    if (Universe::narrow_oop_shift() != 0) {
+      assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
+      shlq(r, LogMinObjAlignmentInBytes);
+    }
+  } else {
+      assert (Address::times_8 == LogMinObjAlignmentInBytes &&
+              Address::times_8 == Universe::narrow_oop_shift(), "decode alg wrong");
+    leaq(r, Address(r12_heapbase, r, Address::times_8, 0));
+  }
 }
 
 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
   assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
   // Cannot assert, unverified entry point counts instructions (see .ad file)
   // vtableStubs also counts instructions in pd_code_size_limit.
   // Also do not verify_oop as this is called by verify_oop.
-  assert(Address::times_8 == LogMinObjAlignmentInBytes, "decode alg wrong");
-  leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
+  if (Universe::narrow_oop_shift() != 0) {
+    assert (Address::times_8 == LogMinObjAlignmentInBytes &&
+            Address::times_8 == Universe::narrow_oop_shift(), "decode alg wrong");
+    leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
+  } else if (dst != src) {
+    movq(dst, src);
+  }
 }
 
 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
-  assert(oop_recorder() != NULL, "this assembler needs an OopRecorder");
+  assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
+  int oop_index = oop_recorder()->find_index(obj);
+  RelocationHolder rspec = oop_Relocation::spec(oop_index);
+  mov_narrow_oop(dst, oop_index, rspec);
+}
+
+void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
+  assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
   int oop_index = oop_recorder()->find_index(obj);
   RelocationHolder rspec = oop_Relocation::spec(oop_index);
-  mov_literal32(dst, oop_index, rspec, narrow_oop_operand);
+  mov_narrow_oop(dst, oop_index, rspec);
+}
+
+void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
+  assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
+  int oop_index = oop_recorder()->find_index(obj);
+  RelocationHolder rspec = oop_Relocation::spec(oop_index);
+  Assembler::cmp_narrow_oop(dst, oop_index, rspec);
+}
+
+void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
+  assert (UseCompressedOops, "should only be used for compressed headers");
+  assert (Universe::heap() != NULL, "java heap should be initialized");
+  assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
+  int oop_index = oop_recorder()->find_index(obj);
+  RelocationHolder rspec = oop_Relocation::spec(oop_index);
+  Assembler::cmp_narrow_oop(dst, oop_index, rspec);
 }
 
 void MacroAssembler::reinit_heapbase() {
   if (UseCompressedOops) {
-    movptr(r12_heapbase, ExternalAddress((address)Universe::heap_base_addr()));
+    movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_oop_base_addr()));
   }
 }
 #endif // _LP64
--- a/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -153,6 +153,21 @@
     times_8  =  3,
     times_ptr = LP64_ONLY(times_8) NOT_LP64(times_4)
   };
+  static ScaleFactor times(int size) {
+    assert(size >= 1 && size <= 8 && is_power_of_2(size), "bad scale size");
+    if (size == 8)  return times_8;
+    if (size == 4)  return times_4;
+    if (size == 2)  return times_2;
+    return times_1;
+  }
+  static int scale_size(ScaleFactor scale) {
+    assert(scale != no_scale, "");
+    assert(((1 << (int)times_1) == 1 &&
+            (1 << (int)times_2) == 2 &&
+            (1 << (int)times_4) == 4 &&
+            (1 << (int)times_8) == 8), "");
+    return (1 << (int)scale);
+  }
 
  private:
   Register         _base;
@@ -197,6 +212,22 @@
            "inconsistent address");
   }
 
+  Address(Register base, RegisterOrConstant index, ScaleFactor scale = times_1, int disp = 0)
+    : _base (base),
+      _index(index.register_or_noreg()),
+      _scale(scale),
+      _disp (disp + (index.constant_or_zero() * scale_size(scale))) {
+    if (!index.is_register())  scale = Address::no_scale;
+    assert(!_index->is_valid() == (scale == Address::no_scale),
+           "inconsistent address");
+  }
+
+  Address plus_disp(int disp) const {
+    Address a = (*this);
+    a._disp += disp;
+    return a;
+  }
+
   // The following two overloads are used in connection with the
   // ByteSize type (see sizes.hpp).  They simplify the use of
   // ByteSize'd arguments in assembly code. Note that their equivalent
@@ -224,6 +255,17 @@
     assert(!index->is_valid() == (scale == Address::no_scale),
            "inconsistent address");
   }
+
+  Address(Register base, RegisterOrConstant index, ScaleFactor scale, ByteSize disp)
+    : _base (base),
+      _index(index.register_or_noreg()),
+      _scale(scale),
+      _disp (in_bytes(disp) + (index.constant_or_zero() * scale_size(scale))) {
+    if (!index.is_register())  scale = Address::no_scale;
+    assert(!_index->is_valid() == (scale == Address::no_scale),
+           "inconsistent address");
+  }
+
 #endif // ASSERT
 
   // accessors
@@ -236,11 +278,10 @@
   // Convert the raw encoding form into the form expected by the constructor for
   // Address.  An index of 4 (rsp) corresponds to having no index, so convert
   // that to noreg for the Address constructor.
-  static Address make_raw(int base, int index, int scale, int disp);
+  static Address make_raw(int base, int index, int scale, int disp, bool disp_is_oop);
 
   static Address make_array(ArrayAddress);
 
-
  private:
   bool base_needs_rex() const {
     return _base != noreg && _base->encoding() >= 8;
@@ -537,20 +578,25 @@
 
   // These are all easily abused and hence protected
 
-  void mov_literal32(Register dst, int32_t imm32, RelocationHolder const& rspec, int format = 0);
-
   // 32BIT ONLY SECTION
 #ifndef _LP64
   // Make these disappear in 64bit mode since they would never be correct
   void cmp_literal32(Register src1, int32_t imm32, RelocationHolder const& rspec);   // 32BIT ONLY
   void cmp_literal32(Address src1, int32_t imm32, RelocationHolder const& rspec);    // 32BIT ONLY
 
+  void mov_literal32(Register dst, int32_t imm32, RelocationHolder const& rspec);    // 32BIT ONLY
   void mov_literal32(Address dst, int32_t imm32, RelocationHolder const& rspec);     // 32BIT ONLY
 
   void push_literal32(int32_t imm32, RelocationHolder const& rspec);                 // 32BIT ONLY
 #else
   // 64BIT ONLY SECTION
   void mov_literal64(Register dst, intptr_t imm64, RelocationHolder const& rspec);   // 64BIT ONLY
+
+  void cmp_narrow_oop(Register src1, int32_t imm32, RelocationHolder const& rspec);
+  void cmp_narrow_oop(Address src1, int32_t imm32, RelocationHolder const& rspec);
+
+  void mov_narrow_oop(Register dst, int32_t imm32, RelocationHolder const& rspec);
+  void mov_narrow_oop(Address dst, int32_t imm32, RelocationHolder const& rspec);
 #endif // _LP64
 
   // These are unique in that we are ensured by the caller that the 32bit
@@ -1022,15 +1068,23 @@
     LoadLoad   = 1 << 0
   };
 
-  // Serializes memory.
+  // Serializes memory and blows flags
   void membar(Membar_mask_bits order_constraint) {
-    // We only have to handle StoreLoad and LoadLoad
-    if (order_constraint & StoreLoad) {
-      // MFENCE subsumes LFENCE
-      mfence();
-    } /* [jk] not needed currently: else if (order_constraint & LoadLoad) {
-         lfence();
-    } */
+    if (os::is_MP()) {
+      // We only have to handle StoreLoad
+      if (order_constraint & StoreLoad) {
+        // All usable chips support "locked" instructions which suffice
+        // as barriers, and are much faster than the alternative of
+        // using cpuid instruction. We use here a locked add [esp],0.
+        // This is conveniently otherwise a no-op except for blowing
+        // flags.
+        // Any change to this code may need to revisit other places in
+        // the code where this idiom is used, in particular the
+        // orderAccess code.
+        lock();
+        addl(Address(rsp, 0), 0);// Assert the lock# signal here
+      }
+    }
   }
 
   void mfence();
@@ -1097,6 +1151,9 @@
   void movsbl(Register dst, Register src);
 
 #ifdef _LP64
+  void movsbq(Register dst, Address src);
+  void movsbq(Register dst, Register src);
+
   // Move signed 32bit immediate to 64bit extending sign
   void movslq(Address dst, int32_t imm64);
   void movslq(Register dst, int32_t imm64);
@@ -1109,6 +1166,11 @@
   void movswl(Register dst, Address src);
   void movswl(Register dst, Register src);
 
+#ifdef _LP64
+  void movswq(Register dst, Address src);
+  void movswq(Register dst, Register src);
+#endif
+
   void movw(Address dst, int imm16);
   void movw(Register dst, Address src);
   void movw(Address dst, Register src);
@@ -1116,9 +1178,19 @@
   void movzbl(Register dst, Address src);
   void movzbl(Register dst, Register src);
 
+#ifdef _LP64
+  void movzbq(Register dst, Address src);
+  void movzbq(Register dst, Register src);
+#endif
+
   void movzwl(Register dst, Address src);
   void movzwl(Register dst, Register src);
 
+#ifdef _LP64
+  void movzwq(Register dst, Address src);
+  void movzwq(Register dst, Register src);
+#endif
+
   void mull(Address src);
   void mull(Register src);
 
@@ -1154,12 +1226,24 @@
   void orq(Register dst, Address src);
   void orq(Register dst, Register src);
 
+  // SSE4.2 string instructions
+  void pcmpestri(XMMRegister xmm1, XMMRegister xmm2, int imm8);
+  void pcmpestri(XMMRegister xmm1, Address src, int imm8);
+
   void popl(Address dst);
 
 #ifdef _LP64
   void popq(Address dst);
 #endif
 
+  void popcntl(Register dst, Address src);
+  void popcntl(Register dst, Register src);
+
+#ifdef _LP64
+  void popcntq(Register dst, Address src);
+  void popcntq(Register dst, Register src);
+#endif
+
   // Prefetches (SSE, SSE2, 3DNOW only)
 
   void prefetchnta(Address src);
@@ -1180,6 +1264,10 @@
   // Shift Right Logical Quadword Immediate
   void psrlq(XMMRegister dst, int shift);
 
+  // Logical Compare Double Quadword
+  void ptest(XMMRegister dst, XMMRegister src);
+  void ptest(XMMRegister dst, Address src);
+
   // Interleave Low Bytes
   void punpcklbw(XMMRegister dst, XMMRegister src);
 
@@ -1393,17 +1481,20 @@
 
   // The following 4 methods return the offset of the appropriate move instruction
 
-  // Support for fast byte/word loading with zero extension (depending on particular CPU)
+  // Support for fast byte/short loading with zero extension (depending on particular CPU)
   int load_unsigned_byte(Register dst, Address src);
-  int load_unsigned_word(Register dst, Address src);
-
-  // Support for fast byte/word loading with sign extension (depending on particular CPU)
+  int load_unsigned_short(Register dst, Address src);
+
+  // Support for fast byte/short loading with sign extension (depending on particular CPU)
   int load_signed_byte(Register dst, Address src);
-  int load_signed_word(Register dst, Address src);
+  int load_signed_short(Register dst, Address src);
 
   // Support for sign-extension (hi:lo = extend_sign(lo))
   void extend_sign(Register hi, Register lo);
 
+  // Loading values by size and signed-ness
+  void load_sized_value(Register dst, Address src, int size_in_bytes, bool is_signed);
+
   // Support for inc/dec with optimal instruction selection depending on value
 
   void increment(Register reg, int value = 1) { LP64_ONLY(incrementq(reg, value)) NOT_LP64(incrementl(reg, value)) ; }
@@ -1585,6 +1676,9 @@
   void decode_heap_oop_not_null(Register dst, Register src);
 
   void set_narrow_oop(Register dst, jobject obj);
+  void set_narrow_oop(Address dst, jobject obj);
+  void cmp_narrow_oop(Register dst, jobject obj);
+  void cmp_narrow_oop(Address dst, jobject obj);
 
   // if heap base register is used - reinit it with the correct value
   void reinit_heapbase();
@@ -1721,6 +1815,48 @@
   );
   void tlab_refill(Label& retry_tlab, Label& try_eden, Label& slow_case);
 
+  // interface method calling
+  void lookup_interface_method(Register recv_klass,
+                               Register intf_klass,
+                               RegisterOrConstant itable_index,
+                               Register method_result,
+                               Register scan_temp,
+                               Label& no_such_interface);
+
+  // Test sub_klass against super_klass, with fast and slow paths.
+
+  // The fast path produces a tri-state answer: yes / no / maybe-slow.
+  // One of the three labels can be NULL, meaning take the fall-through.
+  // If super_check_offset is -1, the value is loaded up from super_klass.
+  // No registers are killed, except temp_reg.
+  void check_klass_subtype_fast_path(Register sub_klass,
+                                     Register super_klass,
+                                     Register temp_reg,
+                                     Label* L_success,
+                                     Label* L_failure,
+                                     Label* L_slow_path,
+                RegisterOrConstant super_check_offset = RegisterOrConstant(-1));
+
+  // The rest of the type check; must be wired to a corresponding fast path.
+  // It does not repeat the fast path logic, so don't use it standalone.
+  // The temp_reg and temp2_reg can be noreg, if no temps are available.
+  // Updates the sub's secondary super cache as necessary.
+  // If set_cond_codes, condition codes will be Z on success, NZ on failure.
+  void check_klass_subtype_slow_path(Register sub_klass,
+                                     Register super_klass,
+                                     Register temp_reg,
+                                     Register temp2_reg,
+                                     Label* L_success,
+                                     Label* L_failure,
+                                     bool set_cond_codes = false);
+
+  // Simplified, combined version, good for typical uses.
+  // Falls through on failure.
+  void check_klass_subtype(Register sub_klass,
+                           Register super_klass,
+                           Register temp_reg,
+                           Label& L_success);
+
   //----
   void set_word_if_not_zero(Register reg); // sets reg to 1 if not zero, otherwise 0
 
@@ -1763,6 +1899,10 @@
   // stack overflow + shadow pages.  Also, clobbers tmp
   void bang_stack_size(Register size, Register tmp);
 
+  virtual RegisterOrConstant delayed_value_impl(intptr_t* delayed_value_addr,
+                                                Register tmp,
+                                                int offset);
+
   // Support for serializing memory accesses between threads
   void serialize_memory(Register thread, Register tmp);
 
--- a/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -554,8 +554,8 @@
   __ jcc (Assembler::zero, noLoop);
 
   // compare first characters
-  __ load_unsigned_word(rcx, Address(rdi, 0));
-  __ load_unsigned_word(rbx, Address(rsi, 0));
+  __ load_unsigned_short(rcx, Address(rdi, 0));
+  __ load_unsigned_short(rbx, Address(rsi, 0));
   __ subl(rcx, rbx);
   __ jcc(Assembler::notZero, haveResult);
   // starting loop
@@ -574,8 +574,8 @@
   Label loop;
   __ align(wordSize);
   __ bind(loop);
-  __ load_unsigned_word(rcx, Address(rdi, rax, Address::times_2, 0));
-  __ load_unsigned_word(rbx, Address(rsi, rax, Address::times_2, 0));
+  __ load_unsigned_short(rcx, Address(rdi, rax, Address::times_2, 0));
+  __ load_unsigned_short(rbx, Address(rsi, rax, Address::times_2, 0));
   __ subl(rcx, rbx);
   __ jcc(Assembler::notZero, haveResult);
   __ increment(rax);
@@ -1598,18 +1598,9 @@
 
     // get instance klass
     __ movptr(k_RInfo, Address(k_RInfo, objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc)));
-    // get super_check_offset
-    __ movl(Rtmp1, Address(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes()));
-    // See if we get an immediate positive hit
-    __ cmpptr(k_RInfo, Address(klass_RInfo, Rtmp1, Address::times_1));
-    __ jcc(Assembler::equal, done);
-    // check for immediate negative hit
-    __ cmpl(Rtmp1, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-    __ jcc(Assembler::notEqual, *stub->entry());
-    // check for self
-    __ cmpptr(klass_RInfo, k_RInfo);
-    __ jcc(Assembler::equal, done);
-
+    // perform the fast part of the checking logic
+    __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, &done, stub->entry(), NULL);
+    // call out-of-line instance of __ check_klass_subtype_slow_path(...):
     __ push(klass_RInfo);
     __ push(k_RInfo);
     __ call(RuntimeAddress(Runtime1::entry_for(Runtime1::slow_subtype_check_id)));
@@ -1735,17 +1726,9 @@
         }
         __ bind(done);
       } else {
-        __ movl(Rtmp1, Address(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes()));
-        // See if we get an immediate positive hit
-        __ cmpptr(k_RInfo, Address(klass_RInfo, Rtmp1, Address::times_1));
-        __ jcc(Assembler::equal, done);
-        // check for immediate negative hit
-        __ cmpl(Rtmp1, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-        __ jcc(Assembler::notEqual, *stub->entry());
-        // check for self
-        __ cmpptr(klass_RInfo, k_RInfo);
-        __ jcc(Assembler::equal, done);
-
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, &done, stub->entry(), NULL);
+        // call out-of-line instance of __ check_klass_subtype_slow_path(...):
         __ push(klass_RInfo);
         __ push(k_RInfo);
         __ call(RuntimeAddress(Runtime1::entry_for(Runtime1::slow_subtype_check_id)));
@@ -1821,23 +1804,15 @@
           __ pop(dst);
           __ jmp(done);
         }
-      } else {
-#else
-      { // YUCK
+      }
+        else // next block is unconditional if LP64:
 #endif // LP64
+      {
         assert(dst != klass_RInfo && dst != k_RInfo, "need 3 registers");
 
-        __ movl(dst, Address(k_RInfo, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes()));
-        // See if we get an immediate positive hit
-        __ cmpptr(k_RInfo, Address(klass_RInfo, dst, Address::times_1));
-        __ jcc(Assembler::equal, one);
-        // check for immediate negative hit
-        __ cmpl(dst, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-        __ jcc(Assembler::notEqual, zero);
-        // check for self
-        __ cmpptr(klass_RInfo, k_RInfo);
-        __ jcc(Assembler::equal, one);
-
+        // perform the fast part of the checking logic
+        __ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, dst, &one, &zero, NULL);
+        // call out-of-line instance of __ check_klass_subtype_slow_path(...):
         __ push(klass_RInfo);
         __ push(k_RInfo);
         __ call(RuntimeAddress(Runtime1::entry_for(Runtime1::slow_subtype_check_id)));
--- a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -501,7 +501,7 @@
     LIRItem right(x->y(), this);
 
     left.load_item();
-    // dont load constants to save register
+    // don't load constants to save register
     right.load_nonconstant();
     rlock_result(x);
     arithmetic_op_long(x->op(), x->operand(), left.result(), right.result(), NULL);
--- a/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1354,6 +1354,13 @@
 
     case slow_subtype_check_id:
       {
+        // Typical calling sequence:
+        // __ push(klass_RInfo);  // object klass or other subclass
+        // __ push(sup_k_RInfo);  // array element klass or other superclass
+        // __ call(slow_subtype_check);
+        // Note that the subclass is pushed first, and is therefore deepest.
+        // Previous versions of this code reversed the names 'sub' and 'super'.
+        // This was operationally harmless but made the code unreadable.
         enum layout {
           rax_off, SLOT2(raxH_off)
           rcx_off, SLOT2(rcxH_off)
@@ -1361,9 +1368,10 @@
           rdi_off, SLOT2(rdiH_off)
           // saved_rbp_off, SLOT2(saved_rbpH_off)
           return_off, SLOT2(returnH_off)
-          sub_off, SLOT2(subH_off)
-          super_off, SLOT2(superH_off)
-          framesize
+          sup_k_off, SLOT2(sup_kH_off)
+          klass_off, SLOT2(superH_off)
+          framesize,
+          result_off = klass_off  // deepest argument is also the return value
         };
 
         __ set_info("slow_subtype_check", dont_gc_arguments);
@@ -1373,19 +1381,14 @@
         __ push(rax);
 
         // This is called by pushing args and not with C abi
-        __ movptr(rsi, Address(rsp, (super_off) * VMRegImpl::stack_slot_size)); // super
-        __ movptr(rax, Address(rsp, (sub_off  ) * VMRegImpl::stack_slot_size)); // sub
-
-        __ movptr(rdi,Address(rsi,sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes()));
-        // since size is postive movl does right thing on 64bit
-        __ movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
-        __ addptr(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
+        __ movptr(rsi, Address(rsp, (klass_off) * VMRegImpl::stack_slot_size)); // subclass
+        __ movptr(rax, Address(rsp, (sup_k_off) * VMRegImpl::stack_slot_size)); // superclass
 
         Label miss;
-        __ repne_scan();
-        __ jcc(Assembler::notEqual, miss);
-        __ movptr(Address(rsi,sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes()), rax);
-        __ movptr(Address(rsp, (super_off) * VMRegImpl::stack_slot_size), 1); // result
+        __ check_klass_subtype_slow_path(rsi, rax, rcx, rdi, NULL, &miss);
+
+        // fallthrough on success:
+        __ movptr(Address(rsp, (result_off) * VMRegImpl::stack_slot_size), 1); // result
         __ pop(rax);
         __ pop(rcx);
         __ pop(rsi);
@@ -1393,7 +1396,7 @@
         __ ret(0);
 
         __ bind(miss);
-        __ movptr(Address(rsp, (super_off) * VMRegImpl::stack_slot_size), NULL_WORD); // result
+        __ movptr(Address(rsp, (result_off) * VMRegImpl::stack_slot_size), NULL_WORD); // result
         __ pop(rax);
         __ pop(rcx);
         __ pop(rsi);
--- a/hotspot/src/cpu/x86/vm/cppInterpreter_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/cppInterpreter_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -513,7 +513,7 @@
     // compute full expression stack limit
 
     const Address size_of_stack    (rbx, methodOopDesc::max_stack_offset());
-    __ load_unsigned_word(rdx, size_of_stack);                            // get size of expression stack in words
+    __ load_unsigned_short(rdx, size_of_stack);                           // get size of expression stack in words
     __ negptr(rdx);                                                       // so we can subtract in next step
     // Allocate expression stack
     __ lea(rsp, Address(rsp, rdx, Address::times_ptr));
@@ -523,7 +523,7 @@
 #ifdef _LP64
   // Make sure stack is properly aligned and sized for the abi
   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
-  __ andptr(rsp, -16); // must be 16 byte boundry (see amd64 ABI)
+  __ andptr(rsp, -16); // must be 16 byte boundary (see amd64 ABI)
 #endif // _LP64
 
 
@@ -659,7 +659,7 @@
     // Always give one monitor to allow us to start interp if sync method.
     // Any additional monitors need a check when moving the expression stack
     const int one_monitor = frame::interpreter_frame_monitor_size() * wordSize;
-  __ load_unsigned_word(rax, size_of_stack);                            // get size of expression stack in words
+  __ load_unsigned_short(rax, size_of_stack);                           // get size of expression stack in words
   __ lea(rax, Address(noreg, rax, Interpreter::stackElementScale(), one_monitor));
   __ lea(rax, Address(rax, rdx, Interpreter::stackElementScale(), overhead_size));
 
@@ -863,13 +863,13 @@
     __ bind(notByte);
     __ cmpl(rdx, stos);
     __ jcc(Assembler::notEqual, notShort);
-    __ load_signed_word(rax, field_address);
+    __ load_signed_short(rax, field_address);
     __ jmp(xreturn_path);
 
     __ bind(notShort);
     __ cmpl(rdx, ctos);
     __ jcc(Assembler::notEqual, notChar);
-    __ load_unsigned_word(rax, field_address);
+    __ load_unsigned_short(rax, field_address);
     __ jmp(xreturn_path);
 
     __ bind(notChar);
@@ -937,7 +937,7 @@
   const Register locals = rdi;
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // rbx: methodOop
   // rcx: size of parameters
@@ -970,7 +970,7 @@
 #ifdef _LP64
     // duplicate the alignment rsp got after setting stack_base
     __ subptr(rax, frame::arg_reg_save_area_bytes); // windows
-    __ andptr(rax, -16); // must be 16 byte boundry (see amd64 ABI)
+    __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
 #endif // _LP64
     __ cmpptr(rax, rsp);
     __ jcc(Assembler::equal, L);
@@ -1062,12 +1062,12 @@
   // allocate space for parameters
   __ movptr(method, STATE(_method));
   __ verify_oop(method);
-  __ load_unsigned_word(t, Address(method, methodOopDesc::size_of_parameters_offset()));
+  __ load_unsigned_short(t, Address(method, methodOopDesc::size_of_parameters_offset()));
   __ shll(t, 2);
 #ifdef _LP64
   __ subptr(rsp, t);
   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
-  __ andptr(rsp, -16); // must be 16 byte boundry (see amd64 ABI)
+  __ andptr(rsp, -16); // must be 16 byte boundary (see amd64 ABI)
 #else
   __ addptr(t, 2*wordSize);     // allocate two more slots for JNIEnv and possible mirror
   __ subptr(rsp, t);
@@ -1659,11 +1659,11 @@
   // const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset * wordSize - (int)sizeof(BasicObjectLock));
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // rbx: methodOop
   // rcx: size of parameters
-  __ load_unsigned_word(rdx, size_of_locals);                      // get size of locals in words
+  __ load_unsigned_short(rdx, size_of_locals);                     // get size of locals in words
 
   __ subptr(rdx, rcx);                                             // rdx = no. of additional locals
 
@@ -1949,7 +1949,7 @@
   __ movptr(rbx, STATE(_result._to_call._callee));
 
   // callee left args on top of expression stack, remove them
-  __ load_unsigned_word(rcx, Address(rbx, methodOopDesc::size_of_parameters_offset()));
+  __ load_unsigned_short(rcx, Address(rbx, methodOopDesc::size_of_parameters_offset()));
   __ lea(rsp, Address(rsp, rcx, Address::times_ptr));
 
   __ movl(rcx, Address(rbx, methodOopDesc::result_index_offset()));
@@ -2119,7 +2119,7 @@
   // Make it look like call_stub calling conventions
 
   // Get (potential) receiver
-  __ load_unsigned_word(rcx, size_of_parameters);                     // get size of parameters in words
+  __ load_unsigned_short(rcx, size_of_parameters);                   // get size of parameters in words
 
   ExternalAddress recursive(CAST_FROM_FN_PTR(address, RecursiveInterpreterActivation));
   __ pushptr(recursive.addr());                                      // make it look good in the debugger
--- a/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/globals_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/globals_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -60,6 +60,7 @@
 define_pd_global(intx, StackShadowPages, 3 DEBUG_ONLY(+1));
 #endif // AMD64
 define_pd_global(intx,  InlineFrequencyCount,     100);
+define_pd_global(intx,  InlineSmallCode,          1000);
 define_pd_global(intx,  PreInflateSpin,           10);
 
 define_pd_global(intx, StackYellowPages, 2);
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -192,7 +192,7 @@
 void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache, Register index, int bcp_offset) {
   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
   assert(cache != index, "must use different registers");
-  load_unsigned_word(index, Address(rsi, bcp_offset));
+  load_unsigned_short(index, Address(rsi, bcp_offset));
   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
   assert(sizeof(ConstantPoolCacheEntry) == 4*wordSize, "adjust code below");
   shlptr(index, 2); // convert from field index to ConstantPoolCacheEntry index
@@ -202,7 +202,7 @@
 void InterpreterMacroAssembler::get_cache_entry_pointer_at_bcp(Register cache, Register tmp, int bcp_offset) {
   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
   assert(cache != tmp, "must use different register");
-  load_unsigned_word(tmp, Address(rsi, bcp_offset));
+  load_unsigned_short(tmp, Address(rsi, bcp_offset));
   assert(sizeof(ConstantPoolCacheEntry) == 4*wordSize, "adjust code below");
                                // convert from field index to ConstantPoolCacheEntry index
                                // and from word offset to byte offset
@@ -219,47 +219,16 @@
   // Resets EDI to locals.  Register sub_klass cannot be any of the above.
 void InterpreterMacroAssembler::gen_subtype_check( Register Rsub_klass, Label &ok_is_subtype ) {
   assert( Rsub_klass != rax, "rax, holds superklass" );
-  assert( Rsub_klass != rcx, "rcx holds 2ndary super array length" );
-  assert( Rsub_klass != rdi, "rdi holds 2ndary super array scan ptr" );
-  Label not_subtype, loop;
+  assert( Rsub_klass != rcx, "used as a temp" );
+  assert( Rsub_klass != rdi, "used as a temp, restored from locals" );
 
   // Profile the not-null value's klass.
-  profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, rdi
-
-  // Load the super-klass's check offset into ECX
-  movl( rcx, Address(rax, sizeof(oopDesc) + Klass::super_check_offset_offset_in_bytes() ) );
-  // Load from the sub-klass's super-class display list, or a 1-word cache of
-  // the secondary superclass list, or a failing value with a sentinel offset
-  // if the super-klass is an interface or exceptionally deep in the Java
-  // hierarchy and we have to scan the secondary superclass list the hard way.
-  // See if we get an immediate positive hit
-  cmpptr( rax, Address(Rsub_klass,rcx,Address::times_1) );
-  jcc( Assembler::equal,ok_is_subtype );
+  profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, reloads rdi
 
-  // Check for immediate negative hit
-  cmpl( rcx, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes() );
-  jcc( Assembler::notEqual, not_subtype );
-  // Check for self
-  cmpptr( Rsub_klass, rax );
-  jcc( Assembler::equal, ok_is_subtype );
+  // Do the check.
+  check_klass_subtype(Rsub_klass, rax, rcx, ok_is_subtype); // blows rcx
 
-  // Now do a linear scan of the secondary super-klass chain.
-  movptr( rdi, Address(Rsub_klass, sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes()) );
-  // EDI holds the objArrayOop of secondary supers.
-  movl( rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));// Load the array length
-  // Skip to start of data; also clear Z flag incase ECX is zero
-  addptr( rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT) );
-  // Scan ECX words at [EDI] for occurance of EAX
-  // Set NZ/Z based on last compare
-  repne_scan();
-  restore_locals();           // Restore EDI; Must not blow flags
-  // Not equal?
-  jcc( Assembler::notEqual, not_subtype );
-  // Must be equal but missed in cache.  Update cache.
-  movptr( Address(Rsub_klass, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes()), rax );
-  jmp( ok_is_subtype );
-
-  bind(not_subtype);
+  // Profile the failure of the check.
   profile_typecheck_failed(rcx); // blows rcx
 }
 
@@ -1031,7 +1000,7 @@
 
   // If the mdp is valid, it will point to a DataLayout header which is
   // consistent with the bcp.  The converse is highly probable also.
-  load_unsigned_word(rdx, Address(rcx, in_bytes(DataLayout::bci_offset())));
+  load_unsigned_short(rdx, Address(rcx, in_bytes(DataLayout::bci_offset())));
   addptr(rdx, Address(rbx, methodOopDesc::const_offset()));
   lea(rdx, Address(rdx, constMethodOopDesc::codes_offset()));
   cmpptr(rdx, rsi);
@@ -1512,6 +1481,15 @@
     call_VM_leaf(
       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), rcx, rbx);
   }
+
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    get_thread(rcx);
+    get_method(rbx);
+    call_VM_leaf(
+      CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+      rcx, rbx);
+  }
 }
 
 
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -190,7 +190,7 @@
                                                            int bcp_offset) {
   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
   assert(cache != index, "must use different registers");
-  load_unsigned_word(index, Address(r13, bcp_offset));
+  load_unsigned_short(index, Address(r13, bcp_offset));
   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
   assert(sizeof(ConstantPoolCacheEntry) == 4 * wordSize, "adjust code below");
   // convert from field index to ConstantPoolCacheEntry index
@@ -203,7 +203,7 @@
                                                                int bcp_offset) {
   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
   assert(cache != tmp, "must use different register");
-  load_unsigned_word(tmp, Address(r13, bcp_offset));
+  load_unsigned_short(tmp, Address(r13, bcp_offset));
   assert(sizeof(ConstantPoolCacheEntry) == 4 * wordSize, "adjust code below");
   // convert from field index to ConstantPoolCacheEntry index
   // and from word offset to byte offset
@@ -232,65 +232,13 @@
   assert(Rsub_klass != rcx, "rcx holds 2ndary super array length");
   assert(Rsub_klass != rdi, "rdi holds 2ndary super array scan ptr");
 
-  Label not_subtype, not_subtype_pop, loop;
-
   // Profile the not-null value's klass.
-  profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, rdi
-
-  // Load the super-klass's check offset into rcx
-  movl(rcx, Address(rax, sizeof(oopDesc) +
-                    Klass::super_check_offset_offset_in_bytes()));
-  // Load from the sub-klass's super-class display list, or a 1-word
-  // cache of the secondary superclass list, or a failing value with a
-  // sentinel offset if the super-klass is an interface or
-  // exceptionally deep in the Java hierarchy and we have to scan the
-  // secondary superclass list the hard way.  See if we get an
-  // immediate positive hit
-  cmpptr(rax, Address(Rsub_klass, rcx, Address::times_1));
-  jcc(Assembler::equal,ok_is_subtype);
-
-  // Check for immediate negative hit
-  cmpl(rcx, sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes());
-  jcc( Assembler::notEqual, not_subtype );
-  // Check for self
-  cmpptr(Rsub_klass, rax);
-  jcc(Assembler::equal, ok_is_subtype);
+  profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, reloads rdi
 
-  // Now do a linear scan of the secondary super-klass chain.
-  movptr(rdi, Address(Rsub_klass, sizeof(oopDesc) +
-                      Klass::secondary_supers_offset_in_bytes()));
-  // rdi holds the objArrayOop of secondary supers.
-  // Load the array length
-  movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
-  // Skip to start of data; also clear Z flag incase rcx is zero
-  addptr(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
-  // Scan rcx words at [rdi] for occurance of rax
-  // Set NZ/Z based on last compare
+  // Do the check.
+  check_klass_subtype(Rsub_klass, rax, rcx, ok_is_subtype); // blows rcx
 
-  // this part is kind tricky, as values in supers array could be 32 or 64 bit wide
-  // and we store values in objArrays always encoded, thus we need to encode value
-  // before repne
-  if (UseCompressedOops) {
-    push(rax);
-    encode_heap_oop(rax);
-    repne_scanl();
-    // Not equal?
-    jcc(Assembler::notEqual, not_subtype_pop);
-    // restore heap oop here for movq
-    pop(rax);
-  } else {
-    repne_scan();
-    jcc(Assembler::notEqual, not_subtype);
-  }
-  // Must be equal but missed in cache.  Update cache.
-  movptr(Address(Rsub_klass, sizeof(oopDesc) +
-               Klass::secondary_super_cache_offset_in_bytes()), rax);
-  jmp(ok_is_subtype);
-
-  bind(not_subtype_pop);
-  // restore heap oop here for miss
-  if (UseCompressedOops) pop(rax);
-  bind(not_subtype);
+  // Profile the failure of the check.
   profile_typecheck_failed(rcx); // blows rcx
 }
 
@@ -1063,8 +1011,8 @@
 
   // If the mdp is valid, it will point to a DataLayout header which is
   // consistent with the bcp.  The converse is highly probable also.
-  load_unsigned_word(c_rarg2,
-                     Address(c_rarg3, in_bytes(DataLayout::bci_offset())));
+  load_unsigned_short(c_rarg2,
+                      Address(c_rarg3, in_bytes(DataLayout::bci_offset())));
   addptr(c_rarg2, Address(rbx, methodOopDesc::const_offset()));
   lea(c_rarg2, Address(c_rarg2, constMethodOopDesc::codes_offset()));
   cmpptr(c_rarg2, r13);
@@ -1593,6 +1541,14 @@
     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
                  r15_thread, c_rarg1);
   }
+
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    get_method(c_rarg1);
+    call_VM_leaf(
+      CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+      r15_thread, c_rarg1);
+  }
 }
 
 
--- a/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/interpreterRT_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/interpreterRT_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -349,7 +349,7 @@
 
     if (_num_args < Argument::n_float_register_parameters_c-1) {
       *_reg_args++ = from_obj;
-      *_fp_identifiers |= (0x01 << (_num_args*2)); // mark as float
+      *_fp_identifiers |= (intptr_t)(0x01 << (_num_args*2)); // mark as float
       _num_args++;
     } else {
       *_to++ = from_obj;
@@ -364,7 +364,7 @@
 
     if (_num_args < Argument::n_float_register_parameters_c-1) {
       *_reg_args++ = from_obj;
-      *_fp_identifiers |= (0x3 << (_num_args*2)); // mark as double
+      *_fp_identifiers |= (intptr_t)(0x3 << (_num_args*2)); // mark as double
       _num_args++;
     } else {
       *_to++ = from_obj;
--- a/hotspot/src/cpu/x86/vm/jni_x86.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/jni_x86.h	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/runtime_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/runtime_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/cpu/x86/vm/sharedRuntime_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/sharedRuntime_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1534,6 +1534,13 @@
          thread, rax);
   }
 
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    __ movoop(rax, JNIHandles::make_local(method()));
+    __ call_VM_leaf(
+         CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+         thread, rax);
+  }
 
   // These are register definitions we need for locking/unlocking
   const Register swap_reg = rax;  // Must use rax, for cmpxchg instruction
--- a/hotspot/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1350,7 +1350,7 @@
     {
       Label L;
       __ mov(rax, rsp);
-      __ andptr(rax, -16); // must be 16 byte boundry (see amd64 ABI)
+      __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
       __ cmpptr(rax, rsp);
       __ jcc(Assembler::equal, L);
       __ stop("improperly aligned stack");
@@ -1508,6 +1508,17 @@
     restore_args(masm, total_c_args, c_arg, out_regs);
   }
 
+  // RedefineClasses() tracing support for obsolete method entry
+  if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
+    // protect the args we've loaded
+    save_args(masm, total_c_args, c_arg, out_regs);
+    __ movoop(c_rarg1, JNIHandles::make_local(method()));
+    __ call_VM_leaf(
+      CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
+      r15_thread, c_rarg1);
+    restore_args(masm, total_c_args, c_arg, out_regs);
+  }
+
   // Lock a synchronized method
 
   // Register definitions used by locking and unlocking
@@ -2680,7 +2691,7 @@
   __ mov(rdi, rax);
 
    Label noException;
-  __ cmpl(r12, Deoptimization::Unpack_exception);   // Was exception pending?
+  __ cmpl(r14, Deoptimization::Unpack_exception);   // Was exception pending?
   __ jcc(Assembler::notEqual, noException);
   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
   // QQQ this is useless it was NULL above
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1310,81 +1310,51 @@
                            Address& super_check_offset_addr,
                            Address& super_klass_addr,
                            Register temp,
-                           Label* L_success_ptr, Label* L_failure_ptr) {
+                           Label* L_success, Label* L_failure) {
     BLOCK_COMMENT("type_check:");
 
     Label L_fallthrough;
-    bool fall_through_on_success = (L_success_ptr == NULL);
-    if (fall_through_on_success) {
-      L_success_ptr = &L_fallthrough;
-    } else {
-      L_failure_ptr = &L_fallthrough;
-    }
-    Label& L_success = *L_success_ptr;
-    Label& L_failure = *L_failure_ptr;
+#define LOCAL_JCC(assembler_con, label_ptr)                             \
+    if (label_ptr != NULL)  __ jcc(assembler_con, *(label_ptr));        \
+    else                    __ jcc(assembler_con, L_fallthrough) /*omit semi*/
 
+    // The following is a strange variation of the fast path which requires
+    // one less register, because needed values are on the argument stack.
+    // __ check_klass_subtype_fast_path(sub_klass, *super_klass*, temp,
+    //                                  L_success, L_failure, NULL);
     assert_different_registers(sub_klass, temp);
 
-    // a couple of useful fields in sub_klass:
-    int ss_offset = (klassOopDesc::header_size() * HeapWordSize +
-                     Klass::secondary_supers_offset_in_bytes());
     int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
                      Klass::secondary_super_cache_offset_in_bytes());
-    Address secondary_supers_addr(sub_klass, ss_offset);
-    Address super_cache_addr(     sub_klass, sc_offset);
 
     // if the pointers are equal, we are done (e.g., String[] elements)
     __ cmpptr(sub_klass, super_klass_addr);
-    __ jcc(Assembler::equal, L_success);
+    LOCAL_JCC(Assembler::equal, L_success);
 
     // check the supertype display:
     __ movl2ptr(temp, super_check_offset_addr);
     Address super_check_addr(sub_klass, temp, Address::times_1, 0);
     __ movptr(temp, super_check_addr); // load displayed supertype
     __ cmpptr(temp, super_klass_addr); // test the super type
-    __ jcc(Assembler::equal, L_success);
+    LOCAL_JCC(Assembler::equal, L_success);
 
     // if it was a primary super, we can just fail immediately
     __ cmpl(super_check_offset_addr, sc_offset);
-    __ jcc(Assembler::notEqual, L_failure);
-
-    // Now do a linear scan of the secondary super-klass chain.
-    // This code is rarely used, so simplicity is a virtue here.
-    inc_counter_np(SharedRuntime::_partial_subtype_ctr);
-    {
-      // The repne_scan instruction uses fixed registers, which we must spill.
-      // (We need a couple more temps in any case.)
-      __ push(rax);
-      __ push(rcx);
-      __ push(rdi);
-      assert_different_registers(sub_klass, rax, rcx, rdi);
+    LOCAL_JCC(Assembler::notEqual, L_failure);
 
-      __ movptr(rdi, secondary_supers_addr);
-      // Load the array length.
-      __ movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
-      // Skip to start of data.
-      __ addptr(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
-      // Scan rcx words at [edi] for occurance of rax,
-      // Set NZ/Z based on last compare
-      __ movptr(rax, super_klass_addr);
-      __ repne_scan();
+    // The repne_scan instruction uses fixed registers, which will get spilled.
+    // We happen to know this works best when super_klass is in rax.
+    Register super_klass = temp;
+    __ movptr(super_klass, super_klass_addr);
+    __ check_klass_subtype_slow_path(sub_klass, super_klass, noreg, noreg,
+                                     L_success, L_failure);
 
-      // Unspill the temp. registers:
-      __ pop(rdi);
-      __ pop(rcx);
-      __ pop(rax);
-    }
-    __ jcc(Assembler::notEqual, L_failure);
+    __ bind(L_fallthrough);
 
-    // Success.  Cache the super we found and proceed in triumph.
-    __ movptr(temp, super_klass_addr); // note: rax, is dead
-    __ movptr(super_cache_addr, temp);
+    if (L_success == NULL) { BLOCK_COMMENT("L_success:"); }
+    if (L_failure == NULL) { BLOCK_COMMENT("L_failure:"); }
 
-    if (!fall_through_on_success)
-      __ jmp(L_success);
-
-    // Fall through on failure!
-    __ bind(L_fallthrough);
+#undef LOCAL_JCC
   }
 
   //
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -637,7 +637,7 @@
   address generate_orderaccess_fence() {
     StubCodeMark mark(this, "StubRoutines", "orderaccess_fence");
     address start = __ pc();
-    __ mfence();
+    __ membar(Assembler::StoreLoad);
     __ ret(0);
 
     return start;
@@ -2091,66 +2091,9 @@
 
     Label L_miss;
 
-    // a couple of useful fields in sub_klass:
-    int ss_offset = (klassOopDesc::header_size() * HeapWordSize +
-                     Klass::secondary_supers_offset_in_bytes());
-    int sc_offset = (klassOopDesc::header_size() * HeapWordSize +
-                     Klass::secondary_super_cache_offset_in_bytes());
-    Address secondary_supers_addr(sub_klass, ss_offset);
-    Address super_cache_addr(     sub_klass, sc_offset);
-
-    // if the pointers are equal, we are done (e.g., String[] elements)
-    __ cmpptr(super_klass, sub_klass);
-    __ jcc(Assembler::equal, L_success);
-
-    // check the supertype display:
-    Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
-    __ cmpptr(super_klass, super_check_addr); // test the super type
-    __ jcc(Assembler::equal, L_success);
-
-    // if it was a primary super, we can just fail immediately
-    __ cmpl(super_check_offset, sc_offset);
-    __ jcc(Assembler::notEqual, L_miss);
-
-    // Now do a linear scan of the secondary super-klass chain.
-    // The repne_scan instruction uses fixed registers, which we must spill.
-    // (We need a couple more temps in any case.)
-    // This code is rarely used, so simplicity is a virtue here.
-    inc_counter_np(SharedRuntime::_partial_subtype_ctr);
-    {
-      __ push(rax);
-      __ push(rcx);
-      __ push(rdi);
-      assert_different_registers(sub_klass, super_klass, rax, rcx, rdi);
-
-      __ movptr(rdi, secondary_supers_addr);
-      // Load the array length.
-      __ movl(rcx, Address(rdi, arrayOopDesc::length_offset_in_bytes()));
-      // Skip to start of data.
-      __ addptr(rdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
-      // Scan rcx words at [rdi] for occurance of rax
-      // Set NZ/Z based on last compare
-      __ movptr(rax, super_klass);
-      if (UseCompressedOops) {
-        // Compare against compressed form.  Don't need to uncompress because
-        // looks like orig rax is restored in popq below.
-        __ encode_heap_oop(rax);
-        __ repne_scanl();
-      } else {
-        __ repne_scan();
-      }
-
-      // Unspill the temp. registers:
-      __ pop(rdi);
-      __ pop(rcx);
-      __ pop(rax);
-
-      __ jcc(Assembler::notEqual, L_miss);
-    }
-
-    // Success.  Cache the super we found and proceed in triumph.
-    __ movptr(super_cache_addr, super_klass); // note: rax is dead
-    __ jmp(L_success);
+    __ check_klass_subtype_fast_path(sub_klass, super_klass, noreg,        &L_success, &L_miss, NULL,
+                                     super_check_offset);
+    __ check_klass_subtype_slow_path(sub_klass, super_klass, noreg, noreg, &L_success, NULL);
 
     // Fall through on failure!
     __ BIND(L_miss);
--- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -662,13 +662,13 @@
     __ bind(notByte);
     __ cmpl(rdx, stos);
     __ jcc(Assembler::notEqual, notShort);
-    __ load_signed_word(rax, field_address);
+    __ load_signed_short(rax, field_address);
     __ jmp(xreturn_path);
 
     __ bind(notShort);
     __ cmpl(rdx, ctos);
     __ jcc(Assembler::notEqual, notChar);
-    __ load_unsigned_word(rax, field_address);
+    __ load_unsigned_short(rax, field_address);
     __ jmp(xreturn_path);
 
     __ bind(notChar);
@@ -723,7 +723,7 @@
   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // native calls don't need the stack size check since they have no expression stack
   // and the arguments are already on the stack and we only add a handful of words
@@ -838,7 +838,7 @@
   // allocate space for parameters
   __ get_method(method);
   __ verify_oop(method);
-  __ load_unsigned_word(t, Address(method, methodOopDesc::size_of_parameters_offset()));
+  __ load_unsigned_short(t, Address(method, methodOopDesc::size_of_parameters_offset()));
   __ shlptr(t, Interpreter::logStackElementSize());
   __ addptr(t, 2*wordSize);     // allocate two more slots for JNIEnv and possible mirror
   __ subptr(rsp, t);
@@ -1155,14 +1155,14 @@
   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // rbx,: methodOop
   // rcx: size of parameters
 
   // rsi: sender_sp (could differ from sp+wordSize if we were called via c2i )
 
-  __ load_unsigned_word(rdx, size_of_locals);       // get size of locals in words
+  __ load_unsigned_short(rdx, size_of_locals);       // get size of locals in words
   __ subl(rdx, rcx);                                // rdx = no. of additional locals
 
   // see if we've got enough room on the stack for locals plus overhead.
@@ -1558,7 +1558,7 @@
     // Compute size of arguments for saving when returning to deoptimized caller
     __ get_method(rax);
     __ verify_oop(rax);
-    __ load_unsigned_word(rax, Address(rax, in_bytes(methodOopDesc::size_of_parameters_offset())));
+    __ load_unsigned_short(rax, Address(rax, in_bytes(methodOopDesc::size_of_parameters_offset())));
     __ shlptr(rax, Interpreter::logStackElementSize());
     __ restore_locals();
     __ subptr(rdi, rax);
--- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -650,7 +650,7 @@
     __ cmpl(rdx, stos);
     __ jcc(Assembler::notEqual, notShort);
     // stos
-    __ load_signed_word(rax, field_address);
+    __ load_signed_short(rax, field_address);
     __ jmp(xreturn_path);
 
     __ bind(notShort);
@@ -662,7 +662,7 @@
     __ bind(okay);
 #endif
     // ctos
-    __ load_unsigned_word(rax, field_address);
+    __ load_unsigned_short(rax, field_address);
 
     __ bind(xreturn_path);
 
@@ -702,7 +702,7 @@
   const Address access_flags      (rbx, methodOopDesc::access_flags_offset());
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // native calls don't need the stack size check since they have no
   // expression stack and the arguments are already on the stack and
@@ -819,14 +819,14 @@
   // allocate space for parameters
   __ get_method(method);
   __ verify_oop(method);
-  __ load_unsigned_word(t,
-                        Address(method,
-                                methodOopDesc::size_of_parameters_offset()));
+  __ load_unsigned_short(t,
+                         Address(method,
+                                 methodOopDesc::size_of_parameters_offset()));
   __ shll(t, Interpreter::logStackElementSize());
 
   __ subptr(rsp, t);
   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
-  __ andptr(rsp, -16); // must be 16 byte boundry (see amd64 ABI)
+  __ andptr(rsp, -16); // must be 16 byte boundary (see amd64 ABI)
 
   // get signature handler
   {
@@ -1165,13 +1165,13 @@
   const Address access_flags(rbx, methodOopDesc::access_flags_offset());
 
   // get parameter size (always needed)
-  __ load_unsigned_word(rcx, size_of_parameters);
+  __ load_unsigned_short(rcx, size_of_parameters);
 
   // rbx: methodOop
   // rcx: size of parameters
   // r13: sender_sp (could differ from sp+wordSize if we were called via c2i )
 
-  __ load_unsigned_word(rdx, size_of_locals); // get size of locals in words
+  __ load_unsigned_short(rdx, size_of_locals); // get size of locals in words
   __ subl(rdx, rcx); // rdx = no. of additional locals
 
   // YYY
@@ -1583,7 +1583,7 @@
     // Compute size of arguments for saving when returning to
     // deoptimized caller
     __ get_method(rax);
-    __ load_unsigned_word(rax, Address(rax, in_bytes(methodOopDesc::
+    __ load_unsigned_short(rax, Address(rax, in_bytes(methodOopDesc::
                                                 size_of_parameters_offset())));
     __ shll(rax, Interpreter::logStackElementSize());
     __ restore_locals(); // XXX do we need this?
--- a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -296,7 +296,7 @@
 
 void TemplateTable::sipush() {
   transition(vtos, itos);
-  __ load_unsigned_word(rax, at_bcp(1));
+  __ load_unsigned_short(rax, at_bcp(1));
   __ bswapl(rax);
   __ sarl(rax, 16);
 }
@@ -662,7 +662,7 @@
   index_check(rdx, rax);  // kills rbx,
   // rax,: index
   // can do better code for P5 - may want to improve this at some point
-  __ load_unsigned_word(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_CHAR)));
+  __ load_unsigned_short(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_CHAR)));
   __ mov(rax, rbx);
 }
 
@@ -677,7 +677,7 @@
   // rdx: array
   index_check(rdx, rax);
   // rax,: index
-  __ load_unsigned_word(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_CHAR)));
+  __ load_unsigned_short(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_CHAR)));
   __ mov(rax, rbx);
 }
 
@@ -687,7 +687,7 @@
   index_check(rdx, rax);  // kills rbx,
   // rax,: index
   // can do better code for P5 - may want to improve this at some point
-  __ load_signed_word(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_SHORT)));
+  __ load_signed_short(rbx, Address(rdx, rax, Address::times_2, arrayOopDesc::base_offset_in_bytes(T_SHORT)));
   __ mov(rax, rbx);
 }
 
@@ -1586,7 +1586,7 @@
 
   // Handle all the JSR stuff here, then exit.
   // It's much shorter and cleaner than intermingling with the
-  // non-JSR normal-branch stuff occuring below.
+  // non-JSR normal-branch stuff occurring below.
   if (is_jsr) {
     // Pre-load the next target bytecode into EBX
     __ load_unsigned_byte(rbx, Address(rsi, rdx, Address::times_1, 0));
@@ -2310,7 +2310,7 @@
   __ cmpl(flags, ctos );
   __ jcc(Assembler::notEqual, notChar);
 
-  __ load_unsigned_word(rax, lo );
+  __ load_unsigned_short(rax, lo );
   __ push(ctos);
   if (!is_static) {
     patch_bytecode(Bytecodes::_fast_cgetfield, rcx, rbx);
@@ -2322,7 +2322,7 @@
   __ cmpl(flags, stos );
   __ jcc(Assembler::notEqual, notShort);
 
-  __ load_signed_word(rax, lo );
+  __ load_signed_short(rax, lo );
   __ push(stos);
   if (!is_static) {
     patch_bytecode(Bytecodes::_fast_sgetfield, rcx, rbx);
@@ -2830,8 +2830,8 @@
   // access field
   switch (bytecode()) {
     case Bytecodes::_fast_bgetfield: __ movsbl(rax, lo );                 break;
-    case Bytecodes::_fast_sgetfield: __ load_signed_word(rax, lo );       break;
-    case Bytecodes::_fast_cgetfield: __ load_unsigned_word(rax, lo );     break;
+    case Bytecodes::_fast_sgetfield: __ load_signed_short(rax, lo );      break;
+    case Bytecodes::_fast_cgetfield: __ load_unsigned_short(rax, lo );    break;
     case Bytecodes::_fast_igetfield: __ movl(rax, lo);                    break;
     case Bytecodes::_fast_lgetfield: __ stop("should not be rewritten");  break;
     case Bytecodes::_fast_fgetfield: __ fld_s(lo);                        break;
@@ -3055,35 +3055,44 @@
   // profile this call
   __ profile_virtual_call(rdx, rsi, rdi);
 
-  __ mov(rdi, rdx); // Save klassOop in rdi
-
-  // Compute start of first itableOffsetEntry (which is at the end of the vtable)
-  const int base = instanceKlass::vtable_start_offset() * wordSize;
-  assert(vtableEntry::size() * wordSize == (1 << (int)Address::times_ptr), "adjust the scaling in the code below");
-  __ movl(rsi, Address(rdx, instanceKlass::vtable_length_offset() * wordSize)); // Get length of vtable
-  __ lea(rdx, Address(rdx, rsi, Address::times_4, base));
-  if (HeapWordsPerLong > 1) {
-    // Round up to align_object_offset boundary
-    __ round_to(rdx, BytesPerLong);
-  }
-
-  Label entry, search, interface_ok;
-
-  __ jmpb(entry);
-  __ bind(search);
-  __ addptr(rdx, itableOffsetEntry::size() * wordSize);
-
-  __ bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the receiver
-  // class doesn't implement the interface, and wasn't the same as the
-  // receiver class checked when the interface was resolved.
-  __ push(rdx);
-  __ movptr(rdx, Address(rdx, itableOffsetEntry::interface_offset_in_bytes()));
-  __ testptr(rdx, rdx);
-  __ jcc(Assembler::notZero, interface_ok);
+  Label no_such_interface, no_such_method;
+
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, rbx,
+                             // outputs: method, scan temp. reg
+                             rbx, rsi,
+                             no_such_interface);
+
+  // rbx,: methodOop to call
+  // rcx: receiver
+  // Check for abstract method error
+  // Note: This should be done more efficiently via a throw_abstract_method_error
+  //       interpreter entry point and a conditional jump to it in case of a null
+  //       method.
+  __ testptr(rbx, rbx);
+  __ jcc(Assembler::zero, no_such_method);
+
+  // do the call
+  // rcx: receiver
+  // rbx,: methodOop
+  __ jump_from_interpreted(rbx, rdx);
+  __ should_not_reach_here();
+
+  // exception handling code follows...
+  // note: must restore interpreter registers to canonical
+  //       state for exception handling to work correctly!
+
+  __ bind(no_such_method);
   // throw exception
-  __ pop(rdx);           // pop saved register first.
+  __ pop(rbx);           // pop return address (pushed by prepare_invoke)
+  __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
+  __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
+  // the call_VM checks for exception, so we should never return here.
+  __ should_not_reach_here();
+
+  __ bind(no_such_interface);
+  // throw exception
   __ pop(rbx);           // pop return address (pushed by prepare_invoke)
   __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
@@ -3091,42 +3100,6 @@
                    InterpreterRuntime::throw_IncompatibleClassChangeError));
   // the call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
-  __ bind(interface_ok);
-
-    __ pop(rdx);
-
-    __ cmpptr(rax, Address(rdx, itableOffsetEntry::interface_offset_in_bytes()));
-    __ jcc(Assembler::notEqual, search);
-
-    __ movl(rdx, Address(rdx, itableOffsetEntry::offset_offset_in_bytes()));
-    __ addptr(rdx, rdi); // Add offset to klassOop
-    assert(itableMethodEntry::size() * wordSize == (1 << (int)Address::times_ptr), "adjust the scaling in the code below");
-    __ movptr(rbx, Address(rdx, rbx, Address::times_ptr));
-    // rbx,: methodOop to call
-    // rcx: receiver
-    // Check for abstract method error
-    // Note: This should be done more efficiently via a throw_abstract_method_error
-    //       interpreter entry point and a conditional jump to it in case of a null
-    //       method.
-    { Label L;
-      __ testptr(rbx, rbx);
-      __ jcc(Assembler::notZero, L);
-      // throw exception
-          // note: must restore interpreter registers to canonical
-          //       state for exception handling to work correctly!
-          __ pop(rbx);           // pop return address (pushed by prepare_invoke)
-          __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
-          __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
-      __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
-      // the call_VM checks for exception, so we should never return here.
-      __ should_not_reach_here();
-      __ bind(L);
-    }
-
-  // do the call
-  // rcx: receiver
-  // rbx,: methodOop
-  __ jump_from_interpreted(rbx, rdx);
 }
 
 //----------------------------------------------------------------------------------------------------
--- a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -307,7 +307,7 @@
 
 void TemplateTable::sipush() {
   transition(vtos, itos);
-  __ load_unsigned_word(rax, at_bcp(1));
+  __ load_unsigned_short(rax, at_bcp(1));
   __ bswapl(rax);
   __ sarl(rax, 16);
 }
@@ -645,10 +645,10 @@
   // eax: index
   // rdx: array
   index_check(rdx, rax); // kills rbx
-  __ load_unsigned_word(rax,
-                        Address(rdx, rax,
-                                Address::times_2,
-                                arrayOopDesc::base_offset_in_bytes(T_CHAR)));
+  __ load_unsigned_short(rax,
+                         Address(rdx, rax,
+                                 Address::times_2,
+                                 arrayOopDesc::base_offset_in_bytes(T_CHAR)));
 }
 
 // iload followed by caload frequent pair
@@ -663,10 +663,10 @@
   // rdx: array
   __ pop_ptr(rdx);
   index_check(rdx, rax); // kills rbx
-  __ load_unsigned_word(rax,
-                        Address(rdx, rax,
-                                Address::times_2,
-                                arrayOopDesc::base_offset_in_bytes(T_CHAR)));
+  __ load_unsigned_short(rax,
+                         Address(rdx, rax,
+                                 Address::times_2,
+                                 arrayOopDesc::base_offset_in_bytes(T_CHAR)));
 }
 
 void TemplateTable::saload() {
@@ -675,10 +675,10 @@
   // eax: index
   // rdx: array
   index_check(rdx, rax); // kills rbx
-  __ load_signed_word(rax,
-                      Address(rdx, rax,
-                              Address::times_2,
-                              arrayOopDesc::base_offset_in_bytes(T_SHORT)));
+  __ load_signed_short(rax,
+                       Address(rdx, rax,
+                               Address::times_2,
+                               arrayOopDesc::base_offset_in_bytes(T_SHORT)));
 }
 
 void TemplateTable::iload(int n) {
@@ -1559,7 +1559,7 @@
 
   // Handle all the JSR stuff here, then exit.
   // It's much shorter and cleaner than intermingling with the non-JSR
-  // normal-branch stuff occuring below.
+  // normal-branch stuff occurring below.
   if (is_jsr) {
     // Pre-load the next target bytecode into rbx
     __ load_unsigned_byte(rbx, Address(r13, rdx, Address::times_1, 0));
@@ -2276,7 +2276,7 @@
   __ cmpl(flags, ctos);
   __ jcc(Assembler::notEqual, notChar);
   // ctos
-  __ load_unsigned_word(rax, field);
+  __ load_unsigned_short(rax, field);
   __ push(ctos);
   // Rewrite bytecode to be faster
   if (!is_static) {
@@ -2288,7 +2288,7 @@
   __ cmpl(flags, stos);
   __ jcc(Assembler::notEqual, notShort);
   // stos
-  __ load_signed_word(rax, field);
+  __ load_signed_short(rax, field);
   __ push(stos);
   // Rewrite bytecode to be faster
   if (!is_static) {
@@ -2751,10 +2751,10 @@
     __ movsbl(rax, field);
     break;
   case Bytecodes::_fast_sgetfield:
-    __ load_signed_word(rax, field);
+    __ load_signed_short(rax, field);
     break;
   case Bytecodes::_fast_cgetfield:
-    __ load_unsigned_word(rax, field);
+    __ load_unsigned_short(rax, field);
     break;
   case Bytecodes::_fast_fgetfield:
     __ movflt(xmm0, field);
@@ -3010,97 +3010,55 @@
   // profile this call
   __ profile_virtual_call(rdx, r13, r14);
 
-  __ mov(r14, rdx); // Save klassOop in r14
-
-  // Compute start of first itableOffsetEntry (which is at the end of
-  // the vtable)
-  const int base = instanceKlass::vtable_start_offset() * wordSize;
-  // Get length of vtable
-  assert(vtableEntry::size() * wordSize == 8,
-         "adjust the scaling in the code below");
-  __ movl(r13, Address(rdx,
-                       instanceKlass::vtable_length_offset() * wordSize));
-  __ lea(rdx, Address(rdx, r13, Address::times_8, base));
-
-  if (HeapWordsPerLong > 1) {
-    // Round up to align_object_offset boundary
-    __ round_to(rdx, BytesPerLong);
-  }
-
-  Label entry, search, interface_ok;
-
-  __ jmpb(entry);
-  __ bind(search);
-  __ addptr(rdx, itableOffsetEntry::size() * wordSize);
-
-  __ bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the
-  // receiver class doesn't implement the interface, and wasn't the
-  // same as the receiver class checked when the interface was
-  // resolved.
-  __ push(rdx);
-  __ movptr(rdx, Address(rdx, itableOffsetEntry::interface_offset_in_bytes()));
-  __ testptr(rdx, rdx);
-  __ jcc(Assembler::notZero, interface_ok);
+  Label no_such_interface, no_such_method;
+
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, rbx,
+                             // outputs: method, scan temp. reg
+                             rbx, r13,
+                             no_such_interface);
+
+  // rbx,: methodOop to call
+  // rcx: receiver
+  // Check for abstract method error
+  // Note: This should be done more efficiently via a throw_abstract_method_error
+  //       interpreter entry point and a conditional jump to it in case of a null
+  //       method.
+  __ testptr(rbx, rbx);
+  __ jcc(Assembler::zero, no_such_method);
+
+  // do the call
+  // rcx: receiver
+  // rbx,: methodOop
+  __ jump_from_interpreted(rbx, rdx);
+  __ should_not_reach_here();
+
+  // exception handling code follows...
+  // note: must restore interpreter registers to canonical
+  //       state for exception handling to work correctly!
+
+  __ bind(no_such_method);
   // throw exception
-  __ pop(rdx); // pop saved register first.
-  __ pop(rbx); // pop return address (pushed by prepare_invoke)
-  __ restore_bcp(); // r13 must be correct for exception handler (was
-                    // destroyed)
-  __ restore_locals(); // make sure locals pointer is correct as well
-                       // (was destroyed)
+  __ pop(rbx);           // pop return address (pushed by prepare_invoke)
+  __ restore_bcp();      // r13 must be correct for exception handler   (was destroyed)
+  __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
+  // the call_VM checks for exception, so we should never return here.
+  __ should_not_reach_here();
+
+  __ bind(no_such_interface);
+  // throw exception
+  __ pop(rbx);           // pop return address (pushed by prepare_invoke)
+  __ restore_bcp();      // r13 must be correct for exception handler   (was destroyed)
+  __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
   __ call_VM(noreg, CAST_FROM_FN_PTR(address,
                    InterpreterRuntime::throw_IncompatibleClassChangeError));
   // the call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
-  __ bind(interface_ok);
-
-  __ pop(rdx);
-
-  __ cmpptr(rax, Address(rdx, itableOffsetEntry::interface_offset_in_bytes()));
-  __ jcc(Assembler::notEqual, search);
-
-  __ movl(rdx, Address(rdx, itableOffsetEntry::offset_offset_in_bytes()));
-
-  __ addptr(rdx, r14); // Add offset to klassOop
-  assert(itableMethodEntry::size() * wordSize == 8,
-         "adjust the scaling in the code below");
-  __ movptr(rbx, Address(rdx, rbx, Address::times_8));
-  // rbx: methodOop to call
-  // rcx: receiver
-  // Check for abstract method error
-  // Note: This should be done more efficiently via a
-  // throw_abstract_method_error interpreter entry point and a
-  // conditional jump to it in case of a null method.
-  {
-    Label L;
-    __ testptr(rbx, rbx);
-    __ jcc(Assembler::notZero, L);
-    // throw exception
-    // note: must restore interpreter registers to canonical
-    //       state for exception handling to work correctly!
-    __ pop(rbx);  // pop return address (pushed by prepare_invoke)
-    __ restore_bcp(); // r13 must be correct for exception handler
-                      // (was destroyed)
-    __ restore_locals(); // make sure locals pointer is correct as
-                         // well (was destroyed)
-    __ call_VM(noreg,
-               CAST_FROM_FN_PTR(address,
-                             InterpreterRuntime::throw_AbstractMethodError));
-    // the call_VM checks for exception, so we should never return here.
-    __ should_not_reach_here();
-    __ bind(L);
-  }
-
-  __ movptr(rcx, Address(rbx, methodOopDesc::interpreter_entry_offset()));
-
-  // do the call
-  // rcx: receiver
-  // rbx: methodOop
-  __ jump_from_interpreted(rbx, rdx);
+  return;
 }
 
+
 //-----------------------------------------------------------------------------
 // Allocation
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,527 @@
+/*
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+# include "incls/_precompiled.incl"
+# include "incls/_vm_version_x86.cpp.incl"
+
+
+int VM_Version::_cpu;
+int VM_Version::_model;
+int VM_Version::_stepping;
+int VM_Version::_cpuFeatures;
+const char*           VM_Version::_features_str = "";
+VM_Version::CpuidInfo VM_Version::_cpuid_info   = { 0, };
+
+static BufferBlob* stub_blob;
+static const int stub_size = 300;
+
+extern "C" {
+  typedef void (*getPsrInfo_stub_t)(void*);
+}
+static getPsrInfo_stub_t getPsrInfo_stub = NULL;
+
+
+class VM_Version_StubGenerator: public StubCodeGenerator {
+ public:
+
+  VM_Version_StubGenerator(CodeBuffer *c) : StubCodeGenerator(c) {}
+
+  address generate_getPsrInfo() {
+    // Flags to test CPU type.
+    const uint32_t EFL_AC           = 0x40000;
+    const uint32_t EFL_ID           = 0x200000;
+    // Values for when we don't have a CPUID instruction.
+    const int      CPU_FAMILY_SHIFT = 8;
+    const uint32_t CPU_FAMILY_386   = (3 << CPU_FAMILY_SHIFT);
+    const uint32_t CPU_FAMILY_486   = (4 << CPU_FAMILY_SHIFT);
+
+    Label detect_486, cpu486, detect_586, std_cpuid1;
+    Label ext_cpuid1, ext_cpuid5, done;
+
+    StubCodeMark mark(this, "VM_Version", "getPsrInfo_stub");
+#   define __ _masm->
+
+    address start = __ pc();
+
+    //
+    // void getPsrInfo(VM_Version::CpuidInfo* cpuid_info);
+    //
+    // LP64: rcx and rdx are first and second argument registers on windows
+
+    __ push(rbp);
+#ifdef _LP64
+    __ mov(rbp, c_rarg0); // cpuid_info address
+#else
+    __ movptr(rbp, Address(rsp, 8)); // cpuid_info address
+#endif
+    __ push(rbx);
+    __ push(rsi);
+    __ pushf();          // preserve rbx, and flags
+    __ pop(rax);
+    __ push(rax);
+    __ mov(rcx, rax);
+    //
+    // if we are unable to change the AC flag, we have a 386
+    //
+    __ xorl(rax, EFL_AC);
+    __ push(rax);
+    __ popf();
+    __ pushf();
+    __ pop(rax);
+    __ cmpptr(rax, rcx);
+    __ jccb(Assembler::notEqual, detect_486);
+
+    __ movl(rax, CPU_FAMILY_386);
+    __ movl(Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())), rax);
+    __ jmp(done);
+
+    //
+    // If we are unable to change the ID flag, we have a 486 which does
+    // not support the "cpuid" instruction.
+    //
+    __ bind(detect_486);
+    __ mov(rax, rcx);
+    __ xorl(rax, EFL_ID);
+    __ push(rax);
+    __ popf();
+    __ pushf();
+    __ pop(rax);
+    __ cmpptr(rcx, rax);
+    __ jccb(Assembler::notEqual, detect_586);
+
+    __ bind(cpu486);
+    __ movl(rax, CPU_FAMILY_486);
+    __ movl(Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())), rax);
+    __ jmp(done);
+
+    //
+    // At this point, we have a chip which supports the "cpuid" instruction
+    //
+    __ bind(detect_586);
+    __ xorl(rax, rax);
+    __ cpuid();
+    __ orl(rax, rax);
+    __ jcc(Assembler::equal, cpu486);   // if cpuid doesn't support an input
+                                        // value of at least 1, we give up and
+                                        // assume a 486
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid0_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    __ cmpl(rax, 3);     // Is cpuid(0x4) supported?
+    __ jccb(Assembler::belowEqual, std_cpuid1);
+
+    //
+    // cpuid(0x4) Deterministic cache params
+    //
+    __ movl(rax, 4);
+    __ xorl(rcx, rcx);   // L1 cache
+    __ cpuid();
+    __ push(rax);
+    __ andl(rax, 0x1f);  // Determine if valid cache parameters used
+    __ orl(rax, rax);    // eax[4:0] == 0 indicates invalid cache
+    __ pop(rax);
+    __ jccb(Assembler::equal, std_cpuid1);
+
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::dcp_cpuid4_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    //
+    // Standard cpuid(0x1)
+    //
+    __ bind(std_cpuid1);
+    __ movl(rax, 1);
+    __ cpuid();
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    __ movl(rax, 0x80000000);
+    __ cpuid();
+    __ cmpl(rax, 0x80000000);     // Is cpuid(0x80000001) supported?
+    __ jcc(Assembler::belowEqual, done);
+    __ cmpl(rax, 0x80000004);     // Is cpuid(0x80000005) supported?
+    __ jccb(Assembler::belowEqual, ext_cpuid1);
+    __ cmpl(rax, 0x80000007);     // Is cpuid(0x80000008) supported?
+    __ jccb(Assembler::belowEqual, ext_cpuid5);
+    //
+    // Extended cpuid(0x80000008)
+    //
+    __ movl(rax, 0x80000008);
+    __ cpuid();
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid8_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    //
+    // Extended cpuid(0x80000005)
+    //
+    __ bind(ext_cpuid5);
+    __ movl(rax, 0x80000005);
+    __ cpuid();
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid5_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    //
+    // Extended cpuid(0x80000001)
+    //
+    __ bind(ext_cpuid1);
+    __ movl(rax, 0x80000001);
+    __ cpuid();
+    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid1_offset())));
+    __ movl(Address(rsi, 0), rax);
+    __ movl(Address(rsi, 4), rbx);
+    __ movl(Address(rsi, 8), rcx);
+    __ movl(Address(rsi,12), rdx);
+
+    //
+    // return
+    //
+    __ bind(done);
+    __ popf();
+    __ pop(rsi);
+    __ pop(rbx);
+    __ pop(rbp);
+    __ ret(0);
+
+#   undef __
+
+    return start;
+  };
+};
+
+
+void VM_Version::get_processor_features() {
+
+  _cpu = 4; // 486 by default
+  _model = 0;
+  _stepping = 0;
+  _cpuFeatures = 0;
+  _logical_processors_per_package = 1;
+
+  if (!Use486InstrsOnly) {
+    // Get raw processor info
+    getPsrInfo_stub(&_cpuid_info);
+    assert_is_initialized();
+    _cpu = extended_cpu_family();
+    _model = extended_cpu_model();
+    _stepping = cpu_stepping();
+
+    if (cpu_family() > 4) { // it supports CPUID
+      _cpuFeatures = feature_flags();
+      // Logical processors are only available on P4s and above,
+      // and only if hyperthreading is available.
+      _logical_processors_per_package = logical_processor_count();
+    }
+  }
+
+  _supports_cx8 = supports_cmpxchg8();
+
+#ifdef _LP64
+  // OS should support SSE for x64 and hardware should support at least SSE2.
+  if (!VM_Version::supports_sse2()) {
+    vm_exit_during_initialization("Unknown x64 processor: SSE2 not supported");
+  }
+#endif
+
+  // If the OS doesn't support SSE, we can't use this feature even if the HW does
+  if (!os::supports_sse())
+    _cpuFeatures &= ~(CPU_SSE|CPU_SSE2|CPU_SSE3|CPU_SSSE3|CPU_SSE4A|CPU_SSE4_1|CPU_SSE4_2);
+
+  if (UseSSE < 4) {
+    _cpuFeatures &= ~CPU_SSE4_1;
+    _cpuFeatures &= ~CPU_SSE4_2;
+  }
+
+  if (UseSSE < 3) {
+    _cpuFeatures &= ~CPU_SSE3;
+    _cpuFeatures &= ~CPU_SSSE3;
+    _cpuFeatures &= ~CPU_SSE4A;
+  }
+
+  if (UseSSE < 2)
+    _cpuFeatures &= ~CPU_SSE2;
+
+  if (UseSSE < 1)
+    _cpuFeatures &= ~CPU_SSE;
+
+  if (logical_processors_per_package() == 1) {
+    // HT processor could be installed on a system which doesn't support HT.
+    _cpuFeatures &= ~CPU_HT;
+  }
+
+  char buf[256];
+  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+               cores_per_cpu(), threads_per_core(),
+               cpu_family(), _model, _stepping,
+               (supports_cmov() ? ", cmov" : ""),
+               (supports_cmpxchg8() ? ", cx8" : ""),
+               (supports_fxsr() ? ", fxsr" : ""),
+               (supports_mmx()  ? ", mmx"  : ""),
+               (supports_sse()  ? ", sse"  : ""),
+               (supports_sse2() ? ", sse2" : ""),
+               (supports_sse3() ? ", sse3" : ""),
+               (supports_ssse3()? ", ssse3": ""),
+               (supports_sse4_1() ? ", sse4.1" : ""),
+               (supports_sse4_2() ? ", sse4.2" : ""),
+               (supports_popcnt() ? ", popcnt" : ""),
+               (supports_mmx_ext() ? ", mmxext" : ""),
+               (supports_3dnow()   ? ", 3dnow"  : ""),
+               (supports_3dnow2()  ? ", 3dnowext" : ""),
+               (supports_sse4a()   ? ", sse4a": ""),
+               (supports_ht() ? ", ht": ""));
+  _features_str = strdup(buf);
+
+  // UseSSE is set to the smaller of what hardware supports and what
+  // the command line requires.  I.e., you cannot set UseSSE to 2 on
+  // older Pentiums which do not support it.
+  if( UseSSE > 4 ) UseSSE=4;
+  if( UseSSE < 0 ) UseSSE=0;
+  if( !supports_sse4_1() ) // Drop to 3 if no SSE4 support
+    UseSSE = MIN2((intx)3,UseSSE);
+  if( !supports_sse3() ) // Drop to 2 if no SSE3 support
+    UseSSE = MIN2((intx)2,UseSSE);
+  if( !supports_sse2() ) // Drop to 1 if no SSE2 support
+    UseSSE = MIN2((intx)1,UseSSE);
+  if( !supports_sse () ) // Drop to 0 if no SSE  support
+    UseSSE = 0;
+
+  // On new cpus instructions which update whole XMM register should be used
+  // to prevent partial register stall due to dependencies on high half.
+  //
+  // UseXmmLoadAndClearUpper == true  --> movsd(xmm, mem)
+  // UseXmmLoadAndClearUpper == false --> movlpd(xmm, mem)
+  // UseXmmRegToRegMoveAll == true  --> movaps(xmm, xmm), movapd(xmm, xmm).
+  // UseXmmRegToRegMoveAll == false --> movss(xmm, xmm),  movsd(xmm, xmm).
+
+  if( is_amd() ) { // AMD cpus specific settings
+    if( supports_sse2() && FLAG_IS_DEFAULT(UseAddressNop) ) {
+      // Use it on new AMD cpus starting from Opteron.
+      UseAddressNop = true;
+    }
+    if( supports_sse2() && FLAG_IS_DEFAULT(UseNewLongLShift) ) {
+      // Use it on new AMD cpus starting from Opteron.
+      UseNewLongLShift = true;
+    }
+    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
+      if( supports_sse4a() ) {
+        UseXmmLoadAndClearUpper = true; // use movsd only on '10h' Opteron
+      } else {
+        UseXmmLoadAndClearUpper = false;
+      }
+    }
+    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
+      if( supports_sse4a() ) {
+        UseXmmRegToRegMoveAll = true; // use movaps, movapd only on '10h'
+      } else {
+        UseXmmRegToRegMoveAll = false;
+      }
+    }
+    if( FLAG_IS_DEFAULT(UseXmmI2F) ) {
+      if( supports_sse4a() ) {
+        UseXmmI2F = true;
+      } else {
+        UseXmmI2F = false;
+      }
+    }
+    if( FLAG_IS_DEFAULT(UseXmmI2D) ) {
+      if( supports_sse4a() ) {
+        UseXmmI2D = true;
+      } else {
+        UseXmmI2D = false;
+      }
+    }
+  }
+
+  if( is_intel() ) { // Intel cpus specific settings
+    if( FLAG_IS_DEFAULT(UseStoreImmI16) ) {
+      UseStoreImmI16 = false; // don't use it on Intel cpus
+    }
+    if( cpu_family() == 6 || cpu_family() == 15 ) {
+      if( FLAG_IS_DEFAULT(UseAddressNop) ) {
+        // Use it on all Intel cpus starting from PentiumPro
+        UseAddressNop = true;
+      }
+    }
+    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
+      UseXmmLoadAndClearUpper = true; // use movsd on all Intel cpus
+    }
+    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
+      if( supports_sse3() ) {
+        UseXmmRegToRegMoveAll = true; // use movaps, movapd on new Intel cpus
+      } else {
+        UseXmmRegToRegMoveAll = false;
+      }
+    }
+    if( cpu_family() == 6 && supports_sse3() ) { // New Intel cpus
+#ifdef COMPILER2
+      if( FLAG_IS_DEFAULT(MaxLoopPad) ) {
+        // For new Intel cpus do the next optimization:
+        // don't align the beginning of a loop if there are enough instructions
+        // left (NumberOfLoopInstrToAlign defined in c2_globals.hpp)
+        // in current fetch line (OptoLoopAlignment) or the padding
+        // is big (> MaxLoopPad).
+        // Set MaxLoopPad to 11 for new Intel cpus to reduce number of
+        // generated NOP instructions. 11 is the largest size of one
+        // address NOP instruction '0F 1F' (see Assembler::nop(i)).
+        MaxLoopPad = 11;
+      }
+#endif // COMPILER2
+      if( FLAG_IS_DEFAULT(UseXMMForArrayCopy) ) {
+        UseXMMForArrayCopy = true; // use SSE2 movq on new Intel cpus
+      }
+      if( supports_sse4_2() && supports_ht() ) { // Newest Intel cpus
+        if( FLAG_IS_DEFAULT(UseUnalignedLoadStores) && UseXMMForArrayCopy ) {
+          UseUnalignedLoadStores = true; // use movdqu on newest Intel cpus
+        }
+      }
+      if( supports_sse4_2() && UseSSE >= 4 ) {
+        if( FLAG_IS_DEFAULT(UseSSE42Intrinsics)) {
+          UseSSE42Intrinsics = true;
+        }
+      }
+    }
+  }
+
+  // Use population count instruction if available.
+  if (supports_popcnt()) {
+    if (FLAG_IS_DEFAULT(UsePopCountInstruction)) {
+      UsePopCountInstruction = true;
+    }
+  }
+
+  assert(0 <= ReadPrefetchInstr && ReadPrefetchInstr <= 3, "invalid value");
+  assert(0 <= AllocatePrefetchInstr && AllocatePrefetchInstr <= 3, "invalid value");
+
+  // set valid Prefetch instruction
+  if( ReadPrefetchInstr < 0 ) ReadPrefetchInstr = 0;
+  if( ReadPrefetchInstr > 3 ) ReadPrefetchInstr = 3;
+  if( ReadPrefetchInstr == 3 && !supports_3dnow() ) ReadPrefetchInstr = 0;
+  if( !supports_sse() && supports_3dnow() ) ReadPrefetchInstr = 3;
+
+  if( AllocatePrefetchInstr < 0 ) AllocatePrefetchInstr = 0;
+  if( AllocatePrefetchInstr > 3 ) AllocatePrefetchInstr = 3;
+  if( AllocatePrefetchInstr == 3 && !supports_3dnow() ) AllocatePrefetchInstr=0;
+  if( !supports_sse() && supports_3dnow() ) AllocatePrefetchInstr = 3;
+
+  // Allocation prefetch settings
+  intx cache_line_size = L1_data_cache_line_size();
+  if( cache_line_size > AllocatePrefetchStepSize )
+    AllocatePrefetchStepSize = cache_line_size;
+  if( FLAG_IS_DEFAULT(AllocatePrefetchLines) )
+    AllocatePrefetchLines = 3; // Optimistic value
+  assert(AllocatePrefetchLines > 0, "invalid value");
+  if( AllocatePrefetchLines < 1 ) // set valid value in product VM
+    AllocatePrefetchLines = 1; // Conservative value
+
+  AllocatePrefetchDistance = allocate_prefetch_distance();
+  AllocatePrefetchStyle    = allocate_prefetch_style();
+
+  if( AllocatePrefetchStyle == 2 && is_intel() &&
+      cpu_family() == 6 && supports_sse3() ) { // watermark prefetching on Core
+#ifdef _LP64
+    AllocatePrefetchDistance = 384;
+#else
+    AllocatePrefetchDistance = 320;
+#endif
+  }
+  assert(AllocatePrefetchDistance % AllocatePrefetchStepSize == 0, "invalid value");
+
+#ifdef _LP64
+  // Prefetch settings
+  PrefetchCopyIntervalInBytes = prefetch_copy_interval_in_bytes();
+  PrefetchScanIntervalInBytes = prefetch_scan_interval_in_bytes();
+  PrefetchFieldsAhead         = prefetch_fields_ahead();
+#endif
+
+#ifndef PRODUCT
+  if (PrintMiscellaneous && Verbose) {
+    tty->print_cr("Logical CPUs per core: %u",
+                  logical_processors_per_package());
+    tty->print_cr("UseSSE=%d",UseSSE);
+    tty->print("Allocation: ");
+    if (AllocatePrefetchStyle <= 0 || UseSSE == 0 && !supports_3dnow()) {
+      tty->print_cr("no prefetching");
+    } else {
+      if (UseSSE == 0 && supports_3dnow()) {
+        tty->print("PREFETCHW");
+      } else if (UseSSE >= 1) {
+        if (AllocatePrefetchInstr == 0) {
+          tty->print("PREFETCHNTA");
+        } else if (AllocatePrefetchInstr == 1) {
+          tty->print("PREFETCHT0");
+        } else if (AllocatePrefetchInstr == 2) {
+          tty->print("PREFETCHT2");
+        } else if (AllocatePrefetchInstr == 3) {
+          tty->print("PREFETCHW");
+        }
+      }
+      if (AllocatePrefetchLines > 1) {
+        tty->print_cr(" %d, %d lines with step %d bytes", AllocatePrefetchDistance, AllocatePrefetchLines, AllocatePrefetchStepSize);
+      } else {
+        tty->print_cr(" %d, one line", AllocatePrefetchDistance);
+      }
+    }
+
+    if (PrefetchCopyIntervalInBytes > 0) {
+      tty->print_cr("PrefetchCopyIntervalInBytes %d", PrefetchCopyIntervalInBytes);
+    }
+    if (PrefetchScanIntervalInBytes > 0) {
+      tty->print_cr("PrefetchScanIntervalInBytes %d", PrefetchScanIntervalInBytes);
+    }
+    if (PrefetchFieldsAhead > 0) {
+      tty->print_cr("PrefetchFieldsAhead %d", PrefetchFieldsAhead);
+    }
+  }
+#endif // !PRODUCT
+}
+
+void VM_Version::initialize() {
+  ResourceMark rm;
+  // Making this stub must be FIRST use of assembler
+
+  stub_blob = BufferBlob::create("getPsrInfo_stub", stub_size);
+  if (stub_blob == NULL) {
+    vm_exit_during_initialization("Unable to allocate getPsrInfo_stub");
+  }
+  CodeBuffer c(stub_blob->instructions_begin(),
+               stub_blob->instructions_size());
+  VM_Version_StubGenerator g(&c);
+  getPsrInfo_stub = CAST_TO_FN_PTR(getPsrInfo_stub_t,
+                                   g.generate_getPsrInfo());
+
+  get_processor_features();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,465 @@
+/*
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+class VM_Version : public Abstract_VM_Version {
+public:
+  // cpuid result register layouts.  These are all unions of a uint32_t
+  // (in case anyone wants access to the register as a whole) and a bitfield.
+
+  union StdCpuid1Eax {
+    uint32_t value;
+    struct {
+      uint32_t stepping   : 4,
+               model      : 4,
+               family     : 4,
+               proc_type  : 2,
+                          : 2,
+               ext_model  : 4,
+               ext_family : 8,
+                          : 4;
+    } bits;
+  };
+
+  union StdCpuid1Ebx { // example, unused
+    uint32_t value;
+    struct {
+      uint32_t brand_id         : 8,
+               clflush_size     : 8,
+               threads_per_cpu  : 8,
+               apic_id          : 8;
+    } bits;
+  };
+
+  union StdCpuid1Ecx {
+    uint32_t value;
+    struct {
+      uint32_t sse3     : 1,
+                        : 2,
+               monitor  : 1,
+                        : 1,
+               vmx      : 1,
+                        : 1,
+               est      : 1,
+                        : 1,
+               ssse3    : 1,
+               cid      : 1,
+                        : 2,
+               cmpxchg16: 1,
+                        : 4,
+               dca      : 1,
+               sse4_1   : 1,
+               sse4_2   : 1,
+                        : 2,
+               popcnt   : 1,
+                        : 8;
+    } bits;
+  };
+
+  union StdCpuid1Edx {
+    uint32_t value;
+    struct {
+      uint32_t          : 4,
+               tsc      : 1,
+                        : 3,
+               cmpxchg8 : 1,
+                        : 6,
+               cmov     : 1,
+                        : 7,
+               mmx      : 1,
+               fxsr     : 1,
+               sse      : 1,
+               sse2     : 1,
+                        : 1,
+               ht       : 1,
+                        : 3;
+    } bits;
+  };
+
+  union DcpCpuid4Eax {
+    uint32_t value;
+    struct {
+      uint32_t cache_type    : 5,
+                             : 21,
+               cores_per_cpu : 6;
+    } bits;
+  };
+
+  union DcpCpuid4Ebx {
+    uint32_t value;
+    struct {
+      uint32_t L1_line_size  : 12,
+               partitions    : 10,
+               associativity : 10;
+    } bits;
+  };
+
+  union ExtCpuid1Ecx {
+    uint32_t value;
+    struct {
+      uint32_t LahfSahf     : 1,
+               CmpLegacy    : 1,
+                            : 4,
+               abm          : 1,
+               sse4a        : 1,
+               misalignsse  : 1,
+               prefetchw    : 1,
+                            : 22;
+    } bits;
+  };
+
+  union ExtCpuid1Edx {
+    uint32_t value;
+    struct {
+      uint32_t           : 22,
+               mmx_amd   : 1,
+               mmx       : 1,
+               fxsr      : 1,
+                         : 4,
+               long_mode : 1,
+               tdnow2    : 1,
+               tdnow     : 1;
+    } bits;
+  };
+
+  union ExtCpuid5Ex {
+    uint32_t value;
+    struct {
+      uint32_t L1_line_size : 8,
+               L1_tag_lines : 8,
+               L1_assoc     : 8,
+               L1_size      : 8;
+    } bits;
+  };
+
+  union ExtCpuid8Ecx {
+    uint32_t value;
+    struct {
+      uint32_t cores_per_cpu : 8,
+                             : 24;
+    } bits;
+  };
+
+protected:
+   static int _cpu;
+   static int _model;
+   static int _stepping;
+   static int _cpuFeatures;     // features returned by the "cpuid" instruction
+                                // 0 if this instruction is not available
+   static const char* _features_str;
+
+   enum {
+     CPU_CX8    = (1 << 0), // next bits are from cpuid 1 (EDX)
+     CPU_CMOV   = (1 << 1),
+     CPU_FXSR   = (1 << 2),
+     CPU_HT     = (1 << 3),
+     CPU_MMX    = (1 << 4),
+     CPU_3DNOW  = (1 << 5), // 3DNow comes from cpuid 0x80000001 (EDX)
+     CPU_SSE    = (1 << 6),
+     CPU_SSE2   = (1 << 7),
+     CPU_SSE3   = (1 << 8), // SSE3 comes from cpuid 1 (ECX)
+     CPU_SSSE3  = (1 << 9),
+     CPU_SSE4A  = (1 << 10),
+     CPU_SSE4_1 = (1 << 11),
+     CPU_SSE4_2 = (1 << 12),
+     CPU_POPCNT = (1 << 13)
+   } cpuFeatureFlags;
+
+  // cpuid information block.  All info derived from executing cpuid with
+  // various function numbers is stored here.  Intel and AMD info is
+  // merged in this block: accessor methods disentangle it.
+  //
+  // The info block is laid out in subblocks of 4 dwords corresponding to
+  // eax, ebx, ecx and edx, whether or not they contain anything useful.
+  struct CpuidInfo {
+    // cpuid function 0
+    uint32_t std_max_function;
+    uint32_t std_vendor_name_0;
+    uint32_t std_vendor_name_1;
+    uint32_t std_vendor_name_2;
+
+    // cpuid function 1
+    StdCpuid1Eax std_cpuid1_eax;
+    StdCpuid1Ebx std_cpuid1_ebx;
+    StdCpuid1Ecx std_cpuid1_ecx;
+    StdCpuid1Edx std_cpuid1_edx;
+
+    // cpuid function 4 (deterministic cache parameters)
+    DcpCpuid4Eax dcp_cpuid4_eax;
+    DcpCpuid4Ebx dcp_cpuid4_ebx;
+    uint32_t     dcp_cpuid4_ecx; // unused currently
+    uint32_t     dcp_cpuid4_edx; // unused currently
+
+    // cpuid function 0x80000000 // example, unused
+    uint32_t ext_max_function;
+    uint32_t ext_vendor_name_0;
+    uint32_t ext_vendor_name_1;
+    uint32_t ext_vendor_name_2;
+
+    // cpuid function 0x80000001
+    uint32_t     ext_cpuid1_eax; // reserved
+    uint32_t     ext_cpuid1_ebx; // reserved
+    ExtCpuid1Ecx ext_cpuid1_ecx;
+    ExtCpuid1Edx ext_cpuid1_edx;
+
+    // cpuid functions 0x80000002 thru 0x80000004: example, unused
+    uint32_t proc_name_0, proc_name_1, proc_name_2, proc_name_3;
+    uint32_t proc_name_4, proc_name_5, proc_name_6, proc_name_7;
+    uint32_t proc_name_8, proc_name_9, proc_name_10,proc_name_11;
+
+    // cpuid function 0x80000005 //AMD L1, Intel reserved
+    uint32_t     ext_cpuid5_eax; // unused currently
+    uint32_t     ext_cpuid5_ebx; // reserved
+    ExtCpuid5Ex  ext_cpuid5_ecx; // L1 data cache info (AMD)
+    ExtCpuid5Ex  ext_cpuid5_edx; // L1 instruction cache info (AMD)
+
+    // cpuid function 0x80000008
+    uint32_t     ext_cpuid8_eax; // unused currently
+    uint32_t     ext_cpuid8_ebx; // reserved
+    ExtCpuid8Ecx ext_cpuid8_ecx;
+    uint32_t     ext_cpuid8_edx; // reserved
+  };
+
+  // The actual cpuid info block
+  static CpuidInfo _cpuid_info;
+
+  // Extractors and predicates
+  static uint32_t extended_cpu_family() {
+    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.family;
+    result += _cpuid_info.std_cpuid1_eax.bits.ext_family;
+    return result;
+  }
+  static uint32_t extended_cpu_model() {
+    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.model;
+    result |= _cpuid_info.std_cpuid1_eax.bits.ext_model << 4;
+    return result;
+  }
+  static uint32_t cpu_stepping() {
+    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.stepping;
+    return result;
+  }
+  static uint logical_processor_count() {
+    uint result = threads_per_core();
+    return result;
+  }
+  static uint32_t feature_flags() {
+    uint32_t result = 0;
+    if (_cpuid_info.std_cpuid1_edx.bits.cmpxchg8 != 0)
+      result |= CPU_CX8;
+    if (_cpuid_info.std_cpuid1_edx.bits.cmov != 0)
+      result |= CPU_CMOV;
+    if (_cpuid_info.std_cpuid1_edx.bits.fxsr != 0 || is_amd() &&
+        _cpuid_info.ext_cpuid1_edx.bits.fxsr != 0)
+      result |= CPU_FXSR;
+    // HT flag is set for multi-core processors also.
+    if (threads_per_core() > 1)
+      result |= CPU_HT;
+    if (_cpuid_info.std_cpuid1_edx.bits.mmx != 0 || is_amd() &&
+        _cpuid_info.ext_cpuid1_edx.bits.mmx != 0)
+      result |= CPU_MMX;
+    if (is_amd() && _cpuid_info.ext_cpuid1_edx.bits.tdnow != 0)
+      result |= CPU_3DNOW;
+    if (_cpuid_info.std_cpuid1_edx.bits.sse != 0)
+      result |= CPU_SSE;
+    if (_cpuid_info.std_cpuid1_edx.bits.sse2 != 0)
+      result |= CPU_SSE2;
+    if (_cpuid_info.std_cpuid1_ecx.bits.sse3 != 0)
+      result |= CPU_SSE3;
+    if (_cpuid_info.std_cpuid1_ecx.bits.ssse3 != 0)
+      result |= CPU_SSSE3;
+    if (is_amd() && _cpuid_info.ext_cpuid1_ecx.bits.sse4a != 0)
+      result |= CPU_SSE4A;
+    if (_cpuid_info.std_cpuid1_ecx.bits.sse4_1 != 0)
+      result |= CPU_SSE4_1;
+    if (_cpuid_info.std_cpuid1_ecx.bits.sse4_2 != 0)
+      result |= CPU_SSE4_2;
+    if (_cpuid_info.std_cpuid1_ecx.bits.popcnt != 0)
+      result |= CPU_POPCNT;
+    return result;
+  }
+
+  static void get_processor_features();
+
+public:
+  // Offsets for cpuid asm stub
+  static ByteSize std_cpuid0_offset() { return byte_offset_of(CpuidInfo, std_max_function); }
+  static ByteSize std_cpuid1_offset() { return byte_offset_of(CpuidInfo, std_cpuid1_eax); }
+  static ByteSize dcp_cpuid4_offset() { return byte_offset_of(CpuidInfo, dcp_cpuid4_eax); }
+  static ByteSize ext_cpuid1_offset() { return byte_offset_of(CpuidInfo, ext_cpuid1_eax); }
+  static ByteSize ext_cpuid5_offset() { return byte_offset_of(CpuidInfo, ext_cpuid5_eax); }
+  static ByteSize ext_cpuid8_offset() { return byte_offset_of(CpuidInfo, ext_cpuid8_eax); }
+
+  // Initialization
+  static void initialize();
+
+  // Asserts
+  static void assert_is_initialized() {
+    assert(_cpuid_info.std_cpuid1_eax.bits.family != 0, "VM_Version not initialized");
+  }
+
+  //
+  // Processor family:
+  //       3   -  386
+  //       4   -  486
+  //       5   -  Pentium
+  //       6   -  PentiumPro, Pentium II, Celeron, Xeon, Pentium III, Athlon,
+  //              Pentium M, Core Solo, Core Duo, Core2 Duo
+  //    family 6 model:   9,        13,       14,        15
+  //    0x0f   -  Pentium 4, Opteron
+  //
+  // Note: The cpu family should be used to select between
+  //       instruction sequences which are valid on all Intel
+  //       processors.  Use the feature test functions below to
+  //       determine whether a particular instruction is supported.
+  //
+  static int  cpu_family()        { return _cpu;}
+  static bool is_P6()             { return cpu_family() >= 6; }
+
+  static bool is_amd()            { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x68747541; } // 'htuA'
+  static bool is_intel()          { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x756e6547; } // 'uneG'
+
+  static uint cores_per_cpu()  {
+    uint result = 1;
+    if (is_intel()) {
+      result = (_cpuid_info.dcp_cpuid4_eax.bits.cores_per_cpu + 1);
+    } else if (is_amd()) {
+      result = (_cpuid_info.ext_cpuid8_ecx.bits.cores_per_cpu + 1);
+    }
+    return result;
+  }
+
+  static uint threads_per_core()  {
+    uint result = 1;
+    if (_cpuid_info.std_cpuid1_edx.bits.ht != 0) {
+      result = _cpuid_info.std_cpuid1_ebx.bits.threads_per_cpu /
+               cores_per_cpu();
+    }
+    return result;
+  }
+
+  static intx L1_data_cache_line_size()  {
+    intx result = 0;
+    if (is_intel()) {
+      result = (_cpuid_info.dcp_cpuid4_ebx.bits.L1_line_size + 1);
+    } else if (is_amd()) {
+      result = _cpuid_info.ext_cpuid5_ecx.bits.L1_line_size;
+    }
+    if (result < 32) // not defined ?
+      result = 32;   // 32 bytes by default on x86 and other x64
+    return result;
+  }
+
+  //
+  // Feature identification
+  //
+  static bool supports_cpuid()    { return _cpuFeatures  != 0; }
+  static bool supports_cmpxchg8() { return (_cpuFeatures & CPU_CX8) != 0; }
+  static bool supports_cmov()     { return (_cpuFeatures & CPU_CMOV) != 0; }
+  static bool supports_fxsr()     { return (_cpuFeatures & CPU_FXSR) != 0; }
+  static bool supports_ht()       { return (_cpuFeatures & CPU_HT) != 0; }
+  static bool supports_mmx()      { return (_cpuFeatures & CPU_MMX) != 0; }
+  static bool supports_sse()      { return (_cpuFeatures & CPU_SSE) != 0; }
+  static bool supports_sse2()     { return (_cpuFeatures & CPU_SSE2) != 0; }
+  static bool supports_sse3()     { return (_cpuFeatures & CPU_SSE3) != 0; }
+  static bool supports_ssse3()    { return (_cpuFeatures & CPU_SSSE3)!= 0; }
+  static bool supports_sse4_1()   { return (_cpuFeatures & CPU_SSE4_1) != 0; }
+  static bool supports_sse4_2()   { return (_cpuFeatures & CPU_SSE4_2) != 0; }
+  static bool supports_popcnt()   { return (_cpuFeatures & CPU_POPCNT) != 0; }
+  //
+  // AMD features
+  //
+  static bool supports_3dnow()    { return (_cpuFeatures & CPU_3DNOW) != 0; }
+  static bool supports_mmx_ext()  { return is_amd() && _cpuid_info.ext_cpuid1_edx.bits.mmx_amd != 0; }
+  static bool supports_3dnow2()   { return is_amd() && _cpuid_info.ext_cpuid1_edx.bits.tdnow2 != 0; }
+  static bool supports_sse4a()    { return (_cpuFeatures & CPU_SSE4A) != 0; }
+
+  static bool supports_compare_and_exchange() { return true; }
+
+  static const char* cpu_features()           { return _features_str; }
+
+  static intx allocate_prefetch_distance() {
+    // This method should be called before allocate_prefetch_style().
+    //
+    // Hardware prefetching (distance/size in bytes):
+    // Pentium 3 -  64 /  32
+    // Pentium 4 - 256 / 128
+    // Athlon    -  64 /  32 ????
+    // Opteron   - 128 /  64 only when 2 sequential cache lines accessed
+    // Core      - 128 /  64
+    //
+    // Software prefetching (distance in bytes / instruction with best score):
+    // Pentium 3 - 128 / prefetchnta
+    // Pentium 4 - 512 / prefetchnta
+    // Athlon    - 128 / prefetchnta
+    // Opteron   - 256 / prefetchnta
+    // Core      - 256 / prefetchnta
+    // It will be used only when AllocatePrefetchStyle > 0
+
+    intx count = AllocatePrefetchDistance;
+    if (count < 0) {   // default ?
+      if (is_amd()) {  // AMD
+        if (supports_sse2())
+          count = 256; // Opteron
+        else
+          count = 128; // Athlon
+      } else {         // Intel
+        if (supports_sse2())
+          if (cpu_family() == 6) {
+            count = 256; // Pentium M, Core, Core2
+          } else {
+            count = 512; // Pentium 4
+          }
+        else
+          count = 128; // Pentium 3 (and all other old CPUs)
+      }
+    }
+    return count;
+  }
+  static intx allocate_prefetch_style() {
+    assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
+    // Return 0 if AllocatePrefetchDistance was not defined.
+    return AllocatePrefetchDistance > 0 ? AllocatePrefetchStyle : 0;
+  }
+
+  // Prefetch interval for gc copy/scan == 9 dcache lines.  Derived from
+  // 50-warehouse specjbb runs on a 2-way 1.8ghz opteron using a 4gb heap.
+  // Tested intervals from 128 to 2048 in increments of 64 == one cache line.
+  // 256 bytes (4 dcache lines) was the nearest runner-up to 576.
+
+  // gc copy/scan is disabled if prefetchw isn't supported, because
+  // Prefetch::write emits an inlined prefetchw on Linux.
+  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
+  // The used prefetcht0 instruction works for both amd64 and em64t.
+  static intx prefetch_copy_interval_in_bytes() {
+    intx interval = PrefetchCopyIntervalInBytes;
+    return interval >= 0 ? interval : 576;
+  }
+  static intx prefetch_scan_interval_in_bytes() {
+    intx interval = PrefetchScanIntervalInBytes;
+    return interval >= 0 ? interval : 576;
+  }
+  static intx prefetch_fields_ahead() {
+    intx count = PrefetchFieldsAhead;
+    return count >= 0 ? count : 1;
+  }
+};
--- a/hotspot/src/cpu/x86/vm/vm_version_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,472 +0,0 @@
-/*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
- * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- *
- */
-
-# include "incls/_precompiled.incl"
-# include "incls/_vm_version_x86_32.cpp.incl"
-
-
-int VM_Version::_cpu;
-int VM_Version::_model;
-int VM_Version::_stepping;
-int VM_Version::_cpuFeatures;
-const char*           VM_Version::_features_str = "";
-VM_Version::CpuidInfo VM_Version::_cpuid_info   = { 0, };
-
-static BufferBlob* stub_blob;
-static const int stub_size = 300;
-
-extern "C" {
-  typedef void (*getPsrInfo_stub_t)(void*);
-}
-static getPsrInfo_stub_t getPsrInfo_stub = NULL;
-
-
-class VM_Version_StubGenerator: public StubCodeGenerator {
- public:
-
-  VM_Version_StubGenerator(CodeBuffer *c) : StubCodeGenerator(c) {}
-
-  address generate_getPsrInfo() {
-    // Flags to test CPU type.
-    const uint32_t EFL_AC           = 0x40000;
-    const uint32_t EFL_ID           = 0x200000;
-    // Values for when we don't have a CPUID instruction.
-    const int      CPU_FAMILY_SHIFT = 8;
-    const uint32_t CPU_FAMILY_386   = (3 << CPU_FAMILY_SHIFT);
-    const uint32_t CPU_FAMILY_486   = (4 << CPU_FAMILY_SHIFT);
-
-    Label detect_486, cpu486, detect_586, std_cpuid1;
-    Label ext_cpuid1, ext_cpuid5, done;
-
-    StubCodeMark mark(this, "VM_Version", "getPsrInfo_stub");
-#   define __ _masm->
-
-    address start = __ pc();
-
-    //
-    // void getPsrInfo(VM_Version::CpuidInfo* cpuid_info);
-    //
-    __ push(rbp);
-    __ movptr(rbp, Address(rsp, 8)); // cpuid_info address
-    __ push(rbx);
-    __ push(rsi);
-    __ pushf();          // preserve rbx, and flags
-    __ pop(rax);
-    __ push(rax);
-    __ mov(rcx, rax);
-    //
-    // if we are unable to change the AC flag, we have a 386
-    //
-    __ xorl(rax, EFL_AC);
-    __ push(rax);
-    __ popf();
-    __ pushf();
-    __ pop(rax);
-    __ cmpptr(rax, rcx);
-    __ jccb(Assembler::notEqual, detect_486);
-
-    __ movl(rax, CPU_FAMILY_386);
-    __ movl(Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())), rax);
-    __ jmp(done);
-
-    //
-    // If we are unable to change the ID flag, we have a 486 which does
-    // not support the "cpuid" instruction.
-    //
-    __ bind(detect_486);
-    __ mov(rax, rcx);
-    __ xorl(rax, EFL_ID);
-    __ push(rax);
-    __ popf();
-    __ pushf();
-    __ pop(rax);
-    __ cmpptr(rcx, rax);
-    __ jccb(Assembler::notEqual, detect_586);
-
-    __ bind(cpu486);
-    __ movl(rax, CPU_FAMILY_486);
-    __ movl(Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())), rax);
-    __ jmp(done);
-
-    //
-    // at this point, we have a chip which supports the "cpuid" instruction
-    //
-    __ bind(detect_586);
-    __ xorptr(rax, rax);
-    __ cpuid();
-    __ orptr(rax, rax);
-    __ jcc(Assembler::equal, cpu486);   // if cpuid doesn't support an input
-                                        // value of at least 1, we give up and
-                                        // assume a 486
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid0_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    __ cmpl(rax, 3);     // Is cpuid(0x4) supported?
-    __ jccb(Assembler::belowEqual, std_cpuid1);
-
-    //
-    // cpuid(0x4) Deterministic cache params
-    //
-    __ movl(rax, 4);     // and rcx already set to 0x0
-    __ xorl(rcx, rcx);
-    __ cpuid();
-    __ push(rax);
-    __ andl(rax, 0x1f);  // Determine if valid cache parameters used
-    __ orl(rax, rax);    // rax,[4:0] == 0 indicates invalid cache
-    __ pop(rax);
-    __ jccb(Assembler::equal, std_cpuid1);
-
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::dcp_cpuid4_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Standard cpuid(0x1)
-    //
-    __ bind(std_cpuid1);
-    __ movl(rax, 1);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    __ movl(rax, 0x80000000);
-    __ cpuid();
-    __ cmpl(rax, 0x80000000);     // Is cpuid(0x80000001) supported?
-    __ jcc(Assembler::belowEqual, done);
-    __ cmpl(rax, 0x80000004);     // Is cpuid(0x80000005) supported?
-    __ jccb(Assembler::belowEqual, ext_cpuid1);
-    __ cmpl(rax, 0x80000007);     // Is cpuid(0x80000008) supported?
-    __ jccb(Assembler::belowEqual, ext_cpuid5);
-    //
-    // Extended cpuid(0x80000008)
-    //
-    __ movl(rax, 0x80000008);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid8_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Extended cpuid(0x80000005)
-    //
-    __ bind(ext_cpuid5);
-    __ movl(rax, 0x80000005);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid5_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Extended cpuid(0x80000001)
-    //
-    __ bind(ext_cpuid1);
-    __ movl(rax, 0x80000001);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid1_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // return
-    //
-    __ bind(done);
-    __ popf();
-    __ pop(rsi);
-    __ pop(rbx);
-    __ pop(rbp);
-    __ ret(0);
-
-#   undef __
-
-    return start;
-  };
-};
-
-
-void VM_Version::get_processor_features() {
-
-  _cpu = 4; // 486 by default
-  _model = 0;
-  _stepping = 0;
-  _cpuFeatures = 0;
-  _logical_processors_per_package = 1;
-  if (!Use486InstrsOnly) {
-    // Get raw processor info
-    getPsrInfo_stub(&_cpuid_info);
-    assert_is_initialized();
-    _cpu = extended_cpu_family();
-    _model = extended_cpu_model();
-    _stepping = cpu_stepping();
-    if (cpu_family() > 4) { // it supports CPUID
-      _cpuFeatures = feature_flags();
-      // Logical processors are only available on P4s and above,
-      // and only if hyperthreading is available.
-      _logical_processors_per_package = logical_processor_count();
-    }
-  }
-  _supports_cx8 = supports_cmpxchg8();
-  // if the OS doesn't support SSE, we can't use this feature even if the HW does
-  if( !os::supports_sse())
-    _cpuFeatures &= ~(CPU_SSE|CPU_SSE2|CPU_SSE3|CPU_SSSE3|CPU_SSE4A|CPU_SSE4_1|CPU_SSE4_2);
-  if (UseSSE < 4) {
-    _cpuFeatures &= ~CPU_SSE4_1;
-    _cpuFeatures &= ~CPU_SSE4_2;
-  }
-  if (UseSSE < 3) {
-    _cpuFeatures &= ~CPU_SSE3;
-    _cpuFeatures &= ~CPU_SSSE3;
-    _cpuFeatures &= ~CPU_SSE4A;
-  }
-  if (UseSSE < 2)
-    _cpuFeatures &= ~CPU_SSE2;
-  if (UseSSE < 1)
-    _cpuFeatures &= ~CPU_SSE;
-
-  if (logical_processors_per_package() == 1) {
-    // HT processor could be installed on a system which doesn't support HT.
-    _cpuFeatures &= ~CPU_HT;
-  }
-
-  char buf[256];
-  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
-               cores_per_cpu(), threads_per_core(),
-               cpu_family(), _model, _stepping,
-               (supports_cmov() ? ", cmov" : ""),
-               (supports_cmpxchg8() ? ", cx8" : ""),
-               (supports_fxsr() ? ", fxsr" : ""),
-               (supports_mmx()  ? ", mmx"  : ""),
-               (supports_sse()  ? ", sse"  : ""),
-               (supports_sse2() ? ", sse2" : ""),
-               (supports_sse3() ? ", sse3" : ""),
-               (supports_ssse3()? ", ssse3": ""),
-               (supports_sse4_1() ? ", sse4.1" : ""),
-               (supports_sse4_2() ? ", sse4.2" : ""),
-               (supports_mmx_ext() ? ", mmxext" : ""),
-               (supports_3dnow()   ? ", 3dnow"  : ""),
-               (supports_3dnow2()  ? ", 3dnowext" : ""),
-               (supports_sse4a()   ? ", sse4a": ""),
-               (supports_ht() ? ", ht": ""));
-  _features_str = strdup(buf);
-
-  // UseSSE is set to the smaller of what hardware supports and what
-  // the command line requires.  I.e., you cannot set UseSSE to 2 on
-  // older Pentiums which do not support it.
-  if( UseSSE > 4 ) UseSSE=4;
-  if( UseSSE < 0 ) UseSSE=0;
-  if( !supports_sse4_1() ) // Drop to 3 if no SSE4 support
-    UseSSE = MIN2((intx)3,UseSSE);
-  if( !supports_sse3() ) // Drop to 2 if no SSE3 support
-    UseSSE = MIN2((intx)2,UseSSE);
-  if( !supports_sse2() ) // Drop to 1 if no SSE2 support
-    UseSSE = MIN2((intx)1,UseSSE);
-  if( !supports_sse () ) // Drop to 0 if no SSE  support
-    UseSSE = 0;
-
-  // On new cpus instructions which update whole XMM register should be used
-  // to prevent partial register stall due to dependencies on high half.
-  //
-  // UseXmmLoadAndClearUpper == true  --> movsd(xmm, mem)
-  // UseXmmLoadAndClearUpper == false --> movlpd(xmm, mem)
-  // UseXmmRegToRegMoveAll == true  --> movaps(xmm, xmm), movapd(xmm, xmm).
-  // UseXmmRegToRegMoveAll == false --> movss(xmm, xmm),  movsd(xmm, xmm).
-
-  if( is_amd() ) { // AMD cpus specific settings
-    if( supports_sse2() && FLAG_IS_DEFAULT(UseAddressNop) ) {
-      // Use it on new AMD cpus starting from Opteron.
-      UseAddressNop = true;
-    }
-    if( supports_sse2() && FLAG_IS_DEFAULT(UseNewLongLShift) ) {
-      // Use it on new AMD cpus starting from Opteron.
-      UseNewLongLShift = true;
-    }
-    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
-      if( supports_sse4a() ) {
-        UseXmmLoadAndClearUpper = true; // use movsd only on '10h' Opteron
-      } else {
-        UseXmmLoadAndClearUpper = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
-      if( supports_sse4a() ) {
-        UseXmmRegToRegMoveAll = true; // use movaps, movapd only on '10h'
-      } else {
-        UseXmmRegToRegMoveAll = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmI2F) ) {
-      if( supports_sse4a() ) {
-        UseXmmI2F = true;
-      } else {
-        UseXmmI2F = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmI2D) ) {
-      if( supports_sse4a() ) {
-        UseXmmI2D = true;
-      } else {
-        UseXmmI2D = false;
-      }
-    }
-  }
-
-  if( is_intel() ) { // Intel cpus specific settings
-    if( FLAG_IS_DEFAULT(UseStoreImmI16) ) {
-      UseStoreImmI16 = false; // don't use it on Intel cpus
-    }
-    if( cpu_family() == 6 || cpu_family() == 15 ) {
-      if( FLAG_IS_DEFAULT(UseAddressNop) ) {
-        // Use it on all Intel cpus starting from PentiumPro
-        UseAddressNop = true;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
-      UseXmmLoadAndClearUpper = true; // use movsd on all Intel cpus
-    }
-    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
-      if( supports_sse3() ) {
-        UseXmmRegToRegMoveAll = true; // use movaps, movapd on new Intel cpus
-      } else {
-        UseXmmRegToRegMoveAll = false;
-      }
-    }
-    if( cpu_family() == 6 && supports_sse3() ) { // New Intel cpus
-#ifdef COMPILER2
-      if( FLAG_IS_DEFAULT(MaxLoopPad) ) {
-        // For new Intel cpus do the next optimization:
-        // don't align the beginning of a loop if there are enough instructions
-        // left (NumberOfLoopInstrToAlign defined in c2_globals.hpp)
-        // in current fetch line (OptoLoopAlignment) or the padding
-        // is big (> MaxLoopPad).
-        // Set MaxLoopPad to 11 for new Intel cpus to reduce number of
-        // generated NOP instructions. 11 is the largest size of one
-        // address NOP instruction '0F 1F' (see Assembler::nop(i)).
-        MaxLoopPad = 11;
-      }
-#endif // COMPILER2
-      if( FLAG_IS_DEFAULT(UseXMMForArrayCopy) ) {
-        UseXMMForArrayCopy = true; // use SSE2 movq on new Intel cpus
-      }
-      if( supports_sse4_2() && supports_ht() ) { // Newest Intel cpus
-        if( FLAG_IS_DEFAULT(UseUnalignedLoadStores) && UseXMMForArrayCopy ) {
-          UseUnalignedLoadStores = true; // use movdqu on newest Intel cpus
-        }
-      }
-    }
-  }
-
-  assert(0 <= ReadPrefetchInstr && ReadPrefetchInstr <= 3, "invalid value");
-  assert(0 <= AllocatePrefetchInstr && AllocatePrefetchInstr <= 3, "invalid value");
-
-  // set valid Prefetch instruction
-  if( ReadPrefetchInstr < 0 ) ReadPrefetchInstr = 0;
-  if( ReadPrefetchInstr > 3 ) ReadPrefetchInstr = 3;
-  if( ReadPrefetchInstr == 3 && !supports_3dnow() ) ReadPrefetchInstr = 0;
-  if( !supports_sse() && supports_3dnow() ) ReadPrefetchInstr = 3;
-
-  if( AllocatePrefetchInstr < 0 ) AllocatePrefetchInstr = 0;
-  if( AllocatePrefetchInstr > 3 ) AllocatePrefetchInstr = 3;
-  if( AllocatePrefetchInstr == 3 && !supports_3dnow() ) AllocatePrefetchInstr=0;
-  if( !supports_sse() && supports_3dnow() ) AllocatePrefetchInstr = 3;
-
-  // Allocation prefetch settings
-  intx cache_line_size = L1_data_cache_line_size();
-  if( cache_line_size > AllocatePrefetchStepSize )
-    AllocatePrefetchStepSize = cache_line_size;
-  if( FLAG_IS_DEFAULT(AllocatePrefetchLines) )
-    AllocatePrefetchLines = 3; // Optimistic value
-  assert(AllocatePrefetchLines > 0, "invalid value");
-  if( AllocatePrefetchLines < 1 ) // set valid value in product VM
-    AllocatePrefetchLines = 1; // Conservative value
-
-  AllocatePrefetchDistance = allocate_prefetch_distance();
-  AllocatePrefetchStyle    = allocate_prefetch_style();
-
-  if( AllocatePrefetchStyle == 2 && is_intel() &&
-      cpu_family() == 6 && supports_sse3() ) { // watermark prefetching on Core
-    AllocatePrefetchDistance = 320;
-  }
-  assert(AllocatePrefetchDistance % AllocatePrefetchStepSize == 0, "invalid value");
-
-#ifndef PRODUCT
-  if (PrintMiscellaneous && Verbose) {
-    tty->print_cr("Logical CPUs per core: %u",
-                  logical_processors_per_package());
-    tty->print_cr("UseSSE=%d",UseSSE);
-    tty->print("Allocation: ");
-    if (AllocatePrefetchStyle <= 0 || UseSSE == 0 && !supports_3dnow()) {
-      tty->print_cr("no prefetching");
-    } else {
-      if (UseSSE == 0 && supports_3dnow()) {
-        tty->print("PREFETCHW");
-      } else if (UseSSE >= 1) {
-        if (AllocatePrefetchInstr == 0) {
-          tty->print("PREFETCHNTA");
-        } else if (AllocatePrefetchInstr == 1) {
-          tty->print("PREFETCHT0");
-        } else if (AllocatePrefetchInstr == 2) {
-          tty->print("PREFETCHT2");
-        } else if (AllocatePrefetchInstr == 3) {
-          tty->print("PREFETCHW");
-        }
-      }
-      if (AllocatePrefetchLines > 1) {
-        tty->print_cr(" %d, %d lines with step %d bytes", AllocatePrefetchDistance, AllocatePrefetchLines, AllocatePrefetchStepSize);
-      } else {
-        tty->print_cr(" %d, one line", AllocatePrefetchDistance);
-      }
-    }
-  }
-#endif // !PRODUCT
-}
-
-void VM_Version::initialize() {
-  ResourceMark rm;
-  // Making this stub must be FIRST use of assembler
-
-  stub_blob = BufferBlob::create("getPsrInfo_stub", stub_size);
-  if (stub_blob == NULL) {
-    vm_exit_during_initialization("Unable to allocate getPsrInfo_stub");
-  }
-  CodeBuffer c(stub_blob->instructions_begin(),
-               stub_blob->instructions_size());
-  VM_Version_StubGenerator g(&c);
-  getPsrInfo_stub = CAST_TO_FN_PTR(getPsrInfo_stub_t,
-                                   g.generate_getPsrInfo());
-
-  get_processor_features();
-}
--- a/hotspot/src/cpu/x86/vm/vm_version_x86_32.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,439 +0,0 @@
-/*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
- * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- *
- */
-
-class VM_Version: public Abstract_VM_Version {
-public:
-  // cpuid result register layouts.  These are all unions of a uint32_t
-  // (in case anyone wants access to the register as a whole) and a bitfield.
-
-  union StdCpuid1Eax {
-    uint32_t value;
-    struct {
-      uint32_t stepping   : 4,
-               model      : 4,
-               family     : 4,
-               proc_type  : 2,
-                          : 2,
-               ext_model  : 4,
-               ext_family : 8,
-                          : 4;
-    } bits;
-  };
-
-  union StdCpuid1Ebx { // example, unused
-    uint32_t value;
-    struct {
-      uint32_t brand_id         : 8,
-               clflush_size     : 8,
-               threads_per_cpu  : 8,
-               apic_id          : 8;
-    } bits;
-  };
-
-  union StdCpuid1Ecx {
-    uint32_t value;
-    struct {
-      uint32_t sse3     : 1,
-                        : 2,
-               monitor  : 1,
-                        : 1,
-               vmx      : 1,
-                        : 1,
-               est      : 1,
-                        : 1,
-               ssse3    : 1,
-               cid      : 1,
-                        : 2,
-               cmpxchg16: 1,
-                        : 4,
-               dca      : 1,
-               sse4_1   : 1,
-               sse4_2   : 1,
-                        : 11;
-    } bits;
-  };
-
-  union StdCpuid1Edx {
-    uint32_t value;
-    struct {
-      uint32_t          : 4,
-               tsc      : 1,
-                        : 3,
-               cmpxchg8 : 1,
-                        : 6,
-               cmov     : 1,
-                        : 7,
-               mmx      : 1,
-               fxsr     : 1,
-               sse      : 1,
-               sse2     : 1,
-                        : 1,
-               ht       : 1,
-                        : 3;
-    } bits;
-  };
-
-  union DcpCpuid4Eax {
-    uint32_t value;
-    struct {
-      uint32_t cache_type    : 5,
-                             : 21,
-               cores_per_cpu : 6;
-    } bits;
-  };
-
-  union DcpCpuid4Ebx {
-    uint32_t value;
-    struct {
-      uint32_t L1_line_size  : 12,
-               partitions    : 10,
-               associativity : 10;
-    } bits;
-  };
-
-  union ExtCpuid1Ecx {
-    uint32_t value;
-    struct {
-      uint32_t LahfSahf     : 1,
-               CmpLegacy    : 1,
-                            : 4,
-               abm          : 1,
-               sse4a        : 1,
-               misalignsse  : 1,
-               prefetchw    : 1,
-                            : 22;
-    } bits;
-  };
-
-  union ExtCpuid1Edx {
-    uint32_t value;
-    struct {
-      uint32_t           : 22,
-               mmx_amd   : 1,
-               mmx       : 1,
-               fxsr      : 1,
-                         : 4,
-               long_mode : 1,
-               tdnow2    : 1,
-               tdnow     : 1;
-    } bits;
-  };
-
-  union ExtCpuid5Ex {
-    uint32_t value;
-    struct {
-      uint32_t L1_line_size : 8,
-               L1_tag_lines : 8,
-               L1_assoc     : 8,
-               L1_size      : 8;
-    } bits;
-  };
-
-  union ExtCpuid8Ecx {
-    uint32_t value;
-    struct {
-      uint32_t cores_per_cpu : 8,
-                             : 24;
-    } bits;
-  };
-
-protected:
-   static int _cpu;
-   static int _model;
-   static int _stepping;
-   static int _cpuFeatures;     // features returned by the "cpuid" instruction
-                                // 0 if this instruction is not available
-   static const char* _features_str;
-
-   enum {
-     CPU_CX8  = (1 << 0), // next bits are from cpuid 1 (EDX)
-     CPU_CMOV = (1 << 1),
-     CPU_FXSR = (1 << 2),
-     CPU_HT   = (1 << 3),
-     CPU_MMX  = (1 << 4),
-     CPU_3DNOW= (1 << 5), // 3DNow comes from cpuid 0x80000001 (EDX)
-     CPU_SSE  = (1 << 6),
-     CPU_SSE2 = (1 << 7),
-     CPU_SSE3 = (1 << 8), // sse3  comes from cpuid 1 (ECX)
-     CPU_SSSE3= (1 << 9),
-     CPU_SSE4A= (1 <<10),
-     CPU_SSE4_1 = (1 << 11),
-     CPU_SSE4_2 = (1 << 12)
-   } cpuFeatureFlags;
-
-  // cpuid information block.  All info derived from executing cpuid with
-  // various function numbers is stored here.  Intel and AMD info is
-  // merged in this block: accessor methods disentangle it.
-  //
-  // The info block is laid out in subblocks of 4 dwords corresponding to
-  // rax, rbx, rcx and rdx, whether or not they contain anything useful.
-  struct CpuidInfo {
-    // cpuid function 0
-    uint32_t std_max_function;
-    uint32_t std_vendor_name_0;
-    uint32_t std_vendor_name_1;
-    uint32_t std_vendor_name_2;
-
-    // cpuid function 1
-    StdCpuid1Eax std_cpuid1_rax;
-    StdCpuid1Ebx std_cpuid1_rbx;
-    StdCpuid1Ecx std_cpuid1_rcx;
-    StdCpuid1Edx std_cpuid1_rdx;
-
-    // cpuid function 4 (deterministic cache parameters)
-    DcpCpuid4Eax dcp_cpuid4_rax;
-    DcpCpuid4Ebx dcp_cpuid4_rbx;
-    uint32_t     dcp_cpuid4_rcx; // unused currently
-    uint32_t     dcp_cpuid4_rdx; // unused currently
-
-    // cpuid function 0x80000000 // example, unused
-    uint32_t ext_max_function;
-    uint32_t ext_vendor_name_0;
-    uint32_t ext_vendor_name_1;
-    uint32_t ext_vendor_name_2;
-
-    // cpuid function 0x80000001
-    uint32_t     ext_cpuid1_rax; // reserved
-    uint32_t     ext_cpuid1_rbx; // reserved
-    ExtCpuid1Ecx ext_cpuid1_rcx;
-    ExtCpuid1Edx ext_cpuid1_rdx;
-
-    // cpuid functions 0x80000002 thru 0x80000004: example, unused
-    uint32_t proc_name_0, proc_name_1, proc_name_2, proc_name_3;
-    uint32_t proc_name_4, proc_name_5, proc_name_6, proc_name_7;
-    uint32_t proc_name_8, proc_name_9, proc_name_10,proc_name_11;
-
-    // cpuid function 0x80000005 //AMD L1, Intel reserved
-    uint32_t     ext_cpuid5_rax; // unused currently
-    uint32_t     ext_cpuid5_rbx; // reserved
-    ExtCpuid5Ex  ext_cpuid5_rcx; // L1 data cache info (AMD)
-    ExtCpuid5Ex  ext_cpuid5_rdx; // L1 instruction cache info (AMD)
-
-    // cpuid function 0x80000008
-    uint32_t     ext_cpuid8_rax; // unused currently
-    uint32_t     ext_cpuid8_rbx; // reserved
-    ExtCpuid8Ecx ext_cpuid8_rcx;
-    uint32_t     ext_cpuid8_rdx; // reserved
-  };
-
-  // The actual cpuid info block
-  static CpuidInfo _cpuid_info;
-
-  // Extractors and predicates
-  static uint32_t extended_cpu_family() {
-    uint32_t result = _cpuid_info.std_cpuid1_rax.bits.family;
-    result += _cpuid_info.std_cpuid1_rax.bits.ext_family;
-    return result;
-  }
-  static uint32_t extended_cpu_model() {
-    uint32_t result = _cpuid_info.std_cpuid1_rax.bits.model;
-    result |= _cpuid_info.std_cpuid1_rax.bits.ext_model << 4;
-    return result;
-  }
-  static uint32_t cpu_stepping() {
-    uint32_t result = _cpuid_info.std_cpuid1_rax.bits.stepping;
-    return result;
-  }
-  static uint logical_processor_count() {
-    uint result = threads_per_core();
-    return result;
-  }
-  static uint32_t feature_flags() {
-    uint32_t result = 0;
-    if (_cpuid_info.std_cpuid1_rdx.bits.cmpxchg8 != 0)
-      result |= CPU_CX8;
-    if (_cpuid_info.std_cpuid1_rdx.bits.cmov != 0)
-      result |= CPU_CMOV;
-    if (_cpuid_info.std_cpuid1_rdx.bits.fxsr != 0 || is_amd() &&
-        _cpuid_info.ext_cpuid1_rdx.bits.fxsr != 0)
-      result |= CPU_FXSR;
-    // HT flag is set for multi-core processors also.
-    if (threads_per_core() > 1)
-      result |= CPU_HT;
-    if (_cpuid_info.std_cpuid1_rdx.bits.mmx != 0 || is_amd() &&
-        _cpuid_info.ext_cpuid1_rdx.bits.mmx != 0)
-      result |= CPU_MMX;
-    if (is_amd() && _cpuid_info.ext_cpuid1_rdx.bits.tdnow != 0)
-      result |= CPU_3DNOW;
-    if (_cpuid_info.std_cpuid1_rdx.bits.sse != 0)
-      result |= CPU_SSE;
-    if (_cpuid_info.std_cpuid1_rdx.bits.sse2 != 0)
-      result |= CPU_SSE2;
-    if (_cpuid_info.std_cpuid1_rcx.bits.sse3 != 0)
-      result |= CPU_SSE3;
-    if (_cpuid_info.std_cpuid1_rcx.bits.ssse3 != 0)
-      result |= CPU_SSSE3;
-    if (is_amd() && _cpuid_info.ext_cpuid1_rcx.bits.sse4a != 0)
-      result |= CPU_SSE4A;
-    if (_cpuid_info.std_cpuid1_rcx.bits.sse4_1 != 0)
-      result |= CPU_SSE4_1;
-    if (_cpuid_info.std_cpuid1_rcx.bits.sse4_2 != 0)
-      result |= CPU_SSE4_2;
-    return result;
-  }
-
-  static void get_processor_features();
-
-public:
-  // Offsets for cpuid asm stub
-  static ByteSize std_cpuid0_offset() { return byte_offset_of(CpuidInfo, std_max_function); }
-  static ByteSize std_cpuid1_offset() { return byte_offset_of(CpuidInfo, std_cpuid1_rax); }
-  static ByteSize dcp_cpuid4_offset() { return byte_offset_of(CpuidInfo, dcp_cpuid4_rax); }
-  static ByteSize ext_cpuid1_offset() { return byte_offset_of(CpuidInfo, ext_cpuid1_rax); }
-  static ByteSize ext_cpuid5_offset() { return byte_offset_of(CpuidInfo, ext_cpuid5_rax); }
-  static ByteSize ext_cpuid8_offset() { return byte_offset_of(CpuidInfo, ext_cpuid8_rax); }
-
-  // Initialization
-  static void initialize();
-
-  // Asserts
-  static void assert_is_initialized() {
-    assert(_cpuid_info.std_cpuid1_rax.bits.family != 0, "VM_Version not initialized");
-  }
-
-  //
-  // Processor family:
-  //       3   -  386
-  //       4   -  486
-  //       5   -  Pentium
-  //       6   -  PentiumPro, Pentium II, Celeron, Xeon, Pentium III, Athlon,
-  //              Pentium M, Core Solo, Core Duo, Core2 Duo
-  //    family 6 model:   9,        13,       14,        15
-  //    0x0f   -  Pentium 4, Opteron
-  //
-  // Note: The cpu family should be used to select between
-  //       instruction sequences which are valid on all Intel
-  //       processors.  Use the feature test functions below to
-  //       determine whether a particular instruction is supported.
-  //
-  static int  cpu_family()        { return _cpu;}
-  static bool is_P6()             { return cpu_family() >= 6; }
-
-  static bool is_amd()            { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x68747541; } // 'htuA'
-  static bool is_intel()          { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x756e6547; } // 'uneG'
-
-  static uint cores_per_cpu()  {
-    uint result = 1;
-    if (is_intel()) {
-      result = (_cpuid_info.dcp_cpuid4_rax.bits.cores_per_cpu + 1);
-    } else if (is_amd()) {
-      result = (_cpuid_info.ext_cpuid8_rcx.bits.cores_per_cpu + 1);
-    }
-    return result;
-  }
-
-  static uint threads_per_core()  {
-    uint result = 1;
-    if (_cpuid_info.std_cpuid1_rdx.bits.ht != 0) {
-      result = _cpuid_info.std_cpuid1_rbx.bits.threads_per_cpu /
-               cores_per_cpu();
-    }
-    return result;
-  }
-
-  static intx L1_data_cache_line_size()  {
-    intx result = 0;
-    if (is_intel()) {
-      result = (_cpuid_info.dcp_cpuid4_rbx.bits.L1_line_size + 1);
-    } else if (is_amd()) {
-      result = _cpuid_info.ext_cpuid5_rcx.bits.L1_line_size;
-    }
-    if (result < 32) // not defined ?
-      result = 32;   // 32 bytes by default on x86
-    return result;
-  }
-
-  //
-  // Feature identification
-  //
-  static bool supports_cpuid()    { return _cpuFeatures  != 0; }
-  static bool supports_cmpxchg8() { return (_cpuFeatures & CPU_CX8) != 0; }
-  static bool supports_cmov()     { return (_cpuFeatures & CPU_CMOV) != 0; }
-  static bool supports_fxsr()     { return (_cpuFeatures & CPU_FXSR) != 0; }
-  static bool supports_ht()       { return (_cpuFeatures & CPU_HT) != 0; }
-  static bool supports_mmx()      { return (_cpuFeatures & CPU_MMX) != 0; }
-  static bool supports_sse()      { return (_cpuFeatures & CPU_SSE) != 0; }
-  static bool supports_sse2()     { return (_cpuFeatures & CPU_SSE2) != 0; }
-  static bool supports_sse3()     { return (_cpuFeatures & CPU_SSE3) != 0; }
-  static bool supports_ssse3()    { return (_cpuFeatures & CPU_SSSE3)!= 0; }
-  static bool supports_sse4_1()   { return (_cpuFeatures & CPU_SSE4_1) != 0; }
-  static bool supports_sse4_2()   { return (_cpuFeatures & CPU_SSE4_2) != 0; }
-  //
-  // AMD features
-  //
-  static bool supports_3dnow()    { return (_cpuFeatures & CPU_3DNOW) != 0; }
-  static bool supports_mmx_ext()  { return is_amd() && _cpuid_info.ext_cpuid1_rdx.bits.mmx_amd != 0; }
-  static bool supports_3dnow2()   { return is_amd() && _cpuid_info.ext_cpuid1_rdx.bits.tdnow2 != 0; }
-  static bool supports_sse4a()    { return (_cpuFeatures & CPU_SSE4A) != 0; }
-
-  static bool supports_compare_and_exchange() { return true; }
-
-  static const char* cpu_features()           { return _features_str; }
-
-  static intx allocate_prefetch_distance() {
-    // This method should be called before allocate_prefetch_style().
-    //
-    // Hardware prefetching (distance/size in bytes):
-    // Pentium 3 -  64 /  32
-    // Pentium 4 - 256 / 128
-    // Athlon    -  64 /  32 ????
-    // Opteron   - 128 /  64 only when 2 sequential cache lines accessed
-    // Core      - 128 /  64
-    //
-    // Software prefetching (distance in bytes / instruction with best score):
-    // Pentium 3 - 128 / prefetchnta
-    // Pentium 4 - 512 / prefetchnta
-    // Athlon    - 128 / prefetchnta
-    // Opteron   - 256 / prefetchnta
-    // Core      - 256 / prefetchnta
-    // It will be used only when AllocatePrefetchStyle > 0
-
-    intx count = AllocatePrefetchDistance;
-    if (count < 0) {   // default ?
-      if (is_amd()) {  // AMD
-        if (supports_sse2())
-          count = 256; // Opteron
-        else
-          count = 128; // Athlon
-      } else {         // Intel
-        if (supports_sse2())
-          if (cpu_family() == 6) {
-            count = 256; // Pentium M, Core, Core2
-          } else {
-            count = 512; // Pentium 4
-          }
-        else
-          count = 128; // Pentium 3 (and all other old CPUs)
-      }
-    }
-    return count;
-  }
-  static intx allocate_prefetch_style() {
-    assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
-    // Return 0 if AllocatePrefetchDistance was not defined or
-    // prefetch instruction is not supported.
-    return (AllocatePrefetchDistance > 0 &&
-            (supports_3dnow() || supports_sse())) ? AllocatePrefetchStyle : 0;
-  }
-};
--- a/hotspot/src/cpu/x86/vm/vm_version_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,419 +0,0 @@
-/*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
- * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- *
- */
-
-# include "incls/_precompiled.incl"
-# include "incls/_vm_version_x86_64.cpp.incl"
-
-int VM_Version::_cpu;
-int VM_Version::_model;
-int VM_Version::_stepping;
-int VM_Version::_cpuFeatures;
-const char*           VM_Version::_features_str = "";
-VM_Version::CpuidInfo VM_Version::_cpuid_info   = { 0, };
-
-static BufferBlob* stub_blob;
-static const int stub_size = 300;
-
-extern "C" {
-  typedef void (*getPsrInfo_stub_t)(void*);
-}
-static getPsrInfo_stub_t getPsrInfo_stub = NULL;
-
-
-class VM_Version_StubGenerator: public StubCodeGenerator {
- public:
-
-  VM_Version_StubGenerator(CodeBuffer *c) : StubCodeGenerator(c) {}
-
-  address generate_getPsrInfo() {
-
-    Label std_cpuid1, ext_cpuid1, ext_cpuid5, done;
-
-    StubCodeMark mark(this, "VM_Version", "getPsrInfo_stub");
-#   define __ _masm->
-
-    address start = __ pc();
-
-    //
-    // void getPsrInfo(VM_Version::CpuidInfo* cpuid_info);
-    //
-    // rcx and rdx are first and second argument registers on windows
-
-    __ push(rbp);
-    __ mov(rbp, c_rarg0); // cpuid_info address
-    __ push(rbx);
-    __ push(rsi);
-
-    //
-    // we have a chip which supports the "cpuid" instruction
-    //
-    __ xorl(rax, rax);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid0_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    __ cmpl(rax, 3);     // Is cpuid(0x4) supported?
-    __ jccb(Assembler::belowEqual, std_cpuid1);
-
-    //
-    // cpuid(0x4) Deterministic cache params
-    //
-    __ movl(rax, 4);
-    __ xorl(rcx, rcx);   // L1 cache
-    __ cpuid();
-    __ push(rax);
-    __ andl(rax, 0x1f);  // Determine if valid cache parameters used
-    __ orl(rax, rax);    // eax[4:0] == 0 indicates invalid cache
-    __ pop(rax);
-    __ jccb(Assembler::equal, std_cpuid1);
-
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::dcp_cpuid4_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Standard cpuid(0x1)
-    //
-    __ bind(std_cpuid1);
-    __ movl(rax, 1);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::std_cpuid1_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    __ movl(rax, 0x80000000);
-    __ cpuid();
-    __ cmpl(rax, 0x80000000);     // Is cpuid(0x80000001) supported?
-    __ jcc(Assembler::belowEqual, done);
-    __ cmpl(rax, 0x80000004);     // Is cpuid(0x80000005) supported?
-    __ jccb(Assembler::belowEqual, ext_cpuid1);
-    __ cmpl(rax, 0x80000007);     // Is cpuid(0x80000008) supported?
-    __ jccb(Assembler::belowEqual, ext_cpuid5);
-    //
-    // Extended cpuid(0x80000008)
-    //
-    __ movl(rax, 0x80000008);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid8_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Extended cpuid(0x80000005)
-    //
-    __ bind(ext_cpuid5);
-    __ movl(rax, 0x80000005);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid5_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // Extended cpuid(0x80000001)
-    //
-    __ bind(ext_cpuid1);
-    __ movl(rax, 0x80000001);
-    __ cpuid();
-    __ lea(rsi, Address(rbp, in_bytes(VM_Version::ext_cpuid1_offset())));
-    __ movl(Address(rsi, 0), rax);
-    __ movl(Address(rsi, 4), rbx);
-    __ movl(Address(rsi, 8), rcx);
-    __ movl(Address(rsi,12), rdx);
-
-    //
-    // return
-    //
-    __ bind(done);
-    __ pop(rsi);
-    __ pop(rbx);
-    __ pop(rbp);
-    __ ret(0);
-
-#   undef __
-
-    return start;
-  };
-};
-
-
-void VM_Version::get_processor_features() {
-
-  _logical_processors_per_package = 1;
-  // Get raw processor info
-  getPsrInfo_stub(&_cpuid_info);
-  assert_is_initialized();
-  _cpu = extended_cpu_family();
-  _model = extended_cpu_model();
-  _stepping = cpu_stepping();
-  _cpuFeatures = feature_flags();
-  // Logical processors are only available on P4s and above,
-  // and only if hyperthreading is available.
-  _logical_processors_per_package = logical_processor_count();
-  _supports_cx8    = supports_cmpxchg8();
-  // OS should support SSE for x64 and hardware should support at least SSE2.
-  if (!VM_Version::supports_sse2()) {
-    vm_exit_during_initialization("Unknown x64 processor: SSE2 not supported");
-  }
-  if (UseSSE < 4) {
-    _cpuFeatures &= ~CPU_SSE4_1;
-    _cpuFeatures &= ~CPU_SSE4_2;
-  }
-  if (UseSSE < 3) {
-    _cpuFeatures &= ~CPU_SSE3;
-    _cpuFeatures &= ~CPU_SSSE3;
-    _cpuFeatures &= ~CPU_SSE4A;
-  }
-  if (UseSSE < 2)
-    _cpuFeatures &= ~CPU_SSE2;
-  if (UseSSE < 1)
-    _cpuFeatures &= ~CPU_SSE;
-
-  if (logical_processors_per_package() == 1) {
-    // HT processor could be installed on a system which doesn't support HT.
-    _cpuFeatures &= ~CPU_HT;
-  }
-
-  char buf[256];
-  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
-               cores_per_cpu(), threads_per_core(),
-               cpu_family(), _model, _stepping,
-               (supports_cmov() ? ", cmov" : ""),
-               (supports_cmpxchg8() ? ", cx8" : ""),
-               (supports_fxsr() ? ", fxsr" : ""),
-               (supports_mmx()  ? ", mmx"  : ""),
-               (supports_sse()  ? ", sse"  : ""),
-               (supports_sse2() ? ", sse2" : ""),
-               (supports_sse3() ? ", sse3" : ""),
-               (supports_ssse3()? ", ssse3": ""),
-               (supports_sse4_1() ? ", sse4.1" : ""),
-               (supports_sse4_2() ? ", sse4.2" : ""),
-               (supports_mmx_ext() ? ", mmxext" : ""),
-               (supports_3dnow()   ? ", 3dnow"  : ""),
-               (supports_3dnow2()  ? ", 3dnowext" : ""),
-               (supports_sse4a()   ? ", sse4a": ""),
-               (supports_ht() ? ", ht": ""));
-  _features_str = strdup(buf);
-
-  // UseSSE is set to the smaller of what hardware supports and what
-  // the command line requires.  I.e., you cannot set UseSSE to 2 on
-  // older Pentiums which do not support it.
-  if( UseSSE > 4 ) UseSSE=4;
-  if( UseSSE < 0 ) UseSSE=0;
-  if( !supports_sse4_1() ) // Drop to 3 if no SSE4 support
-    UseSSE = MIN2((intx)3,UseSSE);
-  if( !supports_sse3() ) // Drop to 2 if no SSE3 support
-    UseSSE = MIN2((intx)2,UseSSE);
-  if( !supports_sse2() ) // Drop to 1 if no SSE2 support
-    UseSSE = MIN2((intx)1,UseSSE);
-  if( !supports_sse () ) // Drop to 0 if no SSE  support
-    UseSSE = 0;
-
-  // On new cpus instructions which update whole XMM register should be used
-  // to prevent partial register stall due to dependencies on high half.
-  //
-  // UseXmmLoadAndClearUpper == true  --> movsd(xmm, mem)
-  // UseXmmLoadAndClearUpper == false --> movlpd(xmm, mem)
-  // UseXmmRegToRegMoveAll == true  --> movaps(xmm, xmm), movapd(xmm, xmm).
-  // UseXmmRegToRegMoveAll == false --> movss(xmm, xmm),  movsd(xmm, xmm).
-
-  if( is_amd() ) { // AMD cpus specific settings
-    if( FLAG_IS_DEFAULT(UseAddressNop) ) {
-      // Use it on all AMD cpus starting from Opteron (don't need
-      // a cpu check since only Opteron and new cpus support 64-bits mode).
-      UseAddressNop = true;
-    }
-    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
-      if( supports_sse4a() ) {
-        UseXmmLoadAndClearUpper = true; // use movsd only on '10h' Opteron
-      } else {
-        UseXmmLoadAndClearUpper = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
-      if( supports_sse4a() ) {
-        UseXmmRegToRegMoveAll = true; // use movaps, movapd only on '10h'
-      } else {
-        UseXmmRegToRegMoveAll = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmI2F) ) {
-      if( supports_sse4a() ) {
-        UseXmmI2F = true;
-      } else {
-        UseXmmI2F = false;
-      }
-    }
-    if( FLAG_IS_DEFAULT(UseXmmI2D) ) {
-      if( supports_sse4a() ) {
-        UseXmmI2D = true;
-      } else {
-        UseXmmI2D = false;
-      }
-    }
-  }
-
-  if( is_intel() ) { // Intel cpus specific settings
-    if( FLAG_IS_DEFAULT(UseStoreImmI16) ) {
-      UseStoreImmI16 = false; // don't use it on Intel cpus
-    }
-    if( FLAG_IS_DEFAULT(UseAddressNop) ) {
-      // Use it on all Intel cpus starting from PentiumPro
-      // (don't need a cpu check since only new cpus support 64-bits mode).
-      UseAddressNop = true;
-    }
-    if( FLAG_IS_DEFAULT(UseXmmLoadAndClearUpper) ) {
-      UseXmmLoadAndClearUpper = true; // use movsd on all Intel cpus
-    }
-    if( FLAG_IS_DEFAULT(UseXmmRegToRegMoveAll) ) {
-      if( supports_sse3() ) {
-        UseXmmRegToRegMoveAll = true; // use movaps, movapd on new Intel cpus
-      } else {
-        UseXmmRegToRegMoveAll = false;
-      }
-    }
-    if( cpu_family() == 6 && supports_sse3() ) { // New Intel cpus
-#ifdef COMPILER2
-      if( FLAG_IS_DEFAULT(MaxLoopPad) ) {
-        // For new Intel cpus do the next optimization:
-        // don't align the beginning of a loop if there are enough instructions
-        // left (NumberOfLoopInstrToAlign defined in c2_globals.hpp)
-        // in current fetch line (OptoLoopAlignment) or the padding
-        // is big (> MaxLoopPad).
-        // Set MaxLoopPad to 11 for new Intel cpus to reduce number of
-        // generated NOP instructions. 11 is the largest size of one
-        // address NOP instruction '0F 1F' (see Assembler::nop(i)).
-        MaxLoopPad = 11;
-      }
-#endif // COMPILER2
-      if( FLAG_IS_DEFAULT(UseXMMForArrayCopy) ) {
-        UseXMMForArrayCopy = true; // use SSE2 movq on new Intel cpus
-      }
-      if( supports_sse4_2() && supports_ht() ) { // Newest Intel cpus
-        if( FLAG_IS_DEFAULT(UseUnalignedLoadStores) && UseXMMForArrayCopy ) {
-          UseUnalignedLoadStores = true; // use movdqu on newest Intel cpus
-        }
-      }
-    }
-  }
-
-  assert(0 <= ReadPrefetchInstr && ReadPrefetchInstr <= 3, "invalid value");
-  assert(0 <= AllocatePrefetchInstr && AllocatePrefetchInstr <= 3, "invalid value");
-
-  // set valid Prefetch instruction
-  if( ReadPrefetchInstr < 0 ) ReadPrefetchInstr = 0;
-  if( ReadPrefetchInstr > 3 ) ReadPrefetchInstr = 3;
-  if( ReadPrefetchInstr == 3 && !supports_3dnow() ) ReadPrefetchInstr = 0;
-
-  if( AllocatePrefetchInstr < 0 ) AllocatePrefetchInstr = 0;
-  if( AllocatePrefetchInstr > 3 ) AllocatePrefetchInstr = 3;
-  if( AllocatePrefetchInstr == 3 && !supports_3dnow() ) AllocatePrefetchInstr=0;
-
-  // Allocation prefetch settings
-  intx cache_line_size = L1_data_cache_line_size();
-  if( cache_line_size > AllocatePrefetchStepSize )
-    AllocatePrefetchStepSize = cache_line_size;
-  if( FLAG_IS_DEFAULT(AllocatePrefetchLines) )
-    AllocatePrefetchLines = 3; // Optimistic value
-  assert(AllocatePrefetchLines > 0, "invalid value");
-  if( AllocatePrefetchLines < 1 ) // set valid value in product VM
-    AllocatePrefetchLines = 1; // Conservative value
-
-  AllocatePrefetchDistance = allocate_prefetch_distance();
-  AllocatePrefetchStyle    = allocate_prefetch_style();
-
-  if( AllocatePrefetchStyle == 2 && is_intel() &&
-      cpu_family() == 6 && supports_sse3() ) { // watermark prefetching on Core
-    AllocatePrefetchDistance = 384;
-  }
-  assert(AllocatePrefetchDistance % AllocatePrefetchStepSize == 0, "invalid value");
-
-  // Prefetch settings
-  PrefetchCopyIntervalInBytes = prefetch_copy_interval_in_bytes();
-  PrefetchScanIntervalInBytes = prefetch_scan_interval_in_bytes();
-  PrefetchFieldsAhead         = prefetch_fields_ahead();
-
-#ifndef PRODUCT
-  if (PrintMiscellaneous && Verbose) {
-    tty->print_cr("Logical CPUs per core: %u",
-                  logical_processors_per_package());
-    tty->print_cr("UseSSE=%d",UseSSE);
-    tty->print("Allocation: ");
-    if (AllocatePrefetchStyle <= 0) {
-      tty->print_cr("no prefetching");
-    } else {
-      if (AllocatePrefetchInstr == 0) {
-        tty->print("PREFETCHNTA");
-      } else if (AllocatePrefetchInstr == 1) {
-        tty->print("PREFETCHT0");
-      } else if (AllocatePrefetchInstr == 2) {
-        tty->print("PREFETCHT2");
-      } else if (AllocatePrefetchInstr == 3) {
-        tty->print("PREFETCHW");
-      }
-      if (AllocatePrefetchLines > 1) {
-        tty->print_cr(" %d, %d lines with step %d bytes", AllocatePrefetchDistance, AllocatePrefetchLines, AllocatePrefetchStepSize);
-      } else {
-        tty->print_cr(" %d, one line", AllocatePrefetchDistance);
-      }
-    }
-    if (PrefetchCopyIntervalInBytes > 0) {
-      tty->print_cr("PrefetchCopyIntervalInBytes %d", PrefetchCopyIntervalInBytes);
-    }
-    if (PrefetchScanIntervalInBytes > 0) {
-      tty->print_cr("PrefetchScanIntervalInBytes %d", PrefetchScanIntervalInBytes);
-    }
-    if (PrefetchFieldsAhead > 0) {
-      tty->print_cr("PrefetchFieldsAhead %d", PrefetchFieldsAhead);
-    }
-  }
-#endif // !PRODUCT
-}
-
-void VM_Version::initialize() {
-  ResourceMark rm;
-  // Making this stub must be FIRST use of assembler
-
-  stub_blob = BufferBlob::create("getPsrInfo_stub", stub_size);
-  if (stub_blob == NULL) {
-    vm_exit_during_initialization("Unable to allocate getPsrInfo_stub");
-  }
-  CodeBuffer c(stub_blob->instructions_begin(),
-               stub_blob->instructions_size());
-  VM_Version_StubGenerator g(&c);
-  getPsrInfo_stub = CAST_TO_FN_PTR(getPsrInfo_stub_t,
-                                   g.generate_getPsrInfo());
-
-  get_processor_features();
-}
--- a/hotspot/src/cpu/x86/vm/vm_version_x86_64.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,449 +0,0 @@
-/*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
- * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- *
- */
-
-class VM_Version : public Abstract_VM_Version {
-public:
-  // cpuid result register layouts.  These are all unions of a uint32_t
-  // (in case anyone wants access to the register as a whole) and a bitfield.
-
-  union StdCpuid1Eax {
-    uint32_t value;
-    struct {
-      uint32_t stepping   : 4,
-               model      : 4,
-               family     : 4,
-               proc_type  : 2,
-                          : 2,
-               ext_model  : 4,
-               ext_family : 8,
-                          : 4;
-    } bits;
-  };
-
-  union StdCpuid1Ebx { // example, unused
-    uint32_t value;
-    struct {
-      uint32_t brand_id         : 8,
-               clflush_size     : 8,
-               threads_per_cpu  : 8,
-               apic_id          : 8;
-    } bits;
-  };
-
-  union StdCpuid1Ecx {
-    uint32_t value;
-    struct {
-      uint32_t sse3     : 1,
-                        : 2,
-               monitor  : 1,
-                        : 1,
-               vmx      : 1,
-                        : 1,
-               est      : 1,
-                        : 1,
-               ssse3    : 1,
-               cid      : 1,
-                        : 2,
-               cmpxchg16: 1,
-                        : 4,
-               dca      : 1,
-               sse4_1   : 1,
-               sse4_2   : 1,
-                        : 11;
-    } bits;
-  };
-
-  union StdCpuid1Edx {
-    uint32_t value;
-    struct {
-      uint32_t          : 4,
-               tsc      : 1,
-                        : 3,
-               cmpxchg8 : 1,
-                        : 6,
-               cmov     : 1,
-                        : 7,
-               mmx      : 1,
-               fxsr     : 1,
-               sse      : 1,
-               sse2     : 1,
-                        : 1,
-               ht       : 1,
-                        : 3;
-    } bits;
-  };
-
-  union DcpCpuid4Eax {
-    uint32_t value;
-    struct {
-      uint32_t cache_type    : 5,
-                             : 21,
-               cores_per_cpu : 6;
-    } bits;
-  };
-
-  union DcpCpuid4Ebx {
-    uint32_t value;
-    struct {
-      uint32_t L1_line_size  : 12,
-               partitions    : 10,
-               associativity : 10;
-    } bits;
-  };
-
-  union ExtCpuid1Edx {
-    uint32_t value;
-    struct {
-      uint32_t           : 22,
-               mmx_amd   : 1,
-               mmx       : 1,
-               fxsr      : 1,
-                         : 4,
-               long_mode : 1,
-               tdnow2    : 1,
-               tdnow     : 1;
-    } bits;
-  };
-
-  union ExtCpuid1Ecx {
-    uint32_t value;
-    struct {
-      uint32_t LahfSahf     : 1,
-               CmpLegacy    : 1,
-                            : 4,
-               abm          : 1,
-               sse4a        : 1,
-               misalignsse  : 1,
-               prefetchw    : 1,
-                            : 22;
-    } bits;
-  };
-
-  union ExtCpuid5Ex {
-    uint32_t value;
-    struct {
-      uint32_t L1_line_size : 8,
-               L1_tag_lines : 8,
-               L1_assoc     : 8,
-               L1_size      : 8;
-    } bits;
-  };
-
-  union ExtCpuid8Ecx {
-    uint32_t value;
-    struct {
-      uint32_t cores_per_cpu : 8,
-                             : 24;
-    } bits;
-  };
-
-protected:
-   static int _cpu;
-   static int _model;
-   static int _stepping;
-   static int _cpuFeatures;     // features returned by the "cpuid" instruction
-                                // 0 if this instruction is not available
-   static const char* _features_str;
-
-   enum {
-     CPU_CX8  = (1 << 0), // next bits are from cpuid 1 (EDX)
-     CPU_CMOV = (1 << 1),
-     CPU_FXSR = (1 << 2),
-     CPU_HT   = (1 << 3),
-     CPU_MMX  = (1 << 4),
-     CPU_3DNOW= (1 << 5),
-     CPU_SSE  = (1 << 6),
-     CPU_SSE2 = (1 << 7),
-     CPU_SSE3 = (1 << 8),
-     CPU_SSSE3= (1 << 9),
-     CPU_SSE4A= (1 <<10),
-     CPU_SSE4_1 = (1 << 11),
-     CPU_SSE4_2 = (1 << 12)
-   } cpuFeatureFlags;
-
-  // cpuid information block.  All info derived from executing cpuid with
-  // various function numbers is stored here.  Intel and AMD info is
-  // merged in this block: accessor methods disentangle it.
-  //
-  // The info block is laid out in subblocks of 4 dwords corresponding to
-  // eax, ebx, ecx and edx, whether or not they contain anything useful.
-  struct CpuidInfo {
-    // cpuid function 0
-    uint32_t std_max_function;
-    uint32_t std_vendor_name_0;
-    uint32_t std_vendor_name_1;
-    uint32_t std_vendor_name_2;
-
-    // cpuid function 1
-    StdCpuid1Eax std_cpuid1_eax;
-    StdCpuid1Ebx std_cpuid1_ebx;
-    StdCpuid1Ecx std_cpuid1_ecx;
-    StdCpuid1Edx std_cpuid1_edx;
-
-    // cpuid function 4 (deterministic cache parameters)
-    DcpCpuid4Eax dcp_cpuid4_eax;
-    DcpCpuid4Ebx dcp_cpuid4_ebx;
-    uint32_t     dcp_cpuid4_ecx; // unused currently
-    uint32_t     dcp_cpuid4_edx; // unused currently
-
-    // cpuid function 0x80000000 // example, unused
-    uint32_t ext_max_function;
-    uint32_t ext_vendor_name_0;
-    uint32_t ext_vendor_name_1;
-    uint32_t ext_vendor_name_2;
-
-    // cpuid function 0x80000001
-    uint32_t     ext_cpuid1_eax; // reserved
-    uint32_t     ext_cpuid1_ebx; // reserved
-    ExtCpuid1Ecx ext_cpuid1_ecx;
-    ExtCpuid1Edx ext_cpuid1_edx;
-
-    // cpuid functions 0x80000002 thru 0x80000004: example, unused
-    uint32_t proc_name_0, proc_name_1, proc_name_2, proc_name_3;
-    uint32_t proc_name_4, proc_name_5, proc_name_6, proc_name_7;
-    uint32_t proc_name_8, proc_name_9, proc_name_10,proc_name_11;
-
-    // cpuid function 0x80000005 //AMD L1, Intel reserved
-    uint32_t     ext_cpuid5_eax; // unused currently
-    uint32_t     ext_cpuid5_ebx; // reserved
-    ExtCpuid5Ex  ext_cpuid5_ecx; // L1 data cache info (AMD)
-    ExtCpuid5Ex  ext_cpuid5_edx; // L1 instruction cache info (AMD)
-
-    // cpuid function 0x80000008
-    uint32_t     ext_cpuid8_eax; // unused currently
-    uint32_t     ext_cpuid8_ebx; // reserved
-    ExtCpuid8Ecx ext_cpuid8_ecx;
-    uint32_t     ext_cpuid8_edx; // reserved
-  };
-
-  // The actual cpuid info block
-  static CpuidInfo _cpuid_info;
-
-  // Extractors and predicates
-  static uint32_t extended_cpu_family() {
-    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.family;
-    result += _cpuid_info.std_cpuid1_eax.bits.ext_family;
-    return result;
-  }
-  static uint32_t extended_cpu_model() {
-    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.model;
-    result |= _cpuid_info.std_cpuid1_eax.bits.ext_model << 4;
-    return result;
-  }
-  static uint32_t cpu_stepping() {
-    uint32_t result = _cpuid_info.std_cpuid1_eax.bits.stepping;
-    return result;
-  }
-  static uint logical_processor_count() {
-    uint result = threads_per_core();
-    return result;
-  }
-  static uint32_t feature_flags() {
-    uint32_t result = 0;
-    if (_cpuid_info.std_cpuid1_edx.bits.cmpxchg8 != 0)
-      result |= CPU_CX8;
-    if (_cpuid_info.std_cpuid1_edx.bits.cmov != 0)
-      result |= CPU_CMOV;
-    if (_cpuid_info.std_cpuid1_edx.bits.fxsr != 0 || is_amd() &&
-        _cpuid_info.ext_cpuid1_edx.bits.fxsr != 0)
-      result |= CPU_FXSR;
-    // HT flag is set for multi-core processors also.
-    if (threads_per_core() > 1)
-      result |= CPU_HT;
-    if (_cpuid_info.std_cpuid1_edx.bits.mmx != 0 || is_amd() &&
-        _cpuid_info.ext_cpuid1_edx.bits.mmx != 0)
-      result |= CPU_MMX;
-    if (is_amd() && _cpuid_info.ext_cpuid1_edx.bits.tdnow != 0)
-      result |= CPU_3DNOW;
-    if (_cpuid_info.std_cpuid1_edx.bits.sse != 0)
-      result |= CPU_SSE;
-    if (_cpuid_info.std_cpuid1_edx.bits.sse2 != 0)
-      result |= CPU_SSE2;
-    if (_cpuid_info.std_cpuid1_ecx.bits.sse3 != 0)
-      result |= CPU_SSE3;
-    if (_cpuid_info.std_cpuid1_ecx.bits.ssse3 != 0)
-      result |= CPU_SSSE3;
-    if (is_amd() && _cpuid_info.ext_cpuid1_ecx.bits.sse4a != 0)
-      result |= CPU_SSE4A;
-    if (_cpuid_info.std_cpuid1_ecx.bits.sse4_1 != 0)
-      result |= CPU_SSE4_1;
-    if (_cpuid_info.std_cpuid1_ecx.bits.sse4_2 != 0)
-      result |= CPU_SSE4_2;
-    return result;
-  }
-
-  static void get_processor_features();
-
-public:
-  // Offsets for cpuid asm stub
-  static ByteSize std_cpuid0_offset() { return byte_offset_of(CpuidInfo, std_max_function); }
-  static ByteSize std_cpuid1_offset() { return byte_offset_of(CpuidInfo, std_cpuid1_eax); }
-  static ByteSize dcp_cpuid4_offset() { return byte_offset_of(CpuidInfo, dcp_cpuid4_eax); }
-  static ByteSize ext_cpuid1_offset() { return byte_offset_of(CpuidInfo, ext_cpuid1_eax); }
-  static ByteSize ext_cpuid5_offset() { return byte_offset_of(CpuidInfo, ext_cpuid5_eax); }
-  static ByteSize ext_cpuid8_offset() { return byte_offset_of(CpuidInfo, ext_cpuid8_eax); }
-
-  // Initialization
-  static void initialize();
-
-  // Asserts
-  static void assert_is_initialized() {
-    assert(_cpuid_info.std_cpuid1_eax.bits.family != 0, "VM_Version not initialized");
-  }
-
-  //
-  // Processor family:
-  //       3   -  386
-  //       4   -  486
-  //       5   -  Pentium
-  //       6   -  PentiumPro, Pentium II, Celeron, Xeon, Pentium III, Athlon,
-  //              Pentium M, Core Solo, Core Duo, Core2 Duo
-  //    family 6 model:   9,        13,       14,        15
-  //    0x0f   -  Pentium 4, Opteron
-  //
-  // Note: The cpu family should be used to select between
-  //       instruction sequences which are valid on all Intel
-  //       processors.  Use the feature test functions below to
-  //       determine whether a particular instruction is supported.
-  //
-  static int  cpu_family()        { return _cpu;}
-  static bool is_P6()             { return cpu_family() >= 6; }
-
-  static bool is_amd()            { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x68747541; } // 'htuA'
-  static bool is_intel()          { assert_is_initialized(); return _cpuid_info.std_vendor_name_0 == 0x756e6547; } // 'uneG'
-
-  static uint cores_per_cpu()  {
-    uint result = 1;
-    if (is_intel()) {
-      result = (_cpuid_info.dcp_cpuid4_eax.bits.cores_per_cpu + 1);
-    } else if (is_amd()) {
-      result = (_cpuid_info.ext_cpuid8_ecx.bits.cores_per_cpu + 1);
-    }
-    return result;
-  }
-
-  static uint threads_per_core()  {
-    uint result = 1;
-    if (_cpuid_info.std_cpuid1_edx.bits.ht != 0) {
-      result = _cpuid_info.std_cpuid1_ebx.bits.threads_per_cpu /
-               cores_per_cpu();
-    }
-    return result;
-  }
-
-  static intx L1_data_cache_line_size()  {
-    intx result = 0;
-    if (is_intel()) {
-      result = (_cpuid_info.dcp_cpuid4_ebx.bits.L1_line_size + 1);
-    } else if (is_amd()) {
-      result = _cpuid_info.ext_cpuid5_ecx.bits.L1_line_size;
-    }
-    if (result < 32) // not defined ?
-      result = 32;   // 32 bytes by default for other x64
-    return result;
-  }
-
-  //
-  // Feature identification
-  //
-  static bool supports_cpuid()    { return _cpuFeatures  != 0; }
-  static bool supports_cmpxchg8() { return (_cpuFeatures & CPU_CX8) != 0; }
-  static bool supports_cmov()     { return (_cpuFeatures & CPU_CMOV) != 0; }
-  static bool supports_fxsr()     { return (_cpuFeatures & CPU_FXSR) != 0; }
-  static bool supports_ht()       { return (_cpuFeatures & CPU_HT) != 0; }
-  static bool supports_mmx()      { return (_cpuFeatures & CPU_MMX) != 0; }
-  static bool supports_sse()      { return (_cpuFeatures & CPU_SSE) != 0; }
-  static bool supports_sse2()     { return (_cpuFeatures & CPU_SSE2) != 0; }
-  static bool supports_sse3()     { return (_cpuFeatures & CPU_SSE3) != 0; }
-  static bool supports_ssse3()    { return (_cpuFeatures & CPU_SSSE3)!= 0; }
-  static bool supports_sse4_1()   { return (_cpuFeatures & CPU_SSE4_1) != 0; }
-  static bool supports_sse4_2()   { return (_cpuFeatures & CPU_SSE4_2) != 0; }
-  //
-  // AMD features
-  //
-  static bool supports_3dnow()    { return (_cpuFeatures & CPU_3DNOW) != 0; }
-  static bool supports_mmx_ext()  { return is_amd() && _cpuid_info.ext_cpuid1_edx.bits.mmx_amd != 0; }
-  static bool supports_3dnow2()   { return is_amd() && _cpuid_info.ext_cpuid1_edx.bits.tdnow2 != 0; }
-  static bool supports_sse4a()    { return (_cpuFeatures & CPU_SSE4A) != 0; }
-
-  static bool supports_compare_and_exchange() { return true; }
-
-  static const char* cpu_features()           { return _features_str; }
-
-  static intx allocate_prefetch_distance() {
-    // This method should be called before allocate_prefetch_style().
-    //
-    // Hardware prefetching (distance/size in bytes):
-    // Pentium 4 - 256 / 128
-    // Opteron   - 128 /  64 only when 2 sequential cache lines accessed
-    // Core      - 128 /  64
-    //
-    // Software prefetching (distance in bytes / instruction with best score):
-    // Pentium 4 - 512 / prefetchnta
-    // Opteron   - 256 / prefetchnta
-    // Core      - 256 / prefetchnta
-    // It will be used only when AllocatePrefetchStyle > 0
-
-    intx count = AllocatePrefetchDistance;
-    if (count < 0) {  // default ?
-      if (is_amd()) { // AMD
-        count = 256;  // Opteron
-      } else {        // Intel
-        if (cpu_family() == 6) {
-          count = 256;// Pentium M, Core, Core2
-        } else {
-          count = 512;// Pentium 4
-        }
-      }
-    }
-    return count;
-  }
-  static intx allocate_prefetch_style() {
-    assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
-    // Return 0 if AllocatePrefetchDistance was not defined.
-    return AllocatePrefetchDistance > 0 ? AllocatePrefetchStyle : 0;
-  }
-
-  // Prefetch interval for gc copy/scan == 9 dcache lines.  Derived from
-  // 50-warehouse specjbb runs on a 2-way 1.8ghz opteron using a 4gb heap.
-  // Tested intervals from 128 to 2048 in increments of 64 == one cache line.
-  // 256 bytes (4 dcache lines) was the nearest runner-up to 576.
-
-  // gc copy/scan is disabled if prefetchw isn't supported, because
-  // Prefetch::write emits an inlined prefetchw on Linux.
-  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
-  // The used prefetcht0 instruction works for both amd64 and em64t.
-  static intx prefetch_copy_interval_in_bytes() {
-    intx interval = PrefetchCopyIntervalInBytes;
-    return interval >= 0 ? interval : 576;
-  }
-  static intx prefetch_scan_interval_in_bytes() {
-    intx interval = PrefetchScanIntervalInBytes;
-    return interval >= 0 ? interval : 576;
-  }
-  static intx prefetch_fields_ahead() {
-    intx count = PrefetchFieldsAhead;
-    return count >= 0 ? count : 1;
-  }
-};
--- a/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -34,10 +34,16 @@
 extern "C" void bad_compiled_vtable_index(JavaThread* thread, oop receiver, int index);
 #endif
 
-// used by compiler only; may use only caller saved registers rax, rbx, rcx.
-// rdx holds first int arg, rsi, rdi, rbp are callee-save & must be preserved.
-// Leave receiver in rcx; required behavior when +OptoArgsInRegisters
-// is modifed to put first oop in rcx.
+// These stubs are used by the compiler only.
+// Argument registers, which must be preserved:
+//   rcx - receiver (always first argument)
+//   rdx - second argument (if any)
+// Other registers that might be usable:
+//   rax - inline cache register (is interface for itable stub)
+//   rbx - method (used when calling out to interpreter)
+// Available now, but may become callee-save at some point:
+//   rsi, rdi
+// Note that rax and rdx are also used for return values.
 //
 VtableStub* VtableStubs::create_vtable_stub(int vtable_index) {
   const int i486_code_length = VtableStub::pd_code_size_limit(true);
@@ -94,16 +100,25 @@
   __ jmp( Address(method, methodOopDesc::from_compiled_offset()));
 
   masm->flush();
+
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  vtable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
+  guarantee(__ pc() <= s->code_end(), "overflowed buffer");
+
   s->set_exception_points(npe_addr, ame_addr);
   return s;
 }
 
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   // Note well: pd_code_size_limit is the absolute minimum we can get away with.  If you
   //            add code here, bump the code stub size returned by pd_code_size_limit!
   const int i486_code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new(i486_code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new(i486_code_length) VtableStub(false, itable_index);
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), i486_code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -123,50 +138,19 @@
 
   // get receiver klass (also an implicit null-check)
   address npe_addr = __ pc();
-  __ movptr(rbx, Address(rcx, oopDesc::klass_offset_in_bytes()));
-
-  __ mov(rsi, rbx);   // Save klass in free register
-  // Most registers are in use, so save a few
-  __ push(rdx);
-  // compute itable entry offset (in words)
-  const int base = instanceKlass::vtable_start_offset() * wordSize;
-  assert(vtableEntry::size() * wordSize == 4, "adjust the scaling in the code below");
-  __ movl(rdx, Address(rbx, instanceKlass::vtable_length_offset() * wordSize)); // Get length of vtable
-  __ lea(rbx, Address(rbx, rdx, Address::times_ptr, base));
-  if (HeapWordsPerLong > 1) {
-    // Round up to align_object_offset boundary
-    __ round_to(rbx, BytesPerLong);
-  }
-
-  Label hit, next, entry, throw_icce;
-
-  __ jmpb(entry);
+  __ movptr(rsi, Address(rcx, oopDesc::klass_offset_in_bytes()));
 
-  __ bind(next);
-  __ addptr(rbx, itableOffsetEntry::size() * wordSize);
-
-  __ bind(entry);
-
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception
-  __ movptr(rdx, Address(rbx, itableOffsetEntry::interface_offset_in_bytes()));
-  __ testptr(rdx, rdx);
-  __ jcc(Assembler::zero, throw_icce);
-  __ cmpptr(rax, rdx);
-  __ jcc(Assembler::notEqual, next);
-
-  // We found a hit, move offset into rbx,
-  __ movl(rdx, Address(rbx, itableOffsetEntry::offset_offset_in_bytes()));
-
-  // Compute itableMethodEntry.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) + itableMethodEntry::method_offset_in_bytes();
+  // Most registers are in use; we'll use rax, rbx, rsi, rdi
+  // (If we need to make rsi, rdi callee-save, do a push/pop here.)
+  const Register method = rbx;
+  Label throw_icce;
 
   // Get methodOop and entrypoint for compiler
-  const Register method = rbx;
-  __ movptr(method, Address(rsi, rdx, Address::times_1, method_offset));
-
-  // Restore saved register, before possible trap.
-  __ pop(rdx);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rsi, rax, itable_index,
+                             // outputs: method, scan temp. reg
+                             method, rdi,
+                             throw_icce);
 
   // method (rbx): methodOop
   // rcx: receiver
@@ -187,12 +171,15 @@
   __ jmp(Address(method, methodOopDesc::from_compiled_offset()));
 
   __ bind(throw_icce);
-  // Restore saved register
-  __ pop(rdx);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
-
   masm->flush();
 
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  itable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
 
   s->set_exception_points(npe_addr, ame_addr);
@@ -207,7 +194,7 @@
     return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 144 : 64) + (CountCompiledCalls ? 6 : 0);
+    return (DebugVtables ? 256 : 66) + (CountCompiledCalls ? 6 : 0);
   }
 }
 
--- a/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -98,17 +98,26 @@
   __ jmp( Address(rbx, methodOopDesc::from_compiled_offset()));
 
   __ flush();
+
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  vtable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
+  guarantee(__ pc() <= s->code_end(), "overflowed buffer");
+
   s->set_exception_points(npe_addr, ame_addr);
   return s;
 }
 
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   // Note well: pd_code_size_limit is the absolute minimum we can get
   // away with.  If you add code here, bump the code stub size
   // returned by pd_code_size_limit!
   const int amd64_code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new(amd64_code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new(amd64_code_length) VtableStub(false, itable_index);
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), amd64_code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -131,68 +140,28 @@
   // get receiver klass (also an implicit null-check)
   address npe_addr = __ pc();
 
-  __ load_klass(rbx, j_rarg0);
+  // Most registers are in use; we'll use rax, rbx, r10, r11
+  // (various calling sequences use r[cd]x, r[sd]i, r[89]; stay away from them)
+  __ load_klass(r10, j_rarg0);
 
   // If we take a trap while this arg is on the stack we will not
   // be able to walk the stack properly. This is not an issue except
   // when there are mistakes in this assembly code that could generate
   // a spurious fault. Ask me how I know...
 
-  __ push(j_rarg1);     // Most registers are in use, so save one
-
-  // compute itable entry offset (in words)
-  const int base = instanceKlass::vtable_start_offset() * wordSize;
-  assert(vtableEntry::size() * wordSize == 8,
-         "adjust the scaling in the code below");
-  // Get length of vtable
-  __ movl(j_rarg1,
-          Address(rbx, instanceKlass::vtable_length_offset() * wordSize));
-  __ lea(rbx, Address(rbx, j_rarg1, Address::times_8, base));
-
-  if (HeapWordsPerLong > 1) {
-    // Round up to align_object_offset boundary
-    __ round_to(rbx, BytesPerLong);
-  }
-  Label hit, next, entry, throw_icce;
-
-  __ jmpb(entry);
-
-  __ bind(next);
-  __ addptr(rbx, itableOffsetEntry::size() * wordSize);
-
-  __ bind(entry);
-
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception
-  __ movptr(j_rarg1, Address(rbx, itableOffsetEntry::interface_offset_in_bytes()));
-  __ testptr(j_rarg1, j_rarg1);
-  __ jcc(Assembler::zero, throw_icce);
-  __ cmpptr(rax, j_rarg1);
-  __ jccb(Assembler::notEqual, next);
-
-  // We found a hit, move offset into j_rarg1
-  __ movl(j_rarg1, Address(rbx, itableOffsetEntry::offset_offset_in_bytes()));
-
-  // Compute itableMethodEntry
-  const int method_offset =
-    (itableMethodEntry::size() * wordSize * vtable_index) +
-    itableMethodEntry::method_offset_in_bytes();
+  const Register method = rbx;
+  Label throw_icce;
 
   // Get methodOop and entrypoint for compiler
-
-  // Get klass pointer again
-  __ load_klass(rax, j_rarg0);
-
-  const Register method = rbx;
-  __ movptr(method, Address(rax, j_rarg1, Address::times_1, method_offset));
-
-  // Restore saved register, before possible trap.
-  __ pop(j_rarg1);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             r10, rax, itable_index,
+                             // outputs: method, scan temp. reg
+                             method, r11,
+                             throw_icce);
 
   // method (rbx): methodOop
   // j_rarg0: receiver
 
-
 #ifdef ASSERT
   if (DebugVtables) {
     Label L2;
@@ -211,12 +180,16 @@
   __ jmp(Address(method, methodOopDesc::from_compiled_offset()));
 
   __ bind(throw_icce);
-  // Restore saved register
-  __ pop(j_rarg1);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
 
   __ flush();
 
+  if (PrintMiscellaneous && (WizardMode || Verbose)) {
+    tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
+                  itable_index, s->entry_point(),
+                  (int)(s->code_end() - s->entry_point()),
+                  (int)(s->code_end() - __ pc()));
+  }
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
 
   s->set_exception_points(npe_addr, ame_addr);
@@ -230,7 +203,7 @@
            (UseCompressedOops ? 16 : 0);  // 1 leaq can be 3 bytes + 1 long
   } else {
     // Itable stub size
-    return (DebugVtables ? 636 : 72) + (CountCompiledCalls ? 13 : 0) +
+    return (DebugVtables ? 512 : 72) + (CountCompiledCalls ? 13 : 0) +
            (UseCompressedOops ? 32 : 0);  // 2 leaqs
   }
 }
--- a/hotspot/src/cpu/x86/vm/x86_32.ad	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/x86_32.ad	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -130,7 +130,7 @@
 // allocation.  Highest priority is first.  A useful heuristic is to
 // give registers a low priority when they are required by machine
 // instructions, like EAX and EDX.  Registers which are used as
-// pairs must fall on an even boundry (witness the FPR#L's in this list).
+// pairs must fall on an even boundary (witness the FPR#L's in this list).
 // For the Intel integer registers, the equivalent Long pairs are
 // EDX:EAX, EBX:ECX, and EDI:EBP.
 alloc_class chunk0( ECX,   EBX,   EBP,   EDI,   EAX,   EDX,   ESI, ESP,
@@ -1483,16 +1483,20 @@
   // main source block for now.  In future, we can generalize this by
   // adding a syntax that specifies the sizes of fields in an order,
   // so that the adlc can build the emit functions automagically
-  enc_class OpcP %{             // Emit opcode
-    emit_opcode(cbuf,$primary);
-  %}
-
-  enc_class OpcS %{             // Emit opcode
-    emit_opcode(cbuf,$secondary);
-  %}
-
-  enc_class Opcode(immI d8 ) %{ // Emit opcode
-    emit_opcode(cbuf,$d8$$constant);
+
+  // Emit primary opcode
+  enc_class OpcP %{
+    emit_opcode(cbuf, $primary);
+  %}
+
+  // Emit secondary opcode
+  enc_class OpcS %{
+    emit_opcode(cbuf, $secondary);
+  %}
+
+  // Emit opcode directly
+  enc_class Opcode(immI d8) %{
+    emit_opcode(cbuf, $d8$$constant);
   %}
 
   enc_class SizePrefix %{
@@ -1688,26 +1692,15 @@
     Register Reax = as_Register(EAX_enc); // super class
     Register Recx = as_Register(ECX_enc); // killed
     Register Resi = as_Register(ESI_enc); // sub class
-    Label hit, miss;
+    Label miss;
 
     MacroAssembler _masm(&cbuf);
-    // Compare super with sub directly, since super is not in its own SSA.
-    // The compiler used to emit this test, but we fold it in here,
-    // to allow platform-specific tweaking on sparc.
-    __ cmpptr(Reax, Resi);
-    __ jcc(Assembler::equal, hit);
-#ifndef PRODUCT
-    __ incrementl(ExternalAddress((address)&SharedRuntime::_partial_subtype_ctr));
-#endif //PRODUCT
-    __ movptr(Redi,Address(Resi,sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes()));
-    __ movl(Recx,Address(Redi,arrayOopDesc::length_offset_in_bytes()));
-    __ addptr(Redi,arrayOopDesc::base_offset_in_bytes(T_OBJECT));
-    __ repne_scan();
-    __ jcc(Assembler::notEqual, miss);
-    __ movptr(Address(Resi,sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes()),Reax);
-    __ bind(hit);
-    if( $primary )
-      __ xorptr(Redi,Redi);
+    __ check_klass_subtype_slow_path(Resi, Reax, Recx, Redi,
+                                     NULL, &miss,
+                                     /*set_cond_codes:*/ true);
+    if ($primary) {
+      __ xorptr(Redi, Redi);
+    }
     __ bind(miss);
   %}
 
@@ -3126,14 +3119,12 @@
 
   enc_class movq_ld(regXD dst, memory mem) %{
     MacroAssembler _masm(&cbuf);
-    Address madr = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ movq(as_XMMRegister($dst$$reg), madr);
+    __ movq($dst$$XMMRegister, $mem$$Address);
   %}
 
   enc_class movq_st(memory mem, regXD src) %{
     MacroAssembler _masm(&cbuf);
-    Address madr = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ movq(madr, as_XMMRegister($src$$reg));
+    __ movq($mem$$Address, $src$$XMMRegister);
   %}
 
   enc_class pshufd_8x8(regX dst, regX src) %{
@@ -3703,12 +3694,16 @@
     }
   %}
 
-  enc_class enc_String_Compare() %{
+  enc_class enc_String_Compare(eDIRegP str1, eSIRegP str2, regXD tmp1, regXD tmp2,
+                        eAXRegI tmp3, eBXRegI tmp4, eCXRegI result) %{
     Label ECX_GOOD_LABEL, LENGTH_DIFF_LABEL,
           POP_LABEL, DONE_LABEL, CONT_LABEL,
           WHILE_HEAD_LABEL;
     MacroAssembler masm(&cbuf);
 
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+
     // Get the first character position in both strings
     //         [8] char array, [12] offset, [16] count
     int value_offset  = java_lang_String::value_offset_in_bytes();
@@ -3726,7 +3721,6 @@
     // Compute the minimum of the string lengths(rsi) and the
     // difference of the string lengths (stack)
 
-
     if (VM_Version::supports_cmov()) {
       masm.movl(rdi, Address(rdi, count_offset));
       masm.movl(rsi, Address(rsi, count_offset));
@@ -3740,7 +3734,7 @@
       masm.movl(rsi, rdi);
       masm.subl(rdi, rcx);
       masm.push(rdi);
-      masm.jcc(Assembler::lessEqual, ECX_GOOD_LABEL);
+      masm.jccb(Assembler::lessEqual, ECX_GOOD_LABEL);
       masm.movl(rsi, rcx);
       // rsi holds min, rcx is unused
     }
@@ -3751,8 +3745,8 @@
     masm.jcc(Assembler::zero, LENGTH_DIFF_LABEL);
 
     // Load first characters
-    masm.load_unsigned_word(rcx, Address(rbx, 0));
-    masm.load_unsigned_word(rdi, Address(rax, 0));
+    masm.load_unsigned_short(rcx, Address(rbx, 0));
+    masm.load_unsigned_short(rdi, Address(rax, 0));
 
     // Compare first characters
     masm.subl(rcx, rdi);
@@ -3765,7 +3759,7 @@
       Label LSkip2;
       // Check if the strings start at same location
       masm.cmpptr(rbx,rax);
-      masm.jcc(Assembler::notEqual, LSkip2);
+      masm.jccb(Assembler::notEqual, LSkip2);
 
       // Check if the length difference is zero (from stack)
       masm.cmpl(Address(rsp, 0), 0x0);
@@ -3775,103 +3769,382 @@
       masm.bind(LSkip2);
     }
 
-    // Shift rax, and rbx, to the end of the arrays, negate min
-    masm.lea(rax, Address(rax, rsi, Address::times_2, 2));
-    masm.lea(rbx, Address(rbx, rsi, Address::times_2, 2));
+   // Advance to next character
+    masm.addptr(rax, 2);
+    masm.addptr(rbx, 2);
+
+    if (UseSSE42Intrinsics) {
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
+      // Setup to compare 16-byte vectors
+      masm.movl(rdi, rsi);
+      masm.andl(rsi, 0xfffffff8); // rsi holds the vector count
+      masm.andl(rdi, 0x00000007); // rdi holds the tail count
+      masm.testl(rsi, rsi);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+
+      masm.lea(rax, Address(rax, rsi, Address::times_2));
+      masm.lea(rbx, Address(rbx, rsi, Address::times_2));
+      masm.negl(rsi);
+
+      masm.bind(COMPARE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(rax, rsi, Address::times_2));
+      masm.movdqu(tmp2Reg, Address(rbx, rsi, Address::times_2));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+      masm.jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
+      masm.addl(rsi, 8);
+      masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+      masm.jmpb(COMPARE_TAIL);
+
+      // Mismatched characters in the vectors
+      masm.bind(VECTOR_NOT_EQUAL);
+      masm.lea(rax, Address(rax, rsi, Address::times_2));
+      masm.lea(rbx, Address(rbx, rsi, Address::times_2));
+      masm.movl(rdi, 8);
+
+      // Compare tail (< 8 chars), or rescan last vectors to
+      // find 1st mismatched characters
+      masm.bind(COMPARE_TAIL);
+      masm.testl(rdi, rdi);
+      masm.jccb(Assembler::zero, LENGTH_DIFF_LABEL);
+      masm.movl(rsi, rdi);
+      // Fallthru to tail compare
+    }
+
+    //Shift rax, and rbx, to the end of the arrays, negate min
+    masm.lea(rax, Address(rax, rsi, Address::times_2, 0));
+    masm.lea(rbx, Address(rbx, rsi, Address::times_2, 0));
     masm.negl(rsi);
 
     // Compare the rest of the characters
     masm.bind(WHILE_HEAD_LABEL);
-    masm.load_unsigned_word(rcx, Address(rbx, rsi, Address::times_2, 0));
-    masm.load_unsigned_word(rdi, Address(rax, rsi, Address::times_2, 0));
+    masm.load_unsigned_short(rcx, Address(rbx, rsi, Address::times_2, 0));
+    masm.load_unsigned_short(rdi, Address(rax, rsi, Address::times_2, 0));
     masm.subl(rcx, rdi);
-    masm.jcc(Assembler::notZero, POP_LABEL);
+    masm.jccb(Assembler::notZero, POP_LABEL);
     masm.incrementl(rsi);
     masm.jcc(Assembler::notZero, WHILE_HEAD_LABEL);
 
     // Strings are equal up to min length.  Return the length difference.
     masm.bind(LENGTH_DIFF_LABEL);
     masm.pop(rcx);
-    masm.jmp(DONE_LABEL);
+    masm.jmpb(DONE_LABEL);
 
     // Discard the stored length difference
     masm.bind(POP_LABEL);
     masm.addptr(rsp, 4);
-       
+
     // That's it
     masm.bind(DONE_LABEL);
   %}
 
-  enc_class enc_Array_Equals(eDIRegP ary1, eSIRegP ary2, eAXRegI tmp1, eBXRegI tmp2, eCXRegI result) %{
-    Label TRUE_LABEL, FALSE_LABEL, DONE_LABEL, COMPARE_LOOP_HDR, COMPARE_LOOP;
+ enc_class enc_String_Equals(eDIRegP str1, eSIRegP str2, regXD tmp1, regXD tmp2,
+                       eBXRegI tmp3, eCXRegI tmp4, eAXRegI result) %{
+    Label RET_TRUE, RET_FALSE, DONE, COMPARE_VECTORS, COMPARE_CHAR;
+    MacroAssembler masm(&cbuf);
+
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+
+    int value_offset  = java_lang_String::value_offset_in_bytes();
+    int offset_offset = java_lang_String::offset_offset_in_bytes();
+    int count_offset  = java_lang_String::count_offset_in_bytes();
+    int base_offset   = arrayOopDesc::base_offset_in_bytes(T_CHAR);
+
+    // does source == target string?
+    masm.cmpptr(rdi, rsi);
+    masm.jcc(Assembler::equal, RET_TRUE);
+
+    // get and compare counts
+    masm.movl(rcx, Address(rdi, count_offset));
+    masm.movl(rax, Address(rsi, count_offset));
+    masm.cmpl(rcx, rax);
+    masm.jcc(Assembler::notEqual, RET_FALSE);
+    masm.testl(rax, rax);
+    masm.jcc(Assembler::zero, RET_TRUE);
+
+    // get source string offset and value
+    masm.movptr(rbx, Address(rsi, value_offset));
+    masm.movl(rax, Address(rsi, offset_offset));
+    masm.leal(rsi, Address(rbx, rax, Address::times_2, base_offset));
+
+    // get compare string offset and value
+    masm.movptr(rbx, Address(rdi, value_offset));
+    masm.movl(rax, Address(rdi, offset_offset));
+    masm.leal(rdi, Address(rbx, rax, Address::times_2, base_offset));
+
+    // Set byte count
+    masm.shll(rcx, 1);
+    masm.movl(rax, rcx);
+
+    if (UseSSE42Intrinsics) {
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
+      // Compare 16-byte vectors
+      masm.andl(rcx, 0xfffffff0);  // vector count (in bytes)
+      masm.andl(rax, 0x0000000e);  // tail count (in bytes)
+      masm.testl(rcx, rcx);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+      masm.lea(rdi, Address(rdi, rcx, Address::times_1));
+      masm.lea(rsi, Address(rsi, rcx, Address::times_1));
+      masm.negl(rcx);
+
+      masm.bind(COMPARE_WIDE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(rdi, rcx, Address::times_1));
+      masm.movdqu(tmp2Reg, Address(rsi, rcx, Address::times_1));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+      masm.jccb(Assembler::notZero, RET_FALSE);
+      masm.addl(rcx, 16);
+      masm.jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
+      masm.bind(COMPARE_TAIL);
+      masm.movl(rcx, rax);
+      // Fallthru to tail compare
+    }
+
+    // Compare 4-byte vectors
+    masm.andl(rcx, 0xfffffffc);  // vector count (in bytes)
+    masm.andl(rax, 0x00000002);  // tail char (in bytes)
+    masm.testl(rcx, rcx);
+    masm.jccb(Assembler::zero, COMPARE_CHAR);
+    masm.lea(rdi, Address(rdi, rcx, Address::times_1));
+    masm.lea(rsi, Address(rsi, rcx, Address::times_1));
+    masm.negl(rcx);
+
+    masm.bind(COMPARE_VECTORS);
+    masm.movl(rbx, Address(rdi, rcx, Address::times_1));
+    masm.cmpl(rbx, Address(rsi, rcx, Address::times_1));
+    masm.jccb(Assembler::notEqual, RET_FALSE);
+    masm.addl(rcx, 4);
+    masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+
+    // Compare trailing char (final 2 bytes), if any
+    masm.bind(COMPARE_CHAR);
+    masm.testl(rax, rax);
+    masm.jccb(Assembler::zero, RET_TRUE);
+    masm.load_unsigned_short(rbx, Address(rdi, 0));
+    masm.load_unsigned_short(rcx, Address(rsi, 0));
+    masm.cmpl(rbx, rcx);
+    masm.jccb(Assembler::notEqual, RET_FALSE);
+
+    masm.bind(RET_TRUE);
+    masm.movl(rax, 1);   // return true
+    masm.jmpb(DONE);
+
+    masm.bind(RET_FALSE);
+    masm.xorl(rax, rax); // return false
+
+    masm.bind(DONE);
+    %}
+
+ enc_class enc_String_IndexOf(eSIRegP str1, eDIRegP str2, regXD tmp1, eAXRegI tmp2,
+                        eCXRegI tmp3, eDXRegI tmp4, eBXRegI result) %{
+    // SSE4.2 version
+    Label LOAD_SUBSTR, PREP_FOR_SCAN, SCAN_TO_SUBSTR,
+          SCAN_SUBSTR, RET_NEG_ONE, RET_NOT_FOUND, CLEANUP, DONE;
     MacroAssembler masm(&cbuf);
 
-    Register ary1Reg   = as_Register($ary1$$reg);
-    Register ary2Reg   = as_Register($ary2$$reg);
-    Register tmp1Reg   = as_Register($tmp1$$reg);
-    Register tmp2Reg   = as_Register($tmp2$$reg);
-    Register resultReg = as_Register($result$$reg);
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+
+    // Get the first character position in both strings
+    //         [8] char array, [12] offset, [16] count
+    int value_offset  = java_lang_String::value_offset_in_bytes();
+    int offset_offset = java_lang_String::offset_offset_in_bytes();
+    int count_offset  = java_lang_String::count_offset_in_bytes();
+    int base_offset   = arrayOopDesc::base_offset_in_bytes(T_CHAR);
+
+    // Get counts for string and substr
+    masm.movl(rdx, Address(rsi, count_offset));
+    masm.movl(rax, Address(rdi, count_offset));
+    // Check for substr count > string count
+    masm.cmpl(rax, rdx);
+    masm.jcc(Assembler::greater, RET_NEG_ONE);
+
+    // Start the indexOf operation
+    // Get start addr of string
+    masm.movptr(rbx, Address(rsi, value_offset));
+    masm.movl(rcx, Address(rsi, offset_offset));
+    masm.lea(rsi, Address(rbx, rcx, Address::times_2, base_offset));
+    masm.push(rsi);
+
+    // Get start addr of substr
+    masm.movptr(rbx, Address(rdi, value_offset));
+    masm.movl(rcx, Address(rdi, offset_offset));
+    masm.lea(rdi, Address(rbx, rcx, Address::times_2, base_offset));
+    masm.push(rdi);
+    masm.push(rax);
+    masm.jmpb(PREP_FOR_SCAN);
+
+    // Substr count saved at sp
+    // Substr saved at sp+4
+    // String saved at sp+8
+
+    // Prep to load substr for scan
+    masm.bind(LOAD_SUBSTR);
+    masm.movptr(rdi, Address(rsp, 4));
+    masm.movl(rax, Address(rsp, 0));
+
+    // Load substr
+    masm.bind(PREP_FOR_SCAN);
+    masm.movdqu(tmp1Reg, Address(rdi, 0));
+    masm.addl(rdx, 8);        // prime the loop
+    masm.subptr(rsi, 16);
+
+    // Scan string for substr in 16-byte vectors
+    masm.bind(SCAN_TO_SUBSTR);
+    masm.subl(rdx, 8);
+    masm.addptr(rsi, 16);
+    masm.pcmpestri(tmp1Reg, Address(rsi, 0), 0x0d);
+    masm.jcc(Assembler::above, SCAN_TO_SUBSTR);     // CF == 0 && ZF == 0
+    masm.jccb(Assembler::aboveEqual, RET_NOT_FOUND); // CF == 0
+
+    // Fallthru: found a potential substr
+
+    // Make sure string is still long enough
+    masm.subl(rdx, rcx);
+    masm.cmpl(rdx, rax);
+    masm.jccb(Assembler::negative, RET_NOT_FOUND);
+    // Compute start addr of substr
+    masm.lea(rsi, Address(rsi, rcx, Address::times_2));
+    masm.movptr(rbx, rsi);
+
+    // Compare potential substr
+    masm.addl(rdx, 8);        // prime the loop
+    masm.addl(rax, 8);
+    masm.subptr(rsi, 16);
+    masm.subptr(rdi, 16);
+
+    // Scan 16-byte vectors of string and substr
+    masm.bind(SCAN_SUBSTR);
+    masm.subl(rax, 8);
+    masm.subl(rdx, 8);
+    masm.addptr(rsi, 16);
+    masm.addptr(rdi, 16);
+    masm.movdqu(tmp1Reg, Address(rdi, 0));
+    masm.pcmpestri(tmp1Reg, Address(rsi, 0), 0x0d);
+    masm.jcc(Assembler::noOverflow, LOAD_SUBSTR);   // OF == 0
+    masm.jcc(Assembler::positive, SCAN_SUBSTR);     // SF == 0
+
+    // Compute substr offset
+    masm.movptr(rsi, Address(rsp, 8));
+    masm.subptr(rbx, rsi);
+    masm.shrl(rbx, 1);
+    masm.jmpb(CLEANUP);
+
+    masm.bind(RET_NEG_ONE);
+    masm.movl(rbx, -1);
+    masm.jmpb(DONE);
+
+    masm.bind(RET_NOT_FOUND);
+    masm.movl(rbx, -1);
+
+    masm.bind(CLEANUP);
+    masm.addptr(rsp, 12);
+
+    masm.bind(DONE);
+  %}
+
+  enc_class enc_Array_Equals(eDIRegP ary1, eSIRegP ary2, regXD tmp1, regXD tmp2,
+                             eBXRegI tmp3, eDXRegI tmp4, eAXRegI result) %{
+    Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR;
+    MacroAssembler masm(&cbuf);
+
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+    Register ary1Reg      = as_Register($ary1$$reg);
+    Register ary2Reg      = as_Register($ary2$$reg);
+    Register tmp3Reg      = as_Register($tmp3$$reg);
+    Register tmp4Reg      = as_Register($tmp4$$reg);
+    Register resultReg    = as_Register($result$$reg);
 
     int length_offset  = arrayOopDesc::length_offset_in_bytes();
     int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
 
     // Check the input args
-    masm.cmpl(ary1Reg, ary2Reg);
+    masm.cmpptr(ary1Reg, ary2Reg);
     masm.jcc(Assembler::equal, TRUE_LABEL);
-    masm.testl(ary1Reg, ary1Reg);
+    masm.testptr(ary1Reg, ary1Reg);
     masm.jcc(Assembler::zero, FALSE_LABEL);
-    masm.testl(ary2Reg, ary2Reg);
+    masm.testptr(ary2Reg, ary2Reg);
     masm.jcc(Assembler::zero, FALSE_LABEL);
 
     // Check the lengths
-    masm.movl(tmp2Reg, Address(ary1Reg, length_offset));
+    masm.movl(tmp4Reg, Address(ary1Reg, length_offset));
     masm.movl(resultReg, Address(ary2Reg, length_offset));
-    masm.cmpl(tmp2Reg, resultReg);
+    masm.cmpl(tmp4Reg, resultReg);
     masm.jcc(Assembler::notEqual, FALSE_LABEL);
     masm.testl(resultReg, resultReg);
     masm.jcc(Assembler::zero, TRUE_LABEL);
 
-    // Get the number of 4 byte vectors to compare
-    masm.shrl(resultReg, 1);
-
-    // Check for odd-length arrays
-    masm.andl(tmp2Reg, 1);
-    masm.testl(tmp2Reg, tmp2Reg);
-    masm.jcc(Assembler::zero, COMPARE_LOOP_HDR);
-
-    // Compare 2-byte "tail" at end of arrays
-    masm.load_unsigned_word(tmp1Reg, Address(ary1Reg, resultReg, Address::times_4, base_offset));
-    masm.load_unsigned_word(tmp2Reg, Address(ary2Reg, resultReg, Address::times_4, base_offset));
-    masm.cmpl(tmp1Reg, tmp2Reg);
-    masm.jcc(Assembler::notEqual, FALSE_LABEL);
+    // Load array addrs
+    masm.lea(ary1Reg, Address(ary1Reg, base_offset));
+    masm.lea(ary2Reg, Address(ary2Reg, base_offset));
+
+    // Set byte count
+    masm.shll(tmp4Reg, 1);
+    masm.movl(resultReg, tmp4Reg);
+
+    if (UseSSE42Intrinsics) {
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
+      // Compare 16-byte vectors
+      masm.andl(tmp4Reg, 0xfffffff0);    // vector count (in bytes)
+      masm.andl(resultReg, 0x0000000e);  // tail count (in bytes)
+      masm.testl(tmp4Reg, tmp4Reg);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+      masm.lea(ary1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+      masm.lea(ary2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+      masm.negl(tmp4Reg);
+
+      masm.bind(COMPARE_WIDE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+      masm.movdqu(tmp2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+
+      masm.jccb(Assembler::notZero, FALSE_LABEL);
+      masm.addl(tmp4Reg, 16);
+      masm.jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
+      masm.bind(COMPARE_TAIL);
+      masm.movl(tmp4Reg, resultReg);
+      // Fallthru to tail compare
+    }
+
+    // Compare 4-byte vectors
+    masm.andl(tmp4Reg, 0xfffffffc);    // vector count (in bytes)
+    masm.andl(resultReg, 0x00000002);  // tail char (in bytes)
+    masm.testl(tmp4Reg, tmp4Reg);
+    masm.jccb(Assembler::zero, COMPARE_CHAR);
+    masm.lea(ary1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+    masm.lea(ary2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+    masm.negl(tmp4Reg);
+
+    masm.bind(COMPARE_VECTORS);
+    masm.movl(tmp3Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+    masm.cmpl(tmp3Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+    masm.jccb(Assembler::notEqual, FALSE_LABEL);
+    masm.addl(tmp4Reg, 4);
+    masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+
+    // Compare trailing char (final 2 bytes), if any
+    masm.bind(COMPARE_CHAR);
     masm.testl(resultReg, resultReg);
-    masm.jcc(Assembler::zero, TRUE_LABEL);
-
-    // Setup compare loop
-    masm.bind(COMPARE_LOOP_HDR);
-    // Shift tmp1Reg and tmp2Reg to the last 4-byte boundary of the arrays
-    masm.leal(tmp1Reg, Address(ary1Reg, resultReg, Address::times_4, base_offset));
-    masm.leal(tmp2Reg, Address(ary2Reg, resultReg, Address::times_4, base_offset));
-    masm.negl(resultReg);
-
-    // 4-byte-wide compare loop
-    masm.bind(COMPARE_LOOP);
-    masm.movl(ary1Reg, Address(tmp1Reg, resultReg, Address::times_4, 0));
-    masm.movl(ary2Reg, Address(tmp2Reg, resultReg, Address::times_4, 0));
-    masm.cmpl(ary1Reg, ary2Reg);
-    masm.jcc(Assembler::notEqual, FALSE_LABEL);
-    masm.increment(resultReg);
-    masm.jcc(Assembler::notZero, COMPARE_LOOP);
+    masm.jccb(Assembler::zero, TRUE_LABEL);
+    masm.load_unsigned_short(tmp3Reg, Address(ary1Reg, 0));
+    masm.load_unsigned_short(tmp4Reg, Address(ary2Reg, 0));
+    masm.cmpl(tmp3Reg, tmp4Reg);
+    masm.jccb(Assembler::notEqual, FALSE_LABEL);
 
     masm.bind(TRUE_LABEL);
     masm.movl(resultReg, 1);   // return true
-    masm.jmp(DONE_LABEL);
+    masm.jmpb(DONE);
 
     masm.bind(FALSE_LABEL);
     masm.xorl(resultReg, resultReg); // return false
 
     // That's it
-    masm.bind(DONE_LABEL);
+    masm.bind(DONE);
   %}
 
   enc_class enc_pop_rdx() %{
@@ -4297,24 +4570,6 @@
     emit_opcode(cbuf, 0xC8 + $src2$$reg);
   %}
 
-  enc_class enc_membar_acquire %{
-    // Doug Lea believes this is not needed with current Sparcs and TSO.
-    // MacroAssembler masm(&cbuf);
-    // masm.membar();
-  %}
-
-  enc_class enc_membar_release %{
-    // Doug Lea believes this is not needed with current Sparcs and TSO.
-    // MacroAssembler masm(&cbuf);
-    // masm.membar();
-  %}
-
-  enc_class enc_membar_volatile %{
-    MacroAssembler masm(&cbuf);
-    masm.membar(Assembler::Membar_mask_bits(Assembler::StoreLoad |
-                                            Assembler::StoreStore));
-  %}
-
   // Atomically load the volatile long
   enc_class enc_loadL_volatile( memory mem, stackSlotL dst ) %{
     emit_opcode(cbuf,0xDF);
@@ -5857,7 +6112,7 @@
 
 //----------OPERAND CLASSES----------------------------------------------------
 // Operand Classes are groups of operands that are used as to simplify
-// instruction definitions by not requiring the AD writer to specify seperate
+// instruction definitions by not requiring the AD writer to specify separate
 // instructions for every form of operand when the instruction accepts
 // multiple operand types with the same basic encoding and format.  The classic
 // case of this is memory operands.
@@ -6389,6 +6644,67 @@
 %}
 
 
+//---------- Population Count Instructions -------------------------------------
+
+instruct popCountI(eRegI dst, eRegI src) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountI src));
+
+  format %{ "POPCNT $dst, $src" %}
+  ins_encode %{
+    __ popcntl($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct popCountI_mem(eRegI dst, memory mem) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountI (LoadI mem)));
+
+  format %{ "POPCNT $dst, $mem" %}
+  ins_encode %{
+    __ popcntl($dst$$Register, $mem$$Address);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+// Note: Long.bitCount(long) returns an int.
+instruct popCountL(eRegI dst, eRegL src, eRegI tmp, eFlagsReg cr) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountL src));
+  effect(KILL cr, TEMP tmp, TEMP dst);
+
+  format %{ "POPCNT $dst, $src.lo\n\t"
+            "POPCNT $tmp, $src.hi\n\t"
+            "ADD    $dst, $tmp" %}
+  ins_encode %{
+    __ popcntl($dst$$Register, $src$$Register);
+    __ popcntl($tmp$$Register, HIGH_FROM_LOW($src$$Register));
+    __ addl($dst$$Register, $tmp$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+// Note: Long.bitCount(long) returns an int.
+instruct popCountL_mem(eRegI dst, memory mem, eRegI tmp, eFlagsReg cr) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountL (LoadL mem)));
+  effect(KILL cr, TEMP tmp, TEMP dst);
+
+  format %{ "POPCNT $dst, $mem\n\t"
+            "POPCNT $tmp, $mem+4\n\t"
+            "ADD    $dst, $tmp" %}
+  ins_encode %{
+    //__ popcntl($dst$$Register, $mem$$Address$$first);
+    //__ popcntl($tmp$$Register, $mem$$Address$$second);
+    __ popcntl($dst$$Register, Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp, false));
+    __ popcntl($tmp$$Register, Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp + 4, false));
+    __ addl($dst$$Register, $tmp$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+
 //----------Load/Store/Move Instructions---------------------------------------
 //----------Load Instructions--------------------------------------------------
 // Load Byte (8bit signed)
@@ -6396,21 +6712,94 @@
   match(Set dst (LoadB mem));
 
   ins_cost(125);
-  format %{ "MOVSX8 $dst,$mem" %}
-  opcode(0xBE, 0x0F);
-  ins_encode( OpcS, OpcP, RegMem(dst,mem));
-  ins_pipe( ialu_reg_mem );
-%}
-
-// Load Byte (8bit UNsigned)
-instruct loadUB(xRegI dst, memory mem, immI_255 bytemask) %{
-  match(Set dst (AndI (LoadB mem) bytemask));
+  format %{ "MOVSX8 $dst,$mem\t# byte" %}
+
+  ins_encode %{
+    __ movsbl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Byte (8bit signed) into Long Register
+instruct loadB2L(eRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadB mem)));
+
+  ins_cost(375);
+  format %{ "MOVSX8 $dst.lo,$mem\t# byte -> long\n\t"
+            "MOV    $dst.hi,$dst.lo\n\t"
+            "SAR    $dst.hi,7" %}
+
+  ins_encode %{
+    __ movsbl($dst$$Register, $mem$$Address);
+    __ movl(HIGH_FROM_LOW($dst$$Register), $dst$$Register); // This is always a different register.
+    __ sarl(HIGH_FROM_LOW($dst$$Register), 7); // 24+1 MSB are already signed extended.
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Byte (8bit UNsigned)
+instruct loadUB(xRegI dst, memory mem) %{
+  match(Set dst (LoadUB mem));
 
   ins_cost(125);
-  format %{ "MOVZX8 $dst,$mem" %}
-  opcode(0xB6, 0x0F);
-  ins_encode( OpcS, OpcP, RegMem(dst,mem));
-  ins_pipe( ialu_reg_mem );
+  format %{ "MOVZX8 $dst,$mem\t# ubyte -> int" %}
+
+  ins_encode %{
+    __ movzbl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Byte (8 bit UNsigned) into Long Register
+instruct loadUB2L(eRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadUB mem)));
+
+  ins_cost(250);
+  format %{ "MOVZX8 $dst.lo,$mem\t# ubyte -> long\n\t"
+            "XOR    $dst.hi,$dst.hi" %}
+
+  ins_encode %{
+    __ movzbl($dst$$Register, $mem$$Address);
+    __ xorl(HIGH_FROM_LOW($dst$$Register), HIGH_FROM_LOW($dst$$Register));
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Short (16bit signed)
+instruct loadS(eRegI dst, memory mem) %{
+  match(Set dst (LoadS mem));
+
+  ins_cost(125);
+  format %{ "MOVSX  $dst,$mem\t# short" %}
+
+  ins_encode %{
+    __ movswl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Short (16bit signed) into Long Register
+instruct loadS2L(eRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadS mem)));
+
+  ins_cost(375);
+  format %{ "MOVSX  $dst.lo,$mem\t# short -> long\n\t"
+            "MOV    $dst.hi,$dst.lo\n\t"
+            "SAR    $dst.hi,15" %}
+
+  ins_encode %{
+    __ movswl($dst$$Register, $mem$$Address);
+    __ movl(HIGH_FROM_LOW($dst$$Register), $dst$$Register); // This is always a different register.
+    __ sarl(HIGH_FROM_LOW($dst$$Register), 15); // 16+1 MSB are already signed extended.
+  %}
+
+  ins_pipe(ialu_reg_mem);
 %}
 
 // Load Unsigned Short/Char (16bit unsigned)
@@ -6418,10 +6807,30 @@
   match(Set dst (LoadUS mem));
 
   ins_cost(125);
-  format %{ "MOVZX  $dst,$mem" %}
-  opcode(0xB7, 0x0F);
-  ins_encode( OpcS, OpcP, RegMem(dst,mem));
-  ins_pipe( ialu_reg_mem );
+  format %{ "MOVZX  $dst,$mem\t# ushort/char -> int" %}
+
+  ins_encode %{
+    __ movzwl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Short/Char (16 bit UNsigned) into Long Register
+instruct loadUS2L(eRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadUS mem)));
+
+  ins_cost(250);
+  format %{ "MOVZX  $dst.lo,$mem\t# ushort/char -> long\n\t"
+            "XOR    $dst.hi,$dst.hi" %}
+
+  ins_encode %{
+    __ movzwl($dst$$Register, $mem$$Address);
+    __ xorl(HIGH_FROM_LOW($dst$$Register), HIGH_FROM_LOW($dst$$Register));
+  %}
+
+  ins_pipe(ialu_reg_mem);
 %}
 
 // Load Integer
@@ -6429,10 +6838,47 @@
   match(Set dst (LoadI mem));
 
   ins_cost(125);
-  format %{ "MOV    $dst,$mem" %}
-  opcode(0x8B);
-  ins_encode( OpcP, RegMem(dst,mem));
-  ins_pipe( ialu_reg_mem );
+  format %{ "MOV    $dst,$mem\t# int" %}
+
+  ins_encode %{
+    __ movl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Integer into Long Register
+instruct loadI2L(eRegL dst, memory mem) %{
+  match(Set dst (ConvI2L (LoadI mem)));
+
+  ins_cost(375);
+  format %{ "MOV    $dst.lo,$mem\t# int -> long\n\t"
+            "MOV    $dst.hi,$dst.lo\n\t"
+            "SAR    $dst.hi,31" %}
+
+  ins_encode %{
+    __ movl($dst$$Register, $mem$$Address);
+    __ movl(HIGH_FROM_LOW($dst$$Register), $dst$$Register); // This is always a different register.
+    __ sarl(HIGH_FROM_LOW($dst$$Register), 31);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Integer into Long Register
+instruct loadUI2L(eRegL dst, memory mem) %{
+  match(Set dst (LoadUI2L mem));
+
+  ins_cost(250);
+  format %{ "MOV    $dst.lo,$mem\t# uint -> long\n\t"
+            "XOR    $dst.hi,$dst.hi" %}
+
+  ins_encode %{
+    __ movl($dst$$Register, $mem$$Address);
+    __ xorl(HIGH_FROM_LOW($dst$$Register), HIGH_FROM_LOW($dst$$Register));
+  %}
+
+  ins_pipe(ialu_reg_mem);
 %}
 
 // Load Long.  Cannot clobber address while loading, so restrict address
@@ -6442,11 +6888,17 @@
   match(Set dst (LoadL mem));
 
   ins_cost(250);
-  format %{ "MOV    $dst.lo,$mem\n\t"
+  format %{ "MOV    $dst.lo,$mem\t# long\n\t"
             "MOV    $dst.hi,$mem+4" %}
-  opcode(0x8B, 0x8B);
-  ins_encode( OpcP, RegMem(dst,mem), OpcS, RegMem_Hi(dst,mem));
-  ins_pipe( ialu_reg_long_mem );
+
+  ins_encode %{
+    Address Amemlo = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp, false);
+    Address Amemhi = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp + 4, false);
+    __ movl($dst$$Register, Amemlo);
+    __ movl(HIGH_FROM_LOW($dst$$Register), Amemhi);
+  %}
+
+  ins_pipe(ialu_reg_long_mem);
 %}
 
 // Volatile Load Long.  Must be atomic, so do 64-bit FILD
@@ -6521,17 +6973,6 @@
   ins_pipe( ialu_reg_mem );
 %}
 
-// Load Short (16bit signed)
-instruct loadS(eRegI dst, memory mem) %{
-  match(Set dst (LoadS mem));
-
-  ins_cost(125);
-  format %{ "MOVSX  $dst,$mem" %}
-  opcode(0xBF, 0x0F);
-  ins_encode( OpcS, OpcP, RegMem(dst,mem));
-  ins_pipe( ialu_reg_mem );
-%}
-
 // Load Double
 instruct loadD(regD dst, memory mem) %{
   predicate(UseSSE<=1);
@@ -7321,9 +7762,9 @@
   ins_cost(400);
 
   size(0);
-  format %{ "MEMBAR-acquire" %}
-  ins_encode( enc_membar_acquire );
-  ins_pipe(pipe_slow);
+  format %{ "MEMBAR-acquire ! (empty encoding)" %}
+  ins_encode();
+  ins_pipe(empty);
 %}
 
 instruct membar_acquire_lock() %{
@@ -7342,9 +7783,9 @@
   ins_cost(400);
 
   size(0);
-  format %{ "MEMBAR-release" %}
-  ins_encode( enc_membar_release );
-  ins_pipe(pipe_slow);
+  format %{ "MEMBAR-release ! (empty encoding)" %}
+  ins_encode( );
+  ins_pipe(empty);
 %}
 
 instruct membar_release_lock() %{
@@ -7358,12 +7799,22 @@
   ins_pipe(empty);
 %}
 
-instruct membar_volatile() %{
+instruct membar_volatile(eFlagsReg cr) %{
   match(MemBarVolatile);
+  effect(KILL cr);
   ins_cost(400);
 
-  format %{ "MEMBAR-volatile" %}
-  ins_encode( enc_membar_volatile );
+  format %{ 
+    $$template
+    if (os::is_MP()) {
+      $$emit$$"LOCK ADDL [ESP + #0], 0\t! membar_volatile"
+    } else {
+      $$emit$$"MEMBAR-volatile ! (empty encoding)"
+    }
+  %}
+  ins_encode %{
+    __ membar(Assembler::StoreLoad);
+  %}
   ins_pipe(pipe_slow);
 %}
 
@@ -7957,7 +8408,7 @@
     __ xchgl(as_Register(EBX_enc), as_Register(ECX_enc));
     if( os::is_MP() )
       __ lock();
-    __ cmpxchg8(Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp));
+    __ cmpxchg8($mem$$Address);
     __ xchgl(as_Register(EBX_enc), as_Register(ECX_enc));
   %}
   ins_pipe( pipe_cmpxchg );
@@ -11467,6 +11918,7 @@
 instruct convI2L_reg( eRegL dst, eRegI src, eFlagsReg cr) %{
   match(Set dst (ConvI2L src));
   effect(KILL cr);
+  ins_cost(375);
   format %{ "MOV    $dst.lo,$src\n\t"
             "MOV    $dst.hi,$src\n\t"
             "SAR    $dst.hi,31" %}
@@ -11478,6 +11930,7 @@
 instruct convI2L_reg_zex(eRegL dst, eRegI src, immL_32bits mask, eFlagsReg flags ) %{
   match(Set dst (AndL (ConvI2L src) mask) );
   effect( KILL flags );
+  ins_cost(250);
   format %{ "MOV    $dst.lo,$src\n\t"
             "XOR    $dst.hi,$dst.hi" %}
   opcode(0x33); // XOR
@@ -11489,6 +11942,7 @@
 instruct zerox_long(eRegL dst, eRegL src, immL_32bits mask, eFlagsReg flags ) %{
   match(Set dst (AndL src mask) );
   effect( KILL flags );
+  ins_cost(250);
   format %{ "MOV    $dst.lo,$src.lo\n\t"
             "XOR    $dst.hi,$dst.hi\n\t" %}
   opcode(0x33); // XOR
@@ -11902,11 +12356,8 @@
   ins_pipe( fpu_reg_reg );
 %}
 
-
-
 // =======================================================================
 // fast clearing of an array
-
 instruct rep_stos(eCXRegI cnt, eDIRegP base, eAXRegI zero, Universe dummy, eFlagsReg cr) %{
   match(Set dummy (ClearArray cnt base));
   effect(USE_KILL cnt, USE_KILL base, KILL zero, KILL cr);
@@ -11920,24 +12371,48 @@
   ins_pipe( pipe_slow );
 %}
 
-instruct string_compare(eDIRegP str1, eSIRegP str2, eAXRegI tmp1, eBXRegI tmp2, eCXRegI result, eFlagsReg cr) %{
+instruct string_compare(eDIRegP str1, eSIRegP str2, regXD tmp1, regXD tmp2,
+                        eAXRegI tmp3, eBXRegI tmp4, eCXRegI result, eFlagsReg cr) %{
   match(Set result (StrComp str1 str2));
-  effect(USE_KILL str1, USE_KILL str2, KILL tmp1, KILL tmp2, KILL cr);
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL str1, USE_KILL str2, KILL tmp3, KILL tmp4, KILL cr);
   //ins_cost(300);
 
   format %{ "String Compare $str1,$str2 -> $result    // KILL EAX, EBX" %}
-  ins_encode( enc_String_Compare() );
+  ins_encode( enc_String_Compare(str1, str2, tmp1, tmp2, tmp3, tmp4, result) );
+  ins_pipe( pipe_slow );
+%}
+
+// fast string equals
+instruct string_equals(eDIRegP str1, eSIRegP str2, regXD tmp1, regXD tmp2,
+                       eBXRegI tmp3, eCXRegI tmp4, eAXRegI result, eFlagsReg cr) %{
+  match(Set result (StrEquals str1 str2));
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL str1, USE_KILL str2, KILL tmp3, KILL tmp4, KILL cr);
+
+  format %{ "String Equals $str1,$str2 -> $result    // KILL EBX, ECX" %}
+  ins_encode( enc_String_Equals(tmp1, tmp2, str1, str2, tmp3, tmp4, result) );
+  ins_pipe( pipe_slow );
+%}
+
+instruct string_indexof(eSIRegP str1, eDIRegP str2, regXD tmp1, eAXRegI tmp2,
+                        eCXRegI tmp3, eDXRegI tmp4, eBXRegI result, eFlagsReg cr) %{
+  predicate(UseSSE42Intrinsics);
+  match(Set result (StrIndexOf str1 str2));
+  effect(TEMP tmp1, USE_KILL str1, USE_KILL str2, KILL tmp2, KILL tmp3, KILL tmp4, KILL cr);
+
+  format %{ "String IndexOf $str1,$str2 -> $result    // KILL EAX, ECX, EDX" %}
+  ins_encode( enc_String_IndexOf(str1, str2, tmp1, tmp2, tmp3, tmp4, result) );
   ins_pipe( pipe_slow );
 %}
 
 // fast array equals
-instruct array_equals(eDIRegP ary1, eSIRegP ary2, eAXRegI tmp1, eBXRegI tmp2, eCXRegI result, eFlagsReg cr) %{
+instruct array_equals(eDIRegP ary1, eSIRegP ary2, regXD tmp1, regXD tmp2, eBXRegI tmp3,
+                      eDXRegI tmp4, eAXRegI result, eFlagsReg cr) %{
   match(Set result (AryEq ary1 ary2));
-  effect(USE_KILL ary1, USE_KILL ary2, KILL tmp1, KILL tmp2, KILL cr);
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL ary1, USE_KILL ary2, KILL tmp3, KILL tmp4, KILL cr);
   //ins_cost(300);
 
-  format %{ "Array Equals $ary1,$ary2 -> $result    // KILL EAX, EBX" %}
-  ins_encode( enc_Array_Equals(ary1, ary2, tmp1, tmp2, result) );
+  format %{ "Array Equals $ary1,$ary2 -> $result    // KILL EBX, EDX" %}
+  ins_encode( enc_Array_Equals(ary1, ary2, tmp1, tmp2, tmp3, tmp4, result) );
   ins_pipe( pipe_slow );
 %}
 
@@ -12375,15 +12850,12 @@
   effect( KILL rcx, KILL cr );
 
   ins_cost(1100);  // slightly larger than the next version
-  format %{ "CMPL   EAX,ESI\n\t"
-            "JEQ,s  hit\n\t"
-            "MOV    EDI,[$sub+Klass::secondary_supers]\n\t"
+  format %{ "MOV    EDI,[$sub+Klass::secondary_supers]\n\t"
             "MOV    ECX,[EDI+arrayKlass::length]\t# length to scan\n\t"
             "ADD    EDI,arrayKlass::base_offset\t# Skip to start of data; set NZ in case count is zero\n\t"
             "REPNE SCASD\t# Scan *EDI++ for a match with EAX while CX-- != 0\n\t"
             "JNE,s  miss\t\t# Missed: EDI not-zero\n\t"
             "MOV    [$sub+Klass::secondary_super_cache],$super\t# Hit: update cache\n\t"
-     "hit:\n\t"
             "XOR    $result,$result\t\t Hit: EDI zero\n\t"
      "miss:\t" %}
 
@@ -12397,9 +12869,7 @@
   effect( KILL rcx, KILL result );
 
   ins_cost(1000);
-  format %{ "CMPL   EAX,ESI\n\t"
-            "JEQ,s  miss\t# Actually a hit; we are done.\n\t"
-            "MOV    EDI,[$sub+Klass::secondary_supers]\n\t"
+  format %{ "MOV    EDI,[$sub+Klass::secondary_supers]\n\t"
             "MOV    ECX,[EDI+arrayKlass::length]\t# length to scan\n\t"
             "ADD    EDI,arrayKlass::base_offset\t# Skip to start of data; set NZ in case count is zero\n\t"
             "REPNE SCASD\t# Scan *EDI++ for a match with EAX while CX-- != 0\n\t"
@@ -13220,7 +13690,7 @@
 // These must follow all instruction definitions as they use the names
 // defined in the instructions definitions.
 //
-// peepmatch ( root_instr_name [preceeding_instruction]* );
+// peepmatch ( root_instr_name [preceding_instruction]* );
 //
 // peepconstraint %{
 // (instruction_number.operand_name relational_op instruction_number.operand_name
--- a/hotspot/src/cpu/x86/vm/x86_64.ad	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/cpu/x86/vm/x86_64.ad	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -326,7 +326,6 @@
                          R9,  R9_H,
                          R10, R10_H,
                          R11, R11_H,
-                         R12, R12_H,
                          R13, R13_H,
                          R14, R14_H);
 
@@ -340,7 +339,6 @@
                          R9,  R9_H,
                          R10, R10_H,
                          R11, R11_H,
-                         R12, R12_H,
                          R13, R13_H,
                          R14, R14_H);
 
@@ -354,7 +352,6 @@
                              R9,  R9_H,
                              R10, R10_H,
                              R11, R11_H,
-                             R12, R12_H,
                              R13, R13_H,
                              R14, R14_H);
 
@@ -444,9 +441,6 @@
 // Singleton class for RDX long register
 reg_class long_rdx_reg(RDX, RDX_H);
 
-// Singleton class for R12 long register
-reg_class long_r12_reg(R12, R12_H);
-
 // Class for all int registers (except RSP)
 reg_class int_reg(RAX,
                   RDX,
@@ -1842,7 +1836,9 @@
 {
   if (UseCompressedOops) {
     st->print_cr("movl    rscratch1, [j_rarg0 + oopDesc::klass_offset_in_bytes() #%d]\t", oopDesc::klass_offset_in_bytes());
-    st->print_cr("leaq    rscratch1, [r12_heapbase, r, Address::times_8, 0]");
+    if (Universe::narrow_oop_shift() != 0) {
+      st->print_cr("leaq    rscratch1, [r12_heapbase, r, Address::times_8, 0]");
+    }
     st->print_cr("cmpq    rax, rscratch1\t # Inline cache check");
   } else {
     st->print_cr("cmpq    rax, [j_rarg0 + oopDesc::klass_offset_in_bytes() #%d]\t"
@@ -1891,7 +1887,11 @@
 uint MachUEPNode::size(PhaseRegAlloc* ra_) const
 {
   if (UseCompressedOops) {
-    return OptoBreakpoint ? 19 : 20;
+    if (Universe::narrow_oop_shift() == 0) {
+      return OptoBreakpoint ? 15 : 16;
+    } else {
+      return OptoBreakpoint ? 19 : 20;
+    }
   } else {
     return OptoBreakpoint ? 11 : 12;
   }
@@ -2575,45 +2575,13 @@
     Register Rrax = as_Register(RAX_enc); // super class
     Register Rrcx = as_Register(RCX_enc); // killed
     Register Rrsi = as_Register(RSI_enc); // sub class
-    Label hit, miss, cmiss;
+    Label miss;
+    const bool set_cond_codes = true;
 
     MacroAssembler _masm(&cbuf);
-    // Compare super with sub directly, since super is not in its own SSA.
-    // The compiler used to emit this test, but we fold it in here,
-    // to allow platform-specific tweaking on sparc.
-    __ cmpptr(Rrax, Rrsi);
-    __ jcc(Assembler::equal, hit);
-#ifndef PRODUCT
-    __ lea(Rrcx, ExternalAddress((address)&SharedRuntime::_partial_subtype_ctr));
-    __ incrementl(Address(Rrcx, 0));
-#endif //PRODUCT
-    __ movptr(Rrdi, Address(Rrsi, 
-                          sizeof(oopDesc) + 
-                          Klass::secondary_supers_offset_in_bytes()));
-    __ movl(Rrcx, Address(Rrdi, arrayOopDesc::length_offset_in_bytes()));
-    __ addptr(Rrdi, arrayOopDesc::base_offset_in_bytes(T_OBJECT));
-    if (UseCompressedOops) {
-      __ encode_heap_oop(Rrax);
-      __ repne_scanl();
-      __ jcc(Assembler::notEqual, cmiss);
-      __ decode_heap_oop(Rrax);
-      __ movptr(Address(Rrsi,
-                      sizeof(oopDesc) +
-                      Klass::secondary_super_cache_offset_in_bytes()),
-              Rrax);
-      __ jmp(hit);
-      __ bind(cmiss);
-      __ decode_heap_oop(Rrax);
-      __ jmp(miss);
-    } else {
-      __ repne_scan();
-      __ jcc(Assembler::notEqual, miss);
-      __ movptr(Address(Rrsi,
-                      sizeof(oopDesc) +
-                      Klass::secondary_super_cache_offset_in_bytes()),
-              Rrax);
-    }
-    __ bind(hit);
+    __ check_klass_subtype_slow_path(Rrsi, Rrax, Rrcx, Rrdi,
+                                     NULL, &miss,
+                                     /*set_cond_codes:*/ true);
     if ($primary) {
       __ xorptr(Rrdi, Rrdi);
     }
@@ -3462,14 +3430,12 @@
 
   enc_class movq_ld(regD dst, memory mem) %{
     MacroAssembler _masm(&cbuf);
-    Address madr = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ movq(as_XMMRegister($dst$$reg), madr);
+    __ movq($dst$$XMMRegister, $mem$$Address);
   %}
 
   enc_class movq_st(memory mem, regD src) %{
     MacroAssembler _masm(&cbuf);
-    Address madr = Address::make_raw($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ movq(madr, as_XMMRegister($src$$reg));
+    __ movq($mem$$Address, $src$$XMMRegister);
   %}
 
   enc_class pshufd_8x8(regF dst, regF src) %{
@@ -3728,13 +3694,16 @@
     }
   %}
 
-  enc_class enc_String_Compare()
-  %{
+  enc_class enc_String_Compare(rdi_RegP str1, rsi_RegP str2, regD tmp1, regD tmp2,
+                        rax_RegI tmp3, rbx_RegI tmp4, rcx_RegI result) %{
     Label RCX_GOOD_LABEL, LENGTH_DIFF_LABEL,
           POP_LABEL, DONE_LABEL, CONT_LABEL,
           WHILE_HEAD_LABEL;
     MacroAssembler masm(&cbuf);
 
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+
     // Get the first character position in both strings
     //         [8] char array, [12] offset, [16] count
     int value_offset  = java_lang_String::value_offset_in_bytes();
@@ -3752,6 +3721,7 @@
     // Compute the minimum of the string lengths(rsi) and the
     // difference of the string lengths (stack)
 
+    // do the conditional move stuff
     masm.movl(rdi, Address(rdi, count_offset));
     masm.movl(rsi, Address(rsi, count_offset));
     masm.movl(rcx, rdi);
@@ -3765,8 +3735,8 @@
     masm.jcc(Assembler::zero, LENGTH_DIFF_LABEL);
 
     // Load first characters
-    masm.load_unsigned_word(rcx, Address(rbx, 0));
-    masm.load_unsigned_word(rdi, Address(rax, 0));
+    masm.load_unsigned_short(rcx, Address(rbx, 0));
+    masm.load_unsigned_short(rdi, Address(rax, 0));
 
     // Compare first characters
     masm.subl(rcx, rdi);
@@ -3779,7 +3749,7 @@
       Label LSkip2;
       // Check if the strings start at same location
       masm.cmpptr(rbx, rax);
-      masm.jcc(Assembler::notEqual, LSkip2);
+      masm.jccb(Assembler::notEqual, LSkip2);
 
       // Check if the length difference is zero (from stack)
       masm.cmpl(Address(rsp, 0), 0x0);
@@ -3789,103 +3759,382 @@
       masm.bind(LSkip2);
     }
 
+    // Advance to next character
+    masm.addptr(rax, 2);
+    masm.addptr(rbx, 2);
+
+    if (UseSSE42Intrinsics) {
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
+      // Setup to compare 16-byte vectors
+      masm.movl(rdi, rsi);
+      masm.andl(rsi, 0xfffffff8); // rsi holds the vector count
+      masm.andl(rdi, 0x00000007); // rdi holds the tail count
+      masm.testl(rsi, rsi);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+
+      masm.lea(rax, Address(rax, rsi, Address::times_2));
+      masm.lea(rbx, Address(rbx, rsi, Address::times_2));
+      masm.negptr(rsi);
+
+      masm.bind(COMPARE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(rax, rsi, Address::times_2));
+      masm.movdqu(tmp2Reg, Address(rbx, rsi, Address::times_2));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+      masm.jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
+      masm.addptr(rsi, 8);
+      masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+      masm.jmpb(COMPARE_TAIL);
+
+      // Mismatched characters in the vectors
+      masm.bind(VECTOR_NOT_EQUAL);
+      masm.lea(rax, Address(rax, rsi, Address::times_2));
+      masm.lea(rbx, Address(rbx, rsi, Address::times_2));
+      masm.movl(rdi, 8);
+
+      // Compare tail (< 8 chars), or rescan last vectors to
+      // find 1st mismatched characters
+      masm.bind(COMPARE_TAIL);
+      masm.testl(rdi, rdi);
+      masm.jccb(Assembler::zero, LENGTH_DIFF_LABEL);
+      masm.movl(rsi, rdi);
+      // Fallthru to tail compare
+    }
+
     // Shift RAX and RBX to the end of the arrays, negate min
-    masm.lea(rax, Address(rax, rsi, Address::times_2, 2));
-    masm.lea(rbx, Address(rbx, rsi, Address::times_2, 2));
+    masm.lea(rax, Address(rax, rsi, Address::times_2, 0));
+    masm.lea(rbx, Address(rbx, rsi, Address::times_2, 0));
     masm.negptr(rsi);
 
     // Compare the rest of the characters
     masm.bind(WHILE_HEAD_LABEL);
-    masm.load_unsigned_word(rcx, Address(rbx, rsi, Address::times_2, 0));
-    masm.load_unsigned_word(rdi, Address(rax, rsi, Address::times_2, 0));
+    masm.load_unsigned_short(rcx, Address(rbx, rsi, Address::times_2, 0));
+    masm.load_unsigned_short(rdi, Address(rax, rsi, Address::times_2, 0));
     masm.subl(rcx, rdi);
-    masm.jcc(Assembler::notZero, POP_LABEL);
+    masm.jccb(Assembler::notZero, POP_LABEL);
     masm.increment(rsi);
     masm.jcc(Assembler::notZero, WHILE_HEAD_LABEL);
 
     // Strings are equal up to min length.  Return the length difference.
     masm.bind(LENGTH_DIFF_LABEL);
     masm.pop(rcx);
-    masm.jmp(DONE_LABEL);
+    masm.jmpb(DONE_LABEL);
 
     // Discard the stored length difference
     masm.bind(POP_LABEL);
     masm.addptr(rsp, 8);
-       
+
     // That's it
     masm.bind(DONE_LABEL);
   %}
 
-  enc_class enc_Array_Equals(rdi_RegP ary1, rsi_RegP ary2, rax_RegI tmp1, rbx_RegI tmp2, rcx_RegI result) %{
-    Label TRUE_LABEL, FALSE_LABEL, DONE_LABEL, COMPARE_LOOP_HDR, COMPARE_LOOP;
+ enc_class enc_String_IndexOf(rsi_RegP str1, rdi_RegP str2, regD tmp1, rax_RegI tmp2,
+                        rcx_RegI tmp3, rdx_RegI tmp4, rbx_RegI result) %{
+    // SSE4.2 version
+    Label LOAD_SUBSTR, PREP_FOR_SCAN, SCAN_TO_SUBSTR,
+          SCAN_SUBSTR, RET_NEG_ONE, RET_NOT_FOUND, CLEANUP, DONE;
     MacroAssembler masm(&cbuf);
 
-    Register ary1Reg   = as_Register($ary1$$reg);
-    Register ary2Reg   = as_Register($ary2$$reg);
-    Register tmp1Reg   = as_Register($tmp1$$reg);
-    Register tmp2Reg   = as_Register($tmp2$$reg);
-    Register resultReg = as_Register($result$$reg);
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+
+    // Get the first character position in both strings
+    //         [8] char array, [12] offset, [16] count
+    int value_offset  = java_lang_String::value_offset_in_bytes();
+    int offset_offset = java_lang_String::offset_offset_in_bytes();
+    int count_offset  = java_lang_String::count_offset_in_bytes();
+    int base_offset   = arrayOopDesc::base_offset_in_bytes(T_CHAR);
+
+    // Get counts for string and substr
+    masm.movl(rdx, Address(rsi, count_offset));
+    masm.movl(rax, Address(rdi, count_offset));
+    // Check for substr count > string count
+    masm.cmpl(rax, rdx);
+    masm.jcc(Assembler::greater, RET_NEG_ONE);
+
+    // Start the indexOf operation
+    // Get start addr of string
+    masm.load_heap_oop(rbx, Address(rsi, value_offset));
+    masm.movl(rcx, Address(rsi, offset_offset));
+    masm.lea(rsi, Address(rbx, rcx, Address::times_2, base_offset));
+    masm.push(rsi);
+
+    // Get start addr of substr
+    masm.load_heap_oop(rbx, Address(rdi, value_offset));
+    masm.movl(rcx, Address(rdi, offset_offset));
+    masm.lea(rdi, Address(rbx, rcx, Address::times_2, base_offset));
+    masm.push(rdi);
+    masm.push(rax);
+    masm.jmpb(PREP_FOR_SCAN);
+
+    // Substr count saved at sp
+    // Substr saved at sp+8
+    // String saved at sp+16
+
+    // Prep to load substr for scan
+    masm.bind(LOAD_SUBSTR);
+    masm.movptr(rdi, Address(rsp, 8));
+    masm.movl(rax, Address(rsp, 0));
+
+    // Load substr
+    masm.bind(PREP_FOR_SCAN);
+    masm.movdqu(tmp1Reg, Address(rdi, 0));
+    masm.addq(rdx, 8);    // prime the loop
+    masm.subptr(rsi, 16);
+
+    // Scan string for substr in 16-byte vectors
+    masm.bind(SCAN_TO_SUBSTR);
+    masm.subq(rdx, 8);
+    masm.addptr(rsi, 16);
+    masm.pcmpestri(tmp1Reg, Address(rsi, 0), 0x0d);
+    masm.jcc(Assembler::above, SCAN_TO_SUBSTR);
+    masm.jccb(Assembler::aboveEqual, RET_NOT_FOUND);
+
+    // Fallthru: found a potential substr
+
+    //Make sure string is still long enough
+    masm.subl(rdx, rcx);
+    masm.cmpl(rdx, rax);
+    masm.jccb(Assembler::negative, RET_NOT_FOUND);
+    // Compute start addr of substr
+    masm.lea(rsi, Address(rsi, rcx, Address::times_2));
+    masm.movptr(rbx, rsi);
+
+    // Compare potential substr
+    masm.addq(rdx, 8);        // prime the loop
+    masm.addq(rax, 8);
+    masm.subptr(rsi, 16);
+    masm.subptr(rdi, 16);
+
+    // Scan 16-byte vectors of string and substr
+    masm.bind(SCAN_SUBSTR);
+    masm.subq(rax, 8);
+    masm.subq(rdx, 8);
+    masm.addptr(rsi, 16);
+    masm.addptr(rdi, 16);
+    masm.movdqu(tmp1Reg, Address(rdi, 0));
+    masm.pcmpestri(tmp1Reg, Address(rsi, 0), 0x0d);
+    masm.jcc(Assembler::noOverflow, LOAD_SUBSTR);   // OF == 0
+    masm.jcc(Assembler::positive, SCAN_SUBSTR);     // SF == 0
+
+    // Compute substr offset
+    masm.movptr(rsi, Address(rsp, 16));
+    masm.subptr(rbx, rsi);
+    masm.shrl(rbx, 1);
+    masm.jmpb(CLEANUP);
+
+    masm.bind(RET_NEG_ONE);
+    masm.movl(rbx, -1);
+    masm.jmpb(DONE);
+
+    masm.bind(RET_NOT_FOUND);
+    masm.movl(rbx, -1);
+
+    masm.bind(CLEANUP);
+    masm.addptr(rsp, 24);
+
+    masm.bind(DONE);
+  %}
+
+  enc_class enc_String_Equals(rdi_RegP str1, rsi_RegP str2, regD tmp1, regD tmp2,
+                              rbx_RegI tmp3, rcx_RegI tmp2, rax_RegI result) %{
+    Label RET_TRUE, RET_FALSE, DONE, COMPARE_VECTORS, COMPARE_CHAR;
+    MacroAssembler masm(&cbuf);
+
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+
+    int value_offset  = java_lang_String::value_offset_in_bytes();
+    int offset_offset = java_lang_String::offset_offset_in_bytes();
+    int count_offset  = java_lang_String::count_offset_in_bytes();
+    int base_offset   = arrayOopDesc::base_offset_in_bytes(T_CHAR);
+
+    // does source == target string?
+    masm.cmpptr(rdi, rsi);
+    masm.jcc(Assembler::equal, RET_TRUE);
+
+    // get and compare counts
+    masm.movl(rcx, Address(rdi, count_offset));
+    masm.movl(rax, Address(rsi, count_offset));
+    masm.cmpl(rcx, rax);
+    masm.jcc(Assembler::notEqual, RET_FALSE);
+    masm.testl(rax, rax);
+    masm.jcc(Assembler::zero, RET_TRUE);
+
+    // get source string offset and value
+    masm.load_heap_oop(rbx, Address(rsi, value_offset));
+    masm.movl(rax, Address(rsi, offset_offset));
+    masm.lea(rsi, Address(rbx, rax, Address::times_2, base_offset));
+
+    // get compare string offset and value
+    masm.load_heap_oop(rbx, Address(rdi, value_offset));
+    masm.movl(rax, Address(rdi, offset_offset));
+    masm.lea(rdi, Address(rbx, rax, Address::times_2, base_offset));
+
+    // Set byte count
+    masm.shll(rcx, 1);
+    masm.movl(rax, rcx);
+
+    if (UseSSE42Intrinsics) {
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
+      // Compare 16-byte vectors
+      masm.andl(rcx, 0xfffffff0);  // vector count (in bytes)
+      masm.andl(rax, 0x0000000e);  // tail count (in bytes)
+      masm.testl(rcx, rcx);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+      masm.lea(rdi, Address(rdi, rcx, Address::times_1));
+      masm.lea(rsi, Address(rsi, rcx, Address::times_1));
+      masm.negptr(rcx);
+
+      masm.bind(COMPARE_WIDE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(rdi, rcx, Address::times_1));
+      masm.movdqu(tmp2Reg, Address(rsi, rcx, Address::times_1));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+      masm.jccb(Assembler::notZero, RET_FALSE);
+      masm.addptr(rcx, 16);
+      masm.jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
+      masm.bind(COMPARE_TAIL);
+      masm.movl(rcx, rax);
+      // Fallthru to tail compare
+    }
+
+    // Compare 4-byte vectors
+    masm.andl(rcx, 0xfffffffc);  // vector count (in bytes)
+    masm.andl(rax, 0x00000002);  // tail char (in bytes)
+    masm.testl(rcx, rcx);
+    masm.jccb(Assembler::zero, COMPARE_CHAR);
+    masm.lea(rdi, Address(rdi, rcx, Address::times_1));
+    masm.lea(rsi, Address(rsi, rcx, Address::times_1));
+    masm.negptr(rcx);
+
+    masm.bind(COMPARE_VECTORS);
+    masm.movl(rbx, Address(rdi, rcx, Address::times_1));
+    masm.cmpl(rbx, Address(rsi, rcx, Address::times_1));
+    masm.jccb(Assembler::notEqual, RET_FALSE);
+    masm.addptr(rcx, 4);
+    masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+
+    // Compare trailing char (final 2 bytes), if any
+    masm.bind(COMPARE_CHAR);
+    masm.testl(rax, rax);
+    masm.jccb(Assembler::zero, RET_TRUE);
+    masm.load_unsigned_short(rbx, Address(rdi, 0));
+    masm.load_unsigned_short(rcx, Address(rsi, 0));
+    masm.cmpl(rbx, rcx);
+    masm.jccb(Assembler::notEqual, RET_FALSE);
+
+    masm.bind(RET_TRUE);
+    masm.movl(rax, 1);   // return true
+    masm.jmpb(DONE);
+
+    masm.bind(RET_FALSE);
+    masm.xorl(rax, rax); // return false
+
+    masm.bind(DONE);
+  %}
+
+  enc_class enc_Array_Equals(rdi_RegP ary1, rsi_RegP ary2, regD tmp1, regD tmp2,
+                             rax_RegI tmp3, rbx_RegI tmp4, rcx_RegI result) %{
+    Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR;
+    MacroAssembler masm(&cbuf);
+
+    XMMRegister tmp1Reg   = as_XMMRegister($tmp1$$reg);
+    XMMRegister tmp2Reg   = as_XMMRegister($tmp2$$reg);
+    Register ary1Reg      = as_Register($ary1$$reg);
+    Register ary2Reg      = as_Register($ary2$$reg);
+    Register tmp3Reg      = as_Register($tmp3$$reg);
+    Register tmp4Reg      = as_Register($tmp4$$reg);
+    Register resultReg    = as_Register($result$$reg);
 
     int length_offset  = arrayOopDesc::length_offset_in_bytes();
     int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
 
     // Check the input args
-    masm.cmpq(ary1Reg, ary2Reg);                        
+    masm.cmpq(ary1Reg, ary2Reg);
     masm.jcc(Assembler::equal, TRUE_LABEL);
-    masm.testq(ary1Reg, ary1Reg);                       
+    masm.testq(ary1Reg, ary1Reg);
     masm.jcc(Assembler::zero, FALSE_LABEL);
-    masm.testq(ary2Reg, ary2Reg);                       
+    masm.testq(ary2Reg, ary2Reg);
     masm.jcc(Assembler::zero, FALSE_LABEL);
 
     // Check the lengths
-    masm.movl(tmp2Reg, Address(ary1Reg, length_offset));
+    masm.movl(tmp4Reg, Address(ary1Reg, length_offset));
     masm.movl(resultReg, Address(ary2Reg, length_offset));
-    masm.cmpl(tmp2Reg, resultReg);
+    masm.cmpl(tmp4Reg, resultReg);
     masm.jcc(Assembler::notEqual, FALSE_LABEL);
     masm.testl(resultReg, resultReg);
     masm.jcc(Assembler::zero, TRUE_LABEL);
 
-    // Get the number of 4 byte vectors to compare
-    masm.shrl(resultReg, 1);
-
-    // Check for odd-length arrays
-    masm.andl(tmp2Reg, 1);
-    masm.testl(tmp2Reg, tmp2Reg);
-    masm.jcc(Assembler::zero, COMPARE_LOOP_HDR);
-
-    // Compare 2-byte "tail" at end of arrays
-    masm.load_unsigned_word(tmp1Reg, Address(ary1Reg, resultReg, Address::times_4, base_offset));
-    masm.load_unsigned_word(tmp2Reg, Address(ary2Reg, resultReg, Address::times_4, base_offset));
-    masm.cmpl(tmp1Reg, tmp2Reg);
-    masm.jcc(Assembler::notEqual, FALSE_LABEL);
+    //load array address
+    masm.lea(ary1Reg, Address(ary1Reg, base_offset));
+    masm.lea(ary2Reg, Address(ary2Reg, base_offset));
+
+    //set byte count
+    masm.shll(tmp4Reg, 1);
+    masm.movl(resultReg,tmp4Reg);
+
+    if (UseSSE42Intrinsics){
+      // With SSE4.2, use double quad vector compare
+      Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
+      // Compare 16-byte vectors
+      masm.andl(tmp4Reg, 0xfffffff0);    // vector count (in bytes)
+      masm.andl(resultReg, 0x0000000e);  // tail count (in bytes)
+      masm.testl(tmp4Reg, tmp4Reg);
+      masm.jccb(Assembler::zero, COMPARE_TAIL);
+      masm.lea(ary1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+      masm.lea(ary2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+      masm.negptr(tmp4Reg);
+
+      masm.bind(COMPARE_WIDE_VECTORS);
+      masm.movdqu(tmp1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+      masm.movdqu(tmp2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+      masm.pxor(tmp1Reg, tmp2Reg);
+      masm.ptest(tmp1Reg, tmp1Reg);
+
+      masm.jccb(Assembler::notZero, FALSE_LABEL);
+      masm.addptr(tmp4Reg, 16);
+      masm.jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
+      masm.bind(COMPARE_TAIL);
+      masm.movl(tmp4Reg, resultReg);
+      // Fallthru to tail compare
+    }
+
+   // Compare 4-byte vectors
+    masm.andl(tmp4Reg, 0xfffffffc);    // vector count (in bytes)
+    masm.andl(resultReg, 0x00000002);  // tail char (in bytes)
+    masm.testl(tmp4Reg, tmp4Reg); //if tmp2 == 0, only compare char
+    masm.jccb(Assembler::zero, COMPARE_CHAR);
+    masm.lea(ary1Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+    masm.lea(ary2Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+    masm.negptr(tmp4Reg);
+
+    masm.bind(COMPARE_VECTORS);
+    masm.movl(tmp3Reg, Address(ary1Reg, tmp4Reg, Address::times_1));
+    masm.cmpl(tmp3Reg, Address(ary2Reg, tmp4Reg, Address::times_1));
+    masm.jccb(Assembler::notEqual, FALSE_LABEL);
+    masm.addptr(tmp4Reg, 4);
+    masm.jcc(Assembler::notZero, COMPARE_VECTORS);
+
+    // Compare trailing char (final 2 bytes), if any
+    masm.bind(COMPARE_CHAR);
     masm.testl(resultReg, resultReg);
-    masm.jcc(Assembler::zero, TRUE_LABEL);
-
-    // Setup compare loop
-    masm.bind(COMPARE_LOOP_HDR);
-    // Shift tmp1Reg and tmp2Reg to the last 4-byte boundary of the arrays
-    masm.leaq(tmp1Reg, Address(ary1Reg, resultReg, Address::times_4, base_offset));
-    masm.leaq(tmp2Reg, Address(ary2Reg, resultReg, Address::times_4, base_offset));
-    masm.negq(resultReg);
-
-    // 4-byte-wide compare loop
-    masm.bind(COMPARE_LOOP);
-    masm.movl(ary1Reg, Address(tmp1Reg, resultReg, Address::times_4, 0));
-    masm.movl(ary2Reg, Address(tmp2Reg, resultReg, Address::times_4, 0));
-    masm.cmpl(ary1Reg, ary2Reg);
-    masm.jcc(Assembler::notEqual, FALSE_LABEL);
-    masm.incrementq(resultReg);
-    masm.jcc(Assembler::notZero, COMPARE_LOOP);
+    masm.jccb(Assembler::zero, TRUE_LABEL);
+    masm.load_unsigned_short(tmp3Reg, Address(ary1Reg, 0));
+    masm.load_unsigned_short(tmp4Reg, Address(ary2Reg, 0));
+    masm.cmpl(tmp3Reg, tmp4Reg);
+    masm.jccb(Assembler::notEqual, FALSE_LABEL);
 
     masm.bind(TRUE_LABEL);
     masm.movl(resultReg, 1);   // return true
-    masm.jmp(DONE_LABEL);
+    masm.jmpb(DONE);
 
     masm.bind(FALSE_LABEL);
     masm.xorl(resultReg, resultReg); // return false
 
     // That's it
-    masm.bind(DONE_LABEL);
+    masm.bind(DONE);
   %}
 
   enc_class enc_rethrow()
@@ -4196,33 +4445,6 @@
     // done:
   %}
 
-  enc_class enc_membar_acquire
-  %{
-    // [jk] not needed currently, if you enable this and it really
-    // emits code don't forget to the remove the "size(0)" line in
-    // membar_acquire()
-    // MacroAssembler masm(&cbuf);
-    // masm.membar(Assembler::Membar_mask_bits(Assembler::LoadStore |
-    //                                         Assembler::LoadLoad));
-  %}
-
-  enc_class enc_membar_release
-  %{
-    // [jk] not needed currently, if you enable this and it really
-    // emits code don't forget to the remove the "size(0)" line in
-    // membar_release()
-    // MacroAssembler masm(&cbuf);
-    // masm.membar(Assembler::Membar_mask_bits(Assembler::LoadStore |
-    //                                         Assembler::StoreStore));
-  %}
-
-  enc_class enc_membar_volatile
-  %{
-    MacroAssembler masm(&cbuf);
-    masm.membar(Assembler::Membar_mask_bits(Assembler::StoreLoad |
-                                            Assembler::StoreStore));
-  %}
-
   // Safepoint Poll.  This polls the safepoint page, and causes an
   // exception if it is not readable. Unfortunately, it kills
   // RFLAGS in the process.
@@ -4908,15 +5130,6 @@
   interface(REG_INTER);
 %}
 
-
-operand r12RegL() %{
-  constraint(ALLOC_IN_RC(long_r12_reg));
-  match(RegL);
-
-  format %{ %}
-  interface(REG_INTER);
-%}
-
 operand rRegN() %{
   constraint(ALLOC_IN_RC(int_reg));
   match(RegN);
@@ -5157,7 +5370,7 @@
 %}
 
 // Double register operands
-operand regD()
+operand regD() 
 %{
   constraint(ALLOC_IN_RC(double_reg));
   match(RegD);
@@ -5291,21 +5504,6 @@
   %}
 %}
 
-// Indirect Narrow Oop Plus Offset Operand
-operand indNarrowOopOffset(rRegN src, immL32 off) %{
-  constraint(ALLOC_IN_RC(ptr_reg));
-  match(AddP (DecodeN src) off);
-
-  op_cost(10);
-  format %{"[R12 + $src << 3 + $off] (compressed oop addressing)" %}
-  interface(MEMORY_INTER) %{
-    base(0xc); // R12
-    index($src);
-    scale(0x3);
-    disp($off);
-  %}
-%}
-
 // Indirect Memory Times Scale Plus Positive Index Register Plus Offset Operand
 operand indPosIndexScaleOffset(any_RegP reg, immL32 off, rRegI idx, immI2 scale)
 %{
@@ -5323,6 +5521,158 @@
   %}
 %}
 
+// Indirect Narrow Oop Plus Offset Operand
+// Note: x86 architecture doesn't support "scale * index + offset" without a base
+// we can't free r12 even with Universe::narrow_oop_base() == NULL.
+operand indCompressedOopOffset(rRegN reg, immL32 off) %{
+  predicate(UseCompressedOops && (Universe::narrow_oop_shift() != 0));
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (DecodeN reg) off);
+
+  op_cost(10);
+  format %{"[R12 + $reg << 3 + $off] (compressed oop addressing)" %}
+  interface(MEMORY_INTER) %{
+    base(0xc); // R12
+    index($reg);
+    scale(0x3);
+    disp($off);
+  %}
+%}
+
+// Indirect Memory Operand
+operand indirectNarrow(rRegN reg)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(DecodeN reg);
+
+  format %{ "[$reg]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index(0x4);
+    scale(0x0);
+    disp(0x0);
+  %}
+%}
+
+// Indirect Memory Plus Short Offset Operand
+operand indOffset8Narrow(rRegN reg, immL8 off)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (DecodeN reg) off);
+
+  format %{ "[$reg + $off (8-bit)]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index(0x4);
+    scale(0x0);
+    disp($off);
+  %}
+%}
+
+// Indirect Memory Plus Long Offset Operand
+operand indOffset32Narrow(rRegN reg, immL32 off)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (DecodeN reg) off);
+
+  format %{ "[$reg + $off (32-bit)]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index(0x4);
+    scale(0x0);
+    disp($off);
+  %}
+%}
+
+// Indirect Memory Plus Index Register Plus Offset Operand
+operand indIndexOffsetNarrow(rRegN reg, rRegL lreg, immL32 off)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (AddP (DecodeN reg) lreg) off);
+
+  op_cost(10);
+  format %{"[$reg + $off + $lreg]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index($lreg);
+    scale(0x0);
+    disp($off);
+  %}
+%}
+
+// Indirect Memory Plus Index Register Plus Offset Operand
+operand indIndexNarrow(rRegN reg, rRegL lreg)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (DecodeN reg) lreg);
+
+  op_cost(10);
+  format %{"[$reg + $lreg]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index($lreg);
+    scale(0x0);
+    disp(0x0);
+  %}
+%}
+
+// Indirect Memory Times Scale Plus Index Register
+operand indIndexScaleNarrow(rRegN reg, rRegL lreg, immI2 scale)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (DecodeN reg) (LShiftL lreg scale));
+
+  op_cost(10);
+  format %{"[$reg + $lreg << $scale]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index($lreg);
+    scale($scale);
+    disp(0x0);
+  %}
+%}
+
+// Indirect Memory Times Scale Plus Index Register Plus Offset Operand
+operand indIndexScaleOffsetNarrow(rRegN reg, immL32 off, rRegL lreg, immI2 scale)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  constraint(ALLOC_IN_RC(ptr_reg));
+  match(AddP (AddP (DecodeN reg) (LShiftL lreg scale)) off);
+
+  op_cost(10);
+  format %{"[$reg + $off + $lreg << $scale]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index($lreg);
+    scale($scale);
+    disp($off);
+  %}
+%}
+
+// Indirect Memory Times Scale Plus Positive Index Register Plus Offset Operand
+operand indPosIndexScaleOffsetNarrow(rRegN reg, immL32 off, rRegI idx, immI2 scale)
+%{
+  constraint(ALLOC_IN_RC(ptr_reg));
+  predicate(Universe::narrow_oop_shift() == 0 && n->in(2)->in(3)->in(1)->as_Type()->type()->is_long()->_lo >= 0);
+  match(AddP (AddP (DecodeN reg) (LShiftL (ConvI2L idx) scale)) off);
+
+  op_cost(10);
+  format %{"[$reg + $off + $idx << $scale]" %}
+  interface(MEMORY_INTER) %{
+    base($reg);
+    index($idx);
+    scale($scale);
+    disp($off);
+  %}
+%}
+
+
 //----------Special Memory Operands--------------------------------------------
 // Stack Slot Operand - This operand is used for loading and storing temporary
 //                      values on the stack where a match requires a value to
@@ -5483,14 +5833,17 @@
 
 //----------OPERAND CLASSES----------------------------------------------------
 // Operand Classes are groups of operands that are used as to simplify
-// instruction definitions by not requiring the AD writer to specify seperate
+// instruction definitions by not requiring the AD writer to specify separate
 // instructions for every form of operand when the instruction accepts
 // multiple operand types with the same basic encoding and format.  The classic
 // case of this is memory operands.
 
 opclass memory(indirect, indOffset8, indOffset32, indIndexOffset, indIndex,
                indIndexScale, indIndexScaleOffset, indPosIndexScaleOffset,
-               indNarrowOopOffset);
+               indCompressedOopOffset,
+               indirectNarrow, indOffset8Narrow, indOffset32Narrow,
+               indIndexOffsetNarrow, indIndexNarrow, indIndexScaleNarrow,
+               indIndexScaleOffsetNarrow, indPosIndexScaleOffsetNarrow);
 
 //----------PIPELINE-----------------------------------------------------------
 // Rules which define the behavior of the target architectures pipeline.
@@ -6031,70 +6384,88 @@
 
   ins_cost(125);
   format %{ "movsbl  $dst, $mem\t# byte" %}
-  opcode(0x0F, 0xBE);
-  ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movsbl($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem);
 %}
 
-// Load Byte (8 bit signed) into long
-// instruct loadB2L(rRegL dst, memory mem)
-// %{
-//   match(Set dst (ConvI2L (LoadB mem)));
-
-//   ins_cost(125);
-//   format %{ "movsbq  $dst, $mem\t# byte -> long" %}
-//   opcode(0x0F, 0xBE);
-//   ins_encode(REX_reg_mem_wide(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
-//   ins_pipe(ialu_reg_mem);
-// %}
-
-// Load Byte (8 bit UNsigned)
-instruct loadUB(rRegI dst, memory mem, immI_255 bytemask)
-%{
-  match(Set dst (AndI (LoadB mem) bytemask));
+// Load Byte (8 bit signed) into Long Register
+instruct loadB2L(rRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadB mem)));
+
+  ins_cost(125);
+  format %{ "movsbq  $dst, $mem\t# byte -> long" %}
+
+  ins_encode %{
+    __ movsbq($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Byte (8 bit UNsigned)
+instruct loadUB(rRegI dst, memory mem)
+%{
+  match(Set dst (LoadUB mem));
 
   ins_cost(125);
   format %{ "movzbl  $dst, $mem\t# ubyte" %}
-  opcode(0x0F, 0xB6);
-  ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movzbl($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem);
 %}
 
-// Load Byte (8 bit UNsigned) into long
-// instruct loadUB2L(rRegL dst, memory mem, immI_255 bytemask)
-// %{
-//   match(Set dst (ConvI2L (AndI (LoadB mem) bytemask)));
-
-//   ins_cost(125);
-//   format %{ "movzbl  $dst, $mem\t# ubyte -> long" %}
-//   opcode(0x0F, 0xB6);
-//   ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
-//   ins_pipe(ialu_reg_mem);
-// %}
+// Load Unsigned Byte (8 bit UNsigned) into Long Register
+instruct loadUB2L(rRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadUB mem)));
+
+  ins_cost(125);
+  format %{ "movzbq  $dst, $mem\t# ubyte -> long" %}
+
+  ins_encode %{
+    __ movzbq($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
 
 // Load Short (16 bit signed)
 instruct loadS(rRegI dst, memory mem)
 %{
   match(Set dst (LoadS mem));
 
-  ins_cost(125); // XXX
+  ins_cost(125);
   format %{ "movswl $dst, $mem\t# short" %}
-  opcode(0x0F, 0xBF);
-  ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movswl($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem);
 %}
 
-// Load Short (16 bit signed) into long
-// instruct loadS2L(rRegL dst, memory mem)
-// %{
-//   match(Set dst (ConvI2L (LoadS mem)));
-
-//   ins_cost(125); // XXX
-//   format %{ "movswq $dst, $mem\t# short -> long" %}
-//   opcode(0x0F, 0xBF);
-//   ins_encode(REX_reg_mem_wide(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
-//   ins_pipe(ialu_reg_mem);
-// %}
+// Load Short (16 bit signed) into Long Register
+instruct loadS2L(rRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadS mem)));
+
+  ins_cost(125);
+  format %{ "movswq $dst, $mem\t# short -> long" %}
+
+  ins_encode %{
+    __ movswq($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
 
 // Load Unsigned Short/Char (16 bit UNsigned)
 instruct loadUS(rRegI dst, memory mem)
@@ -6103,32 +6474,71 @@
 
   ins_cost(125);
   format %{ "movzwl  $dst, $mem\t# ushort/char" %}
-  opcode(0x0F, 0xB7);
-  ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movzwl($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem);
 %}
 
-// Load Unsigned Short/Char (16 bit UNsigned) into long
-// instruct loadUS2L(rRegL dst, memory mem)
-// %{
-//   match(Set dst (ConvI2L (LoadUS mem)));
-
-//   ins_cost(125);
-//   format %{ "movzwl  $dst, $mem\t# ushort/char -> long" %}
-//   opcode(0x0F, 0xB7);
-//   ins_encode(REX_reg_mem(dst, mem), OpcP, OpcS, reg_mem(dst, mem));
-//   ins_pipe(ialu_reg_mem);
-// %}
+// Load Unsigned Short/Char (16 bit UNsigned) into Long Register
+instruct loadUS2L(rRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadUS mem)));
+
+  ins_cost(125);
+  format %{ "movzwq  $dst, $mem\t# ushort/char -> long" %}
+
+  ins_encode %{
+    __ movzwq($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
 
 // Load Integer
 instruct loadI(rRegI dst, memory mem)
 %{
   match(Set dst (LoadI mem));
 
-  ins_cost(125); // XXX
+  ins_cost(125);
   format %{ "movl    $dst, $mem\t# int" %}
-  opcode(0x8B);
-  ins_encode(REX_reg_mem(dst, mem), OpcP, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movl($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Integer into Long Register
+instruct loadI2L(rRegL dst, memory mem)
+%{
+  match(Set dst (ConvI2L (LoadI mem)));
+
+  ins_cost(125);
+  format %{ "movslq  $dst, $mem\t# int -> long" %}
+
+  ins_encode %{
+    __ movslq($dst$$Register, $mem$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+// Load Unsigned Integer into Long Register
+instruct loadUI2L(rRegL dst, memory mem)
+%{
+  match(Set dst (LoadUI2L mem));
+
+  ins_cost(125);
+  format %{ "movl    $dst, $mem\t# uint -> long" %}
+
+  ins_encode %{
+    __ movl($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem);
 %}
 
@@ -6137,10 +6547,13 @@
 %{
   match(Set dst (LoadL mem));
 
-  ins_cost(125); // XXX
+  ins_cost(125);
   format %{ "movq    $dst, $mem\t# long" %}
-  opcode(0x8B);
-  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+
+  ins_encode %{
+    __ movq($dst$$Register, $mem$$Address);
+  %}
+
   ins_pipe(ialu_reg_mem); // XXX
 %}
 
@@ -6176,9 +6589,7 @@
    ins_cost(125); // XXX
    format %{ "movl    $dst, $mem\t# compressed ptr" %}
    ins_encode %{
-     Address addr = build_address($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-     Register dst = as_Register($dst$$reg);
-     __ movl(dst, addr);
+     __ movl($dst$$Register, $mem$$Address);
    %}
    ins_pipe(ialu_reg_mem); // XXX
 %}
@@ -6204,9 +6615,7 @@
   ins_cost(125); // XXX
   format %{ "movl    $dst, $mem\t# compressed klass ptr" %}
   ins_encode %{
-    Address addr = build_address($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    Register dst = as_Register($dst$$reg);
-    __ movl(dst, addr);
+    __ movl($dst$$Register, $mem$$Address);
   %}
   ins_pipe(ialu_reg_mem); // XXX
 %}
@@ -6360,6 +6769,102 @@
   ins_pipe(ialu_reg_reg_fat);
 %}
 
+instruct leaPPosIdxScaleOff(rRegP dst, indPosIndexScaleOffset mem)
+%{
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr posidxscaleoff" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+// Load Effective Address which uses Narrow (32-bits) oop
+instruct leaPCompressedOopOffset(rRegP dst, indCompressedOopOffset mem)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_shift() != 0));
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr compressedoopoff32" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaP8Narrow(rRegP dst, indOffset8Narrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110); // XXX
+  format %{ "leaq    $dst, $mem\t# ptr off8narrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaP32Narrow(rRegP dst, indOffset32Narrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr off32narrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaPIdxOffNarrow(rRegP dst, indIndexOffsetNarrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr idxoffnarrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaPIdxScaleNarrow(rRegP dst, indIndexScaleNarrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr idxscalenarrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaPIdxScaleOffNarrow(rRegP dst, indIndexScaleOffsetNarrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr idxscaleoffnarrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
+instruct leaPPosIdxScaleOffNarrow(rRegP dst, indPosIndexScaleOffsetNarrow mem)
+%{
+  predicate(Universe::narrow_oop_shift() == 0);
+  match(Set dst mem);
+
+  ins_cost(110);
+  format %{ "leaq    $dst, $mem\t# ptr posidxscaleoffnarrow" %}
+  opcode(0x8D);
+  ins_encode(REX_reg_mem_wide(dst, mem), OpcP, reg_mem(dst, mem));
+  ins_pipe(ialu_reg_reg_fat);
+%}
+
 instruct loadConI(rRegI dst, immI src)
 %{
   match(Set dst src);
@@ -6470,8 +6975,7 @@
   effect(KILL cr);
   format %{ "xorq    $dst, $src\t# compressed NULL ptr" %}
   ins_encode %{
-    Register dst = $dst$$Register;
-    __ xorq(dst, dst);
+    __ xorq($dst$$Register, $dst$$Register);
   %}
   ins_pipe(ialu_reg);
 %}
@@ -6483,11 +6987,10 @@
   format %{ "movl    $dst, $src\t# compressed ptr" %}
   ins_encode %{
     address con = (address)$src$$constant;
-    Register dst = $dst$$Register;
     if (con == NULL) {
       ShouldNotReachHere();
     } else {
-      __ set_narrow_oop(dst, (jobject)$src$$constant);
+      __ set_narrow_oop($dst$$Register, (jobject)$src$$constant);
     }
   %}
   ins_pipe(ialu_reg_fat); // XXX
@@ -6736,12 +7239,25 @@
   ins_pipe(ialu_mem_reg);
 %}
 
+instruct storeImmP0(memory mem, immP0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreP mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movq    $mem, R12\t# ptr (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movq($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 // Store NULL Pointer, mark word, or other simple pointer constant.
 instruct storeImmP(memory mem, immP31 src)
 %{
   match(Set mem (StoreP mem src));
 
-  ins_cost(125); // XXX
+  ins_cost(150); // XXX
   format %{ "movq    $mem, $src\t# ptr" %}
   opcode(0xC7); /* C7 /0 */
   ins_encode(REX_mem_wide(mem), OpcP, RM_opc_mem(0x00, mem), Con32(src));
@@ -6756,14 +7272,55 @@
   ins_cost(125); // XXX
   format %{ "movl    $mem, $src\t# compressed ptr" %}
   ins_encode %{
-    Address addr = build_address($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    Register src = as_Register($src$$reg);
-    __ movl(addr, src);
+    __ movl($mem$$Address, $src$$Register);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
+instruct storeImmN0(memory mem, immN0 zero)
+%{
+  predicate(Universe::narrow_oop_base() == NULL);
+  match(Set mem (StoreN mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movl    $mem, R12\t# compressed ptr (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movl($mem$$Address, r12);
   %}
   ins_pipe(ialu_mem_reg);
 %}
 
+instruct storeImmN(memory mem, immN src)
+%{
+  match(Set mem (StoreN mem src));
+
+  ins_cost(150); // XXX
+  format %{ "movl    $mem, $src\t# compressed ptr" %}
+  ins_encode %{
+    address con = (address)$src$$constant;
+    if (con == NULL) {
+      __ movl($mem$$Address, (int32_t)0);
+    } else {
+      __ set_narrow_oop($mem$$Address, (jobject)$src$$constant);
+    }
+  %}
+  ins_pipe(ialu_mem_imm);
+%}
+
 // Store Integer Immediate
+instruct storeImmI0(memory mem, immI0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreI mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movl    $mem, R12\t# int (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movl($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeImmI(memory mem, immI src)
 %{
   match(Set mem (StoreI mem src));
@@ -6776,6 +7333,19 @@
 %}
 
 // Store Long Immediate
+instruct storeImmL0(memory mem, immL0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreL mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movq    $mem, R12\t# long (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movq($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeImmL(memory mem, immL32 src)
 %{
   match(Set mem (StoreL mem src));
@@ -6788,6 +7358,19 @@
 %}
 
 // Store Short/Char Immediate
+instruct storeImmC0(memory mem, immI0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreC mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movw    $mem, R12\t# short/char (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movw($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeImmI16(memory mem, immI16 src)
 %{
   predicate(UseStoreImmI16);
@@ -6801,6 +7384,19 @@
 %}
 
 // Store Byte Immediate
+instruct storeImmB0(memory mem, immI0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreB mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movb    $mem, R12\t# short/char (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movb($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeImmB(memory mem, immI8 src)
 %{
   match(Set mem (StoreB mem src));
@@ -6840,6 +7436,19 @@
 %}
 
 // Store CMS card-mark Immediate
+instruct storeImmCM0_reg(memory mem, immI0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreCM mem zero));
+
+  ins_cost(125); // XXX
+  format %{ "movb    $mem, R12\t# CMS card-mark byte 0 (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movb($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeImmCM0(memory mem, immI0 src)
 %{
   match(Set mem (StoreCM mem src));
@@ -6873,6 +7482,19 @@
 %}
 
 // Store immediate Float value (it is faster than store from XMM register)
+instruct storeF0(memory mem, immF0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreF mem zero));
+
+  ins_cost(25); // XXX
+  format %{ "movl    $mem, R12\t# float 0. (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movl($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeF_imm(memory mem, immF src)
 %{
   match(Set mem (StoreF mem src));
@@ -6899,6 +7521,7 @@
 // Store immediate double 0.0 (it is faster than store from XMM register)
 instruct storeD0_imm(memory mem, immD0 src)
 %{
+  predicate(!UseCompressedOops || (Universe::narrow_oop_base() != NULL));
   match(Set mem (StoreD mem src));
 
   ins_cost(50);
@@ -6908,6 +7531,19 @@
   ins_pipe(ialu_mem_imm);
 %}
 
+instruct storeD0(memory mem, immD0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set mem (StoreD mem zero));
+
+  ins_cost(25); // XXX
+  format %{ "movq    $mem, R12\t# double 0. (R12_heapbase==0)" %}
+  ins_encode %{
+    __ movq($mem$$Address, r12);
+  %}
+  ins_pipe(ialu_mem_reg);
+%}
+
 instruct storeSSI(stackSlotI dst, rRegI src)
 %{
   match(Set dst src);
@@ -7019,6 +7655,56 @@
   ins_pipe( ialu_mem_reg );
 %}
 
+
+//---------- Population Count Instructions -------------------------------------
+
+instruct popCountI(rRegI dst, rRegI src) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountI src));
+
+  format %{ "popcnt  $dst, $src" %}
+  ins_encode %{
+    __ popcntl($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct popCountI_mem(rRegI dst, memory mem) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountI (LoadI mem)));
+
+  format %{ "popcnt  $dst, $mem" %}
+  ins_encode %{
+    __ popcntl($dst$$Register, $mem$$Address);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+// Note: Long.bitCount(long) returns an int.
+instruct popCountL(rRegI dst, rRegL src) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountL src));
+
+  format %{ "popcnt  $dst, $src" %}
+  ins_encode %{
+    __ popcntq($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+// Note: Long.bitCount(long) returns an int.
+instruct popCountL_mem(rRegI dst, memory mem) %{
+  predicate(UsePopCountInstruction);
+  match(Set dst (PopCountL (LoadL mem)));
+
+  format %{ "popcnt  $dst, $mem" %}
+  ins_encode %{
+    __ popcntq($dst$$Register, $mem$$Address);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+
 //----------MemBar Instructions-----------------------------------------------
 // Memory barrier flavors
 
@@ -7028,7 +7714,7 @@
   ins_cost(0);
 
   size(0);
-  format %{ "MEMBAR-acquire" %}
+  format %{ "MEMBAR-acquire ! (empty encoding)" %}
   ins_encode();
   ins_pipe(empty);
 %}
@@ -7051,7 +7737,7 @@
   ins_cost(0);
 
   size(0);
-  format %{ "MEMBAR-release" %}
+  format %{ "MEMBAR-release ! (empty encoding)" %}
   ins_encode();
   ins_pipe(empty);
 %}
@@ -7068,13 +7754,22 @@
   ins_pipe(empty);
 %}
 
-instruct membar_volatile()
-%{
+instruct membar_volatile(rFlagsReg cr) %{
   match(MemBarVolatile);
+  effect(KILL cr);
   ins_cost(400);
 
-  format %{ "MEMBAR-volatile" %}
-  ins_encode(enc_membar_volatile);
+  format %{ 
+    $$template
+    if (os::is_MP()) {
+      $$emit$$"lock addl [rsp + #0], 0\t! membar_volatile"
+    } else {
+      $$emit$$"MEMBAR-volatile ! (empty encoding)"
+    }
+  %}
+  ins_encode %{
+    __ membar(Assembler::StoreLoad);
+  %}
   ins_pipe(pipe_slow);
 %}
 
@@ -7134,9 +7829,7 @@
   effect(KILL cr);
   format %{ "encode_heap_oop_not_null $dst,$src" %}
   ins_encode %{
-    Register s = $src$$Register;
-    Register d = $dst$$Register;
-    __ encode_heap_oop_not_null(d, s);
+    __ encode_heap_oop_not_null($dst$$Register, $src$$Register);
   %}
   ins_pipe(ialu_reg_long);
 %}
@@ -7166,7 +7859,11 @@
   ins_encode %{
     Register s = $src$$Register;
     Register d = $dst$$Register;
-    __ decode_heap_oop_not_null(d, s);
+    if (s != d) {
+      __ decode_heap_oop_not_null(d, s);
+    } else {
+      __ decode_heap_oop_not_null(d);
+    }
   %}
   ins_pipe(ialu_reg_long);
 %}
@@ -8363,7 +9060,7 @@
 //----------- DivL-By-Constant-Expansions--------------------------------------
 // DivI cases are handled by the compiler
 
-// Magic constant, reciprical of 10
+// Magic constant, reciprocal of 10
 instruct loadConL_0x6666666666666667(rRegL dst)
 %{
   effect(DEF dst);
@@ -10804,16 +11501,6 @@
 //   ins_pipe(ialu_reg_reg);
 // %}
 
-instruct convI2L_reg_mem(rRegL dst, memory src)
-%{
-  match(Set dst (ConvI2L (LoadI src)));
-
-  format %{ "movslq  $dst, $src\t# i2l" %}
-  opcode(0x63); // needs REX.W
-  ins_encode(REX_reg_mem_wide(dst, src), OpcP, reg_mem(dst,src));
-  ins_pipe(ialu_reg_mem);
-%}
-
 // Zero-extend convert int to long
 instruct convI2L_reg_reg_zex(rRegL dst, rRegI src, immL_32bits mask)
 %{
@@ -11136,27 +11823,52 @@
   ins_pipe(pipe_slow);
 %}
 
-instruct string_compare(rdi_RegP str1, rsi_RegP str2, rax_RegI tmp1,
-                        rbx_RegI tmp2, rcx_RegI result, rFlagsReg cr)
+instruct string_compare(rdi_RegP str1, rsi_RegP str2, regD tmp1, regD tmp2,
+                        rax_RegI tmp3, rbx_RegI tmp4, rcx_RegI result, rFlagsReg cr)
 %{
   match(Set result (StrComp str1 str2));
-  effect(USE_KILL str1, USE_KILL str2, KILL tmp1, KILL tmp2, KILL cr);
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL str1, USE_KILL str2, KILL tmp3, KILL tmp4, KILL cr);
   //ins_cost(300);
 
   format %{ "String Compare $str1, $str2 -> $result    // XXX KILL RAX, RBX" %}
-  ins_encode( enc_String_Compare() );
+  ins_encode( enc_String_Compare(str1, str2, tmp1, tmp2, tmp3, tmp4, result) );
+  ins_pipe( pipe_slow );
+%}
+
+instruct string_indexof(rsi_RegP str1, rdi_RegP str2, regD tmp1, rax_RegI tmp2,
+                        rcx_RegI tmp3, rdx_RegI tmp4, rbx_RegI result, rFlagsReg cr)
+%{
+  predicate(UseSSE42Intrinsics);
+  match(Set result (StrIndexOf str1 str2));
+  effect(TEMP tmp1, USE_KILL str1, USE_KILL str2, KILL tmp2, KILL tmp3, KILL tmp4, KILL cr);
+
+  format %{ "String IndexOf $str1,$str2 -> $result   // KILL RAX, RCX, RDX" %}
+  ins_encode( enc_String_IndexOf(str1, str2, tmp1, tmp2, tmp3, tmp4, result) );
+  ins_pipe( pipe_slow );
+%}
+
+// fast string equals
+instruct string_equals(rdi_RegP str1, rsi_RegP str2, regD tmp1, regD tmp2, rbx_RegI tmp3,
+                       rcx_RegI tmp4, rax_RegI result, rFlagsReg cr)
+%{
+  match(Set result (StrEquals str1 str2));
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL str1, USE_KILL str2, KILL tmp3, KILL tmp4, KILL cr);
+
+  format %{ "String Equals $str1,$str2 -> $result    // KILL RBX, RCX" %}
+  ins_encode( enc_String_Equals(str1, str2, tmp1, tmp2, tmp3, tmp4, result) );
   ins_pipe( pipe_slow );
 %}
 
 // fast array equals
-instruct array_equals(rdi_RegP ary1, rsi_RegP ary2, rax_RegI tmp1, 
-                      rbx_RegI tmp2, rcx_RegI result, rFlagsReg cr) %{
+instruct array_equals(rdi_RegP ary1, rsi_RegP ary2, regD tmp1, regD tmp2, rax_RegI tmp3,
+                      rbx_RegI tmp4, rcx_RegI result, rFlagsReg cr)
+%{
   match(Set result (AryEq ary1 ary2));
-  effect(USE_KILL ary1, USE_KILL ary2, KILL tmp1, KILL tmp2, KILL cr);
+  effect(TEMP tmp1, TEMP tmp2, USE_KILL ary1, USE_KILL ary2, KILL tmp3, KILL tmp4, KILL cr);
   //ins_cost(300);
 
-  format %{ "Array Equals $ary1,$ary2 -> $result    // KILL RAX, RBX" %}
-  ins_encode( enc_Array_Equals(ary1, ary2, tmp1, tmp2, result) );
+  format %{ "Array Equals $ary1,$ary2 -> $result   // KILL RAX, RBX" %}
+  ins_encode( enc_Array_Equals(ary1, ary2, tmp1, tmp2, tmp3, tmp4, result) );
   ins_pipe( pipe_slow );
 %}
 
@@ -11341,8 +12053,9 @@
 
 // This will generate a signed flags result. This should be OK since
 // any compare to a zero should be eq/neq.
-instruct testP_reg_mem(rFlagsReg cr, memory op, immP0 zero)
-%{
+instruct testP_mem(rFlagsReg cr, memory op, immP0 zero)
+%{
+  predicate(!UseCompressedOops || (Universe::narrow_oop_base() != NULL));
   match(Set cr (CmpP (LoadP op) zero));
 
   ins_cost(500); // XXX
@@ -11353,13 +12066,24 @@
   ins_pipe(ialu_cr_reg_imm);
 %}
 
+instruct testP_mem_reg0(rFlagsReg cr, memory mem, immP0 zero)
+%{
+  predicate(UseCompressedOops && (Universe::narrow_oop_base() == NULL));
+  match(Set cr (CmpP (LoadP mem) zero));
+
+  format %{ "cmpq    R12, $mem\t# ptr (R12_heapbase==0)" %}
+  ins_encode %{
+    __ cmpq(r12, $mem$$Address);
+  %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
 
 instruct compN_rReg(rFlagsRegU cr, rRegN op1, rRegN op2)
 %{
   match(Set cr (CmpN op1 op2));
 
   format %{ "cmpl    $op1, $op2\t# compressed ptr" %}
-  ins_encode %{ __ cmpl(as_Register($op1$$reg), as_Register($op2$$reg)); %}
+  ins_encode %{ __ cmpl($op1$$Register, $op2$$Register); %}
   ins_pipe(ialu_cr_reg_reg);
 %}
 
@@ -11367,11 +12091,30 @@
 %{
   match(Set cr (CmpN src (LoadN mem)));
 
-  ins_cost(500); // XXX
-  format %{ "cmpl    $src, mem\t# compressed ptr" %}
+  format %{ "cmpl    $src, $mem\t# compressed ptr" %}
+  ins_encode %{
+    __ cmpl($src$$Register, $mem$$Address);
+  %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
+instruct compN_rReg_imm(rFlagsRegU cr, rRegN op1, immN op2) %{
+  match(Set cr (CmpN op1 op2));
+
+  format %{ "cmpl    $op1, $op2\t# compressed ptr" %}
   ins_encode %{
-    Address adr = build_address($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ cmpl(as_Register($src$$reg), adr);
+    __ cmp_narrow_oop($op1$$Register, (jobject)$op2$$constant);
+  %}
+  ins_pipe(ialu_cr_reg_imm);
+%}
+
+instruct compN_mem_imm(rFlagsRegU cr, memory mem, immN src)
+%{
+  match(Set cr (CmpN src (LoadN mem)));
+
+  format %{ "cmpl    $mem, $src\t# compressed ptr" %}
+  ins_encode %{
+    __ cmp_narrow_oop($mem$$Address, (jobject)$src$$constant);
   %}
   ins_pipe(ialu_cr_reg_mem);
 %}
@@ -11384,15 +12127,27 @@
   ins_pipe(ialu_cr_reg_imm);
 %}
 
-instruct testN_reg_mem(rFlagsReg cr, memory mem, immN0 zero)
-%{
+instruct testN_mem(rFlagsReg cr, memory mem, immN0 zero)
+%{
+  predicate(Universe::narrow_oop_base() != NULL);
   match(Set cr (CmpN (LoadN mem) zero));
 
   ins_cost(500); // XXX
   format %{ "testl   $mem, 0xffffffff\t# compressed ptr" %}
   ins_encode %{
-    Address addr = build_address($mem$$base, $mem$$index, $mem$$scale, $mem$$disp);
-    __ cmpl(addr, (int)0xFFFFFFFF);
+    __ cmpl($mem$$Address, (int)0xFFFFFFFF);
+  %}
+  ins_pipe(ialu_cr_reg_mem);
+%}
+
+instruct testN_mem_reg0(rFlagsReg cr, memory mem, immN0 zero)
+%{
+  predicate(Universe::narrow_oop_base() == NULL);
+  match(Set cr (CmpN (LoadN mem) zero));
+
+  format %{ "cmpl    R12, $mem\t# compressed ptr (R12_heapbase==0)" %}
+  ins_encode %{
+    __ cmpl(r12, $mem$$Address);
   %}
   ins_pipe(ialu_cr_reg_mem);
 %}
@@ -11424,7 +12179,6 @@
 %{
   match(Set cr (CmpL op1 (LoadL op2)));
 
-  ins_cost(500); // XXX
   format %{ "cmpq    $op1, $op2" %}
   opcode(0x3B); /* Opcode 3B /r */
   ins_encode(REX_reg_mem_wide(op1, op2), OpcP, reg_mem(op1, op2));
@@ -11685,15 +12439,12 @@
   effect(KILL rcx, KILL cr);
 
   ins_cost(1100);  // slightly larger than the next version
-  format %{ "cmpq    rax, rsi\n\t"
-            "jeq,s   hit\n\t"
-            "movq    rdi, [$sub + (sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes())]\n\t"
+  format %{ "movq    rdi, [$sub + (sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes())]\n\t"
             "movl    rcx, [rdi + arrayOopDesc::length_offset_in_bytes()]\t# length to scan\n\t"
             "addq    rdi, arrayOopDex::base_offset_in_bytes(T_OBJECT)\t# Skip to start of data; set NZ in case count is zero\n\t"
             "repne   scasq\t# Scan *rdi++ for a match with rax while rcx--\n\t"
             "jne,s   miss\t\t# Missed: rdi not-zero\n\t"
             "movq    [$sub + (sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes())], $super\t# Hit: update cache\n\t"
-    "hit:\n\t"
             "xorq    $result, $result\t\t Hit: rdi zero\n\t"
     "miss:\t" %}
 
@@ -11708,13 +12459,10 @@
                                      rdi_RegP result)
 %{
   match(Set cr (CmpP (PartialSubtypeCheck sub super) zero));
-  predicate(!UseCompressedOops); // decoding oop kills condition codes
   effect(KILL rcx, KILL result);
 
   ins_cost(1000);
-  format %{ "cmpq    rax, rsi\n\t"
-            "jeq,s   miss\t# Actually a hit; we are done.\n\t"
-            "movq    rdi, [$sub + (sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes())]\n\t"
+  format %{ "movq    rdi, [$sub + (sizeof(oopDesc) + Klass::secondary_supers_offset_in_bytes())]\n\t"
             "movl    rcx, [rdi + arrayOopDesc::length_offset_in_bytes()]\t# length to scan\n\t"
             "addq    rdi, arrayOopDex::base_offset_in_bytes(T_OBJECT)\t# Skip to start of data; set NZ in case count is zero\n\t"
             "repne   scasq\t# Scan *rdi++ for a match with rax while cx-- != 0\n\t"
@@ -12082,7 +12830,7 @@
 // These must follow all instruction definitions as they use the names
 // defined in the instructions definitions.
 //
-// peepmatch ( root_instr_name [precerding_instruction]* );
+// peepmatch ( root_instr_name [preceding_instruction]* );
 //
 // peepconstraint %{
 // (instruction_number.operand_name relational_op instruction_number.operand_name
--- a/hotspot/src/os/linux/launcher/java.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/linux/launcher/java.c	Fri Apr 10 13:05:12 2009 -0700
@@ -419,7 +419,7 @@
             goto leave;
         }
         mainClass = LoadClass(env, classname);
-        if(mainClass == NULL) { /* exception occured */
+        if(mainClass == NULL) { /* exception occurred */
             ReportExceptionDescription(env);
             message = "Could not find the main class.  Program will exit.";
             goto leave;
@@ -441,7 +441,7 @@
         goto leave;
       }
       mainClass = LoadClass(env, classname);
-      if(mainClass == NULL) { /* exception occured */
+      if(mainClass == NULL) { /* exception occurred */
         ReportExceptionDescription(env);
         message = "Could not find the main class. Program will exit.";
         goto leave;
--- a/hotspot/src/os/linux/launcher/java_md.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/linux/launcher/java_md.h	Fri Apr 10 13:05:12 2009 -0700
@@ -47,7 +47,7 @@
 #ifdef JAVA_ARGS
 /*
  * ApplicationHome is prepended to each of these entries; the resulting
- * strings are concatenated (seperated by PATH_SEPARATOR) and used as the
+ * strings are concatenated (separated by PATH_SEPARATOR) and used as the
  * value of -cp option to the launcher.
  */
 #ifndef APP_CLASSPATH
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1518,21 +1518,51 @@
 
 const char* os::get_temp_directory() { return "/tmp/"; }
 
-void os::dll_build_name(
-    char* buffer, size_t buflen, const char* pname, const char* fname) {
-  // copied from libhpi
+static bool file_exists(const char* filename) {
+  struct stat statbuf;
+  if (filename == NULL || strlen(filename) == 0) {
+    return false;
+  }
+  return os::stat(filename, &statbuf) == 0;
+}
+
+void os::dll_build_name(char* buffer, size_t buflen,
+                        const char* pname, const char* fname) {
+  // Copied from libhpi
   const size_t pnamelen = pname ? strlen(pname) : 0;
 
-  /* Quietly truncate on buffer overflow.  Should be an error. */
+  // Quietly truncate on buffer overflow.  Should be an error.
   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
       *buffer = '\0';
       return;
   }
 
   if (pnamelen == 0) {
-      sprintf(buffer, "lib%s.so", fname);
+    snprintf(buffer, buflen, "lib%s.so", fname);
+  } else if (strchr(pname, *os::path_separator()) != NULL) {
+    int n;
+    char** pelements = split_path(pname, &n);
+    for (int i = 0 ; i < n ; i++) {
+      // Really shouldn't be NULL, but check can't hurt
+      if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
+        continue; // skip the empty path values
+      }
+      snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
+      if (file_exists(buffer)) {
+        break;
+      }
+    }
+    // release the storage
+    for (int i = 0 ; i < n ; i++) {
+      if (pelements[i] != NULL) {
+        FREE_C_HEAP_ARRAY(char, pelements[i]);
+      }
+    }
+    if (pelements != NULL) {
+      FREE_C_HEAP_ARRAY(char*, pelements);
+    }
   } else {
-      sprintf(buffer, "%s/lib%s.so", pname, fname);
+    snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
   }
 }
 
@@ -2269,15 +2299,16 @@
 //       All it does is to check if there are enough free pages
 //       left at the time of mmap(). This could be a potential
 //       problem.
-bool os::commit_memory(char* addr, size_t size) {
-  uintptr_t res = (uintptr_t) ::mmap(addr, size,
-                                   PROT_READ|PROT_WRITE|PROT_EXEC,
+bool os::commit_memory(char* addr, size_t size, bool exec) {
+  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
+  uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
   return res != (uintptr_t) MAP_FAILED;
 }
 
-bool os::commit_memory(char* addr, size_t size, size_t alignment_hint) {
-  return commit_memory(addr, size);
+bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
+                       bool exec) {
+  return commit_memory(addr, size, exec);
 }
 
 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { }
@@ -2417,8 +2448,7 @@
 unsigned long* os::Linux::_numa_all_nodes;
 
 bool os::uncommit_memory(char* addr, size_t size) {
-  return ::mmap(addr, size,
-                PROT_READ|PROT_WRITE|PROT_EXEC,
+  return ::mmap(addr, size, PROT_NONE,
                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0)
     != MAP_FAILED;
 }
@@ -2441,7 +2471,9 @@
     flags |= MAP_FIXED;
   }
 
-  addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE|PROT_EXEC,
+  // Map uncommitted pages PROT_READ and PROT_WRITE, change access
+  // to PROT_EXEC if executable when we commit the page.
+  addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE,
                        flags, -1, 0);
 
   if (addr != MAP_FAILED) {
@@ -2582,7 +2614,9 @@
 #define SHM_HUGETLB 04000
 #endif
 
-char* os::reserve_memory_special(size_t bytes) {
+char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) {
+  // "exec" is passed in but not used.  Creating the shared image for
+  // the code cache doesn't have an SHM_X executable permission to check.
   assert(UseLargePages, "only for large pages");
 
   key_t key = IPC_PRIVATE;
--- a/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -192,7 +192,7 @@
 // check if the given path is considered a secure directory for
 // the backing store files. Returns true if the directory exists
 // and is considered a secure location. Returns false if the path
-// is a symbolic link or if an error occured.
+// is a symbolic link or if an error occurred.
 //
 static bool is_directory_secure(const char* path) {
   struct stat statbuf;
--- a/hotspot/src/os/solaris/dtrace/generateJvmOffsets.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/dtrace/generateJvmOffsets.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -249,6 +249,10 @@
 
   printf("\n");
 
+  GEN_OFFS(NarrowOopStruct, _base);
+  GEN_OFFS(NarrowOopStruct, _shift);
+  printf("\n");
+
   GEN_VALUE(SIZE_HeapBlockHeader, sizeof(HeapBlock::Header));
   GEN_SIZE(oopDesc);
   GEN_SIZE(constantPoolOopDesc);
--- a/hotspot/src/os/solaris/dtrace/jhelper.d	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/dtrace/jhelper.d	Fri Apr 10 13:05:12 2009 -0700
@@ -46,7 +46,10 @@
 extern pointer __1cJCodeCacheF_heap_;
 extern pointer __1cIUniverseP_methodKlassObj_;
 extern pointer __1cIUniverseO_collectedHeap_;
-extern pointer __1cIUniverseK_heap_base_;
+extern pointer __1cIUniverseL_narrow_oop_;
+#ifdef _LP64
+extern pointer UseCompressedOops;
+#endif
 
 extern pointer __1cHnmethodG__vtbl_;
 extern pointer __1cKBufferBlobG__vtbl_;
@@ -56,6 +59,7 @@
 #define copyin_uint16(ADDR) *(uint16_t*) copyin((pointer) (ADDR), sizeof(uint16_t))
 #define copyin_uint32(ADDR) *(uint32_t*) copyin((pointer) (ADDR), sizeof(uint32_t))
 #define copyin_int32(ADDR)  *(int32_t*)  copyin((pointer) (ADDR), sizeof(int32_t))
+#define copyin_uint8(ADDR)  *(uint8_t*)  copyin((pointer) (ADDR), sizeof(uint8_t))
 
 #define SAME(x) x
 #define copyin_offset(JVM_CONST)  JVM_CONST = \
@@ -132,6 +136,9 @@
   copyin_offset(SIZE_oopDesc);
   copyin_offset(SIZE_constantPoolOopDesc);
 
+  copyin_offset(OFFSET_NarrowOopStruct_base);
+  copyin_offset(OFFSET_NarrowOopStruct_shift);
+
   /*
    * The PC to translate is in arg0.
    */
@@ -151,9 +158,19 @@
 
   this->Universe_methodKlassOop = copyin_ptr(&``__1cIUniverseP_methodKlassObj_);
   this->CodeCache_heap_address = copyin_ptr(&``__1cJCodeCacheF_heap_);
-  this->Universe_heap_base = copyin_ptr(&``__1cIUniverseK_heap_base_);
 
   /* Reading volatile values */
+#ifdef _LP64
+  this->Use_Compressed_Oops  = copyin_uint8(&``UseCompressedOops);
+#else
+  this->Use_Compressed_Oops  = 0;
+#endif
+
+  this->Universe_narrow_oop_base  = copyin_ptr(&``__1cIUniverseL_narrow_oop_ +
+                                               OFFSET_NarrowOopStruct_base);
+  this->Universe_narrow_oop_shift = copyin_int32(&``__1cIUniverseL_narrow_oop_ +
+                                                 OFFSET_NarrowOopStruct_shift);
+
   this->CodeCache_low = copyin_ptr(this->CodeCache_heap_address + 
       OFFSET_CodeHeap_memory + OFFSET_VirtualSpace_low);
 
@@ -295,7 +312,7 @@
 
 dtrace:helper:ustack:
 /!this->done && this->vtbl == this->BufferBlob_vtbl &&
-this->Universe_heap_base == NULL &&
+this->Use_Compressed_Oops == 0 &&
 this->methodOopPtr > this->heap_start && this->methodOopPtr < this->heap_end/
 {
   MARK_LINE;
@@ -306,7 +323,7 @@
 
 dtrace:helper:ustack:
 /!this->done && this->vtbl == this->BufferBlob_vtbl &&
-this->Universe_heap_base != NULL &&
+this->Use_Compressed_Oops != 0 &&
 this->methodOopPtr > this->heap_start && this->methodOopPtr < this->heap_end/
 {
   MARK_LINE;
@@ -314,8 +331,8 @@
    * Read compressed pointer and  decode heap oop, same as oop.inline.hpp
    */
   this->cklass = copyin_uint32(this->methodOopPtr + OFFSET_oopDesc_metadata);
-  this->klass = (uint64_t)((uintptr_t)this->Universe_heap_base +
-                ((uintptr_t)this->cklass << 3));
+  this->klass = (uint64_t)((uintptr_t)this->Universe_narrow_oop_base +
+                ((uintptr_t)this->cklass << this->Universe_narrow_oop_shift));
   this->methodOop = this->klass == this->Universe_methodKlassOop;
   this->done = !this->methodOop;
 }
--- a/hotspot/src/os/solaris/dtrace/libjvm_db.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/dtrace/libjvm_db.c	Fri Apr 10 13:05:12 2009 -0700
@@ -146,13 +146,17 @@
   uint64_t BufferBlob_vtbl;
   uint64_t RuntimeStub_vtbl;
 
+  uint64_t Use_Compressed_Oops_address;
   uint64_t Universe_methodKlassObj_address;
+  uint64_t Universe_narrow_oop_base_address;
+  uint64_t Universe_narrow_oop_shift_address;
   uint64_t CodeCache_heap_address;
-  uint64_t Universe_heap_base_address;
 
   /* Volatiles */
+  uint8_t  Use_Compressed_Oops;
   uint64_t Universe_methodKlassObj;
-  uint64_t Universe_heap_base;
+  uint64_t Universe_narrow_oop_base;
+  uint32_t Universe_narrow_oop_shift;
   uint64_t CodeCache_low;
   uint64_t CodeCache_high;
   uint64_t CodeCache_segmap_low;
@@ -279,8 +283,11 @@
       if (strcmp("_methodKlassObj", vmp->fieldName) == 0) {
         J->Universe_methodKlassObj_address = vmp->address;
       }
-      if (strcmp("_heap_base", vmp->fieldName) == 0) {
-        J->Universe_heap_base_address = vmp->address;
+      if (strcmp("_narrow_oop._base", vmp->fieldName) == 0) {
+        J->Universe_narrow_oop_base_address = vmp->address;
+      }
+      if (strcmp("_narrow_oop._shift", vmp->fieldName) == 0) {
+        J->Universe_narrow_oop_shift_address = vmp->address;
       }
     }
     CHECK_FAIL(err);
@@ -298,14 +305,39 @@
   return -1;
 }
 
+static int find_symbol(jvm_agent_t* J, const char *name, uint64_t* valuep) {
+  psaddr_t sym_addr;
+  int err;
+
+  err = ps_pglobal_lookup(J->P, LIBJVM_SO, name, &sym_addr);
+  if (err != PS_OK) goto fail;
+  *valuep = sym_addr;
+  return PS_OK;
+
+ fail:
+  return err;
+}
+
 static int read_volatiles(jvm_agent_t* J) {
   uint64_t ptr;
   int err;
 
+  err = find_symbol(J, "UseCompressedOops", &J->Use_Compressed_Oops_address);
+  if (err == PS_OK) {
+    err = ps_pread(J->P,  J->Use_Compressed_Oops_address, &J->Use_Compressed_Oops, sizeof(uint8_t));
+    CHECK_FAIL(err);
+  } else {
+    J->Use_Compressed_Oops = 0;
+  }
+
   err = read_pointer(J, J->Universe_methodKlassObj_address, &J->Universe_methodKlassObj);
   CHECK_FAIL(err);
-  err = read_pointer(J, J->Universe_heap_base_address, &J->Universe_heap_base);
+
+  err = read_pointer(J, J->Universe_narrow_oop_base_address, &J->Universe_narrow_oop_base);
   CHECK_FAIL(err);
+  err = ps_pread(J->P,  J->Universe_narrow_oop_shift_address, &J->Universe_narrow_oop_shift, sizeof(uint32_t));
+  CHECK_FAIL(err);
+
   err = read_pointer(J, J->CodeCache_heap_address + OFFSET_CodeHeap_memory +
                      OFFSET_VirtualSpace_low, &J->CodeCache_low);
   CHECK_FAIL(err);
@@ -374,19 +406,6 @@
   return -1;
 }
 
-static int find_symbol(jvm_agent_t* J, const char *name, uint64_t* valuep) {
-  psaddr_t sym_addr;
-  int err;
-
-  err = ps_pglobal_lookup(J->P, LIBJVM_SO, name, &sym_addr);
-  if (err != PS_OK) goto fail;
-  *valuep = sym_addr;
-  return PS_OK;
-
- fail:
-  return err;
-}
-
 static int find_jlong_constant(jvm_agent_t* J, const char *name, uint64_t* valuep) {
   psaddr_t sym_addr;
   int err = ps_pglobal_lookup(J->P, LIBJVM_SO, name, &sym_addr);
@@ -458,14 +477,14 @@
 static int is_methodOop(jvm_agent_t* J, uint64_t methodOopPtr) {
   uint64_t klass;
   int err;
-  // If heap_base is nonnull, this was a compressed oop.
-  if (J->Universe_heap_base != NULL) {
+  // If UseCompressedOops, this was a compressed oop.
+  if (J->Use_Compressed_Oops != 0) {
     uint32_t cklass;
     err = read_compressed_pointer(J, methodOopPtr + OFFSET_oopDesc_metadata,
           &cklass);
     // decode heap oop, same as oop.inline.hpp
-    klass = (uint64_t)((uintptr_t)J->Universe_heap_base +
-            ((uintptr_t)cklass << 3));
+    klass = (uint64_t)((uintptr_t)J->Universe_narrow_oop_base +
+            ((uintptr_t)cklass << J->Universe_narrow_oop_shift));
   } else {
     err = read_pointer(J, methodOopPtr + OFFSET_oopDesc_metadata, &klass);
   }
--- a/hotspot/src/os/solaris/launcher/java.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/launcher/java.c	Fri Apr 10 13:05:12 2009 -0700
@@ -419,7 +419,7 @@
             goto leave;
         }
         mainClass = LoadClass(env, classname);
-        if(mainClass == NULL) { /* exception occured */
+        if(mainClass == NULL) { /* exception occurred */
             ReportExceptionDescription(env);
             message = "Could not find the main class.  Program will exit.";
             goto leave;
@@ -441,7 +441,7 @@
         goto leave;
       }
       mainClass = LoadClass(env, classname);
-      if(mainClass == NULL) { /* exception occured */
+      if(mainClass == NULL) { /* exception occurred */
         ReportExceptionDescription(env);
         message = "Could not find the main class. Program will exit.";
         goto leave;
--- a/hotspot/src/os/solaris/launcher/java_md.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/launcher/java_md.h	Fri Apr 10 13:05:12 2009 -0700
@@ -47,7 +47,7 @@
 #ifdef JAVA_ARGS
 /*
  * ApplicationHome is prepended to each of these entries; the resulting
- * strings are concatenated (seperated by PATH_SEPARATOR) and used as the
+ * strings are concatenated (separated by PATH_SEPARATOR) and used as the
  * value of -cp option to the launcher.
  */
 #ifndef APP_CLASSPATH
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1827,21 +1827,51 @@
 
 const char* os::get_temp_directory() { return "/tmp/"; }
 
-void os::dll_build_name(
-    char* buffer, size_t buflen, const char* pname, const char* fname) {
-  // copied from libhpi
+static bool file_exists(const char* filename) {
+  struct stat statbuf;
+  if (filename == NULL || strlen(filename) == 0) {
+    return false;
+  }
+  return os::stat(filename, &statbuf) == 0;
+}
+
+void os::dll_build_name(char* buffer, size_t buflen,
+                        const char* pname, const char* fname) {
+  // Copied from libhpi
   const size_t pnamelen = pname ? strlen(pname) : 0;
 
-  /* Quietly truncate on buffer overflow.  Should be an error. */
+  // Quietly truncate on buffer overflow.  Should be an error.
   if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
       *buffer = '\0';
       return;
   }
 
   if (pnamelen == 0) {
-      sprintf(buffer, "lib%s.so", fname);
+    snprintf(buffer, buflen, "lib%s.so", fname);
+  } else if (strchr(pname, *os::path_separator()) != NULL) {
+    int n;
+    char** pelements = split_path(pname, &n);
+    for (int i = 0 ; i < n ; i++) {
+      // really shouldn't be NULL but what the heck, check can't hurt
+      if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
+        continue; // skip the empty path values
+      }
+      snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
+      if (file_exists(buffer)) {
+        break;
+      }
+    }
+    // release the storage
+    for (int i = 0 ; i < n ; i++) {
+      if (pelements[i] != NULL) {
+        FREE_C_HEAP_ARRAY(char, pelements[i]);
+      }
+    }
+    if (pelements != NULL) {
+      FREE_C_HEAP_ARRAY(char*, pelements);
+    }
   } else {
-      sprintf(buffer, "%s/lib%s.so", pname, fname);
+    snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
   }
 }
 
@@ -2623,15 +2653,16 @@
   return page_size;
 }
 
-bool os::commit_memory(char* addr, size_t bytes) {
+bool os::commit_memory(char* addr, size_t bytes, bool exec) {
+  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
   size_t size = bytes;
   return
-     NULL != Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED,
-                                 PROT_READ | PROT_WRITE | PROT_EXEC);
-}
-
-bool os::commit_memory(char* addr, size_t bytes, size_t alignment_hint) {
-  if (commit_memory(addr, bytes)) {
+     NULL != Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
+}
+
+bool os::commit_memory(char* addr, size_t bytes, size_t alignment_hint,
+                       bool exec) {
+  if (commit_memory(addr, bytes, exec)) {
     if (UseMPSS && alignment_hint > (size_t)vm_page_size()) {
       // If the large page size has been set and the VM
       // is using large pages, use the large page size
@@ -3220,7 +3251,9 @@
   return true;
 }
 
-char* os::reserve_memory_special(size_t bytes) {
+char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) {
+  // "exec" is passed in but not used.  Creating the shared image for
+  // the code cache doesn't have an SHM_X executable permission to check.
   assert(UseLargePages && UseISM, "only for ISM large pages");
 
   size_t size = bytes;
@@ -4451,6 +4484,9 @@
 int_fnP_thread_t os::Solaris::_thr_suspend_mutator;
 int_fnP_thread_t os::Solaris::_thr_continue_mutator;
 
+// (Static) wrapper for getisax(2) call.
+os::Solaris::getisax_func_t os::Solaris::_getisax = 0;
+
 // (Static) wrappers for the liblgrp API
 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
@@ -4465,16 +4501,19 @@
 // (Static) wrapper for meminfo() call.
 os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0;
 
-static address resolve_symbol(const char *name) {
-  address addr;
-
-  addr = (address) dlsym(RTLD_DEFAULT, name);
+static address resolve_symbol_lazy(const char* name) {
+  address addr = (address) dlsym(RTLD_DEFAULT, name);
   if(addr == NULL) {
     // RTLD_DEFAULT was not defined on some early versions of 2.5.1
     addr = (address) dlsym(RTLD_NEXT, name);
-    if(addr == NULL) {
-      fatal(dlerror());
-    }
+  }
+  return addr;
+}
+
+static address resolve_symbol(const char* name) {
+  address addr = resolve_symbol_lazy(name);
+  if(addr == NULL) {
+    fatal(dlerror());
   }
   return addr;
 }
@@ -4673,15 +4712,26 @@
 }
 
 void os::Solaris::misc_sym_init() {
-  address func = (address)dlsym(RTLD_DEFAULT, "meminfo");
-  if(func == NULL) {
-    func = (address) dlsym(RTLD_NEXT, "meminfo");
-  }
+  address func;
+
+  // getisax
+  func = resolve_symbol_lazy("getisax");
+  if (func != NULL) {
+    os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func);
+  }
+
+  // meminfo
+  func = resolve_symbol_lazy("meminfo");
   if (func != NULL) {
     os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func));
   }
 }
 
+uint_t os::Solaris::getisax(uint32_t* array, uint_t n) {
+  assert(_getisax != NULL, "_getisax not set");
+  return _getisax(array, n);
+}
+
 // Symbol doesn't exist in Solaris 8 pset.h
 #ifndef PS_MYID
 #define PS_MYID -3
@@ -4716,6 +4766,10 @@
 
   Solaris::initialize_system_info();
 
+  // Initialize misc. symbols as soon as possible, so we can use them
+  // if we need them.
+  Solaris::misc_sym_init();
+
   int fd = open("/dev/zero", O_RDWR);
   if (fd < 0) {
     fatal1("os::init: cannot open /dev/zero (%s)", strerror(errno));
@@ -4857,7 +4911,6 @@
     }
   }
 
-  Solaris::misc_sym_init();
   Solaris::signal_sets_init();
   Solaris::init_signal_mem();
   Solaris::install_signal_handlers();
--- a/hotspot/src/os/solaris/vm/os_solaris.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,6 +72,8 @@
         LGRP_VIEW_OS            /* what's available to operating system */
   } lgrp_view_t;
 
+  typedef uint_t (*getisax_func_t)(uint32_t* array, uint_t n);
+
   typedef lgrp_id_t (*lgrp_home_func_t)(idtype_t idtype, id_t id);
   typedef lgrp_cookie_t (*lgrp_init_func_t)(lgrp_view_t view);
   typedef int (*lgrp_fini_func_t)(lgrp_cookie_t cookie);
@@ -87,6 +89,8 @@
                                 const uint_t  info_req[],  int info_count,
                                 uint64_t  outdata[], uint_t validity[]);
 
+  static getisax_func_t _getisax;
+
   static lgrp_home_func_t _lgrp_home;
   static lgrp_init_func_t _lgrp_init;
   static lgrp_fini_func_t _lgrp_fini;
@@ -283,6 +287,9 @@
   }
   static lgrp_cookie_t lgrp_cookie()                 { return _lgrp_cookie; }
 
+  static bool supports_getisax()                     { return _getisax != NULL; }
+  static uint_t getisax(uint32_t* array, uint_t n);
+
   static void set_meminfo(meminfo_func_t func)       { _meminfo = func; }
   static int meminfo (const uint64_t inaddr[],   int addr_count,
                      const uint_t  info_req[],  int info_count,
--- a/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -194,7 +194,7 @@
 // check if the given path is considered a secure directory for
 // the backing store files. Returns true if the directory exists
 // and is considered a secure location. Returns false if the path
-// is a symbolic link or if an error occured.
+// is a symbolic link or if an error occurred.
 //
 static bool is_directory_secure(const char* path) {
   struct stat statbuf;
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1004,26 +1004,61 @@
     }
 }
 
-void os::dll_build_name(char *holder, size_t holderlen,
-                        const char* pname, const char* fname)
-{
-    // copied from libhpi
-    const size_t pnamelen = pname ? strlen(pname) : 0;
-    const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0;
-
-    /* Quietly truncates on buffer overflow. Should be an error. */
-    if (pnamelen + strlen(fname) + 10 > holderlen) {
-        *holder = '\0';
-        return;
+static bool file_exists(const char* filename) {
+  if (filename == NULL || strlen(filename) == 0) {
+    return false;
+  }
+  return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES;
+}
+
+void os::dll_build_name(char *buffer, size_t buflen,
+                        const char* pname, const char* fname) {
+  // Copied from libhpi
+  const size_t pnamelen = pname ? strlen(pname) : 0;
+  const char c = (pnamelen > 0) ? pname[pnamelen-1] : 0;
+
+  // Quietly truncates on buffer overflow. Should be an error.
+  if (pnamelen + strlen(fname) + 10 > buflen) {
+    *buffer = '\0';
+    return;
+  }
+
+  if (pnamelen == 0) {
+    jio_snprintf(buffer, buflen, "%s.dll", fname);
+  } else if (c == ':' || c == '\\') {
+    jio_snprintf(buffer, buflen, "%s%s.dll", pname, fname);
+  } else if (strchr(pname, *os::path_separator()) != NULL) {
+    int n;
+    char** pelements = split_path(pname, &n);
+    for (int i = 0 ; i < n ; i++) {
+      char* path = pelements[i];
+      // Really shouldn't be NULL, but check can't hurt
+      size_t plen = (path == NULL) ? 0 : strlen(path);
+      if (plen == 0) {
+        continue; // skip the empty path values
+      }
+      const char lastchar = path[plen - 1];
+      if (lastchar == ':' || lastchar == '\\') {
+        jio_snprintf(buffer, buflen, "%s%s.dll", path, fname);
+      } else {
+        jio_snprintf(buffer, buflen, "%s\\%s.dll", path, fname);
+      }
+      if (file_exists(buffer)) {
+        break;
+      }
     }
-
-    if (pnamelen == 0) {
-        sprintf(holder, "%s.dll", fname);
-    } else if (c == ':' || c == '\\') {
-        sprintf(holder, "%s%s.dll", pname, fname);
-    } else {
-        sprintf(holder, "%s\\%s.dll", pname, fname);
+    // release the storage
+    for (int i = 0 ; i < n ; i++) {
+      if (pelements[i] != NULL) {
+        FREE_C_HEAP_ARRAY(char, pelements[i]);
+      }
     }
+    if (pelements != NULL) {
+      FREE_C_HEAP_ARRAY(char*, pelements);
+    }
+  } else {
+    jio_snprintf(buffer, buflen, "%s\\%s.dll", pname, fname);
+  }
 }
 
 // Needs to be in os specific directory because windows requires another
@@ -2189,7 +2224,8 @@
           if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) {
                   addr = (address)((uintptr_t)addr &
                          (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
-                  os::commit_memory( (char *)addr, thread->stack_base() - addr );
+                  os::commit_memory((char *)addr, thread->stack_base() - addr,
+                                    false );
                   return EXCEPTION_CONTINUE_EXECUTION;
           }
           else
@@ -2565,8 +2601,7 @@
   assert((size_t)addr % os::vm_allocation_granularity() == 0,
          "reserve alignment");
   assert(bytes % os::vm_allocation_granularity() == 0, "reserve block size");
-  char* res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE,
-                                  PAGE_EXECUTE_READWRITE);
+  char* res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE);
   assert(res == NULL || addr == NULL || addr == res,
          "Unexpected address from reserve.");
   return res;
@@ -2595,7 +2630,7 @@
   return true;
 }
 
-char* os::reserve_memory_special(size_t bytes) {
+char* os::reserve_memory_special(size_t bytes, char* addr, bool exec) {
 
   if (UseLargePagesIndividualAllocation) {
     if (TracePageSizes && Verbose) {
@@ -2615,10 +2650,10 @@
         "use -XX:-UseLargePagesIndividualAllocation to turn off");
       return NULL;
     }
-    p_buf = (char *) VirtualAlloc(NULL,
+    p_buf = (char *) VirtualAlloc(addr,
                                  size_of_reserve,  // size of Reserve
                                  MEM_RESERVE,
-                                 PAGE_EXECUTE_READWRITE);
+                                 PAGE_READWRITE);
     // If reservation failed, return NULL
     if (p_buf == NULL) return NULL;
 
@@ -2659,7 +2694,13 @@
         p_new = (char *) VirtualAlloc(next_alloc_addr,
                                     bytes_to_rq,
                                     MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
-                                    PAGE_EXECUTE_READWRITE);
+                                    PAGE_READWRITE);
+        if (p_new != NULL && exec) {
+          DWORD oldprot;
+          // Windows doc says to use VirtualProtect to get execute permissions
+          VirtualProtect(next_alloc_addr, bytes_to_rq,
+                         PAGE_EXECUTE_READWRITE, &oldprot);
+        }
       }
 
       if (p_new == NULL) {
@@ -2688,10 +2729,12 @@
   } else {
     // normal policy just allocate it all at once
     DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES;
-    char * res = (char *)VirtualAlloc(NULL,
-                                      bytes,
-                                      flag,
-                                      PAGE_EXECUTE_READWRITE);
+    char * res = (char *)VirtualAlloc(NULL, bytes, flag, PAGE_READWRITE);
+    if (res != NULL && exec) {
+      DWORD oldprot;
+      // Windows doc says to use VirtualProtect to get execute permissions
+      VirtualProtect(res, bytes, PAGE_EXECUTE_READWRITE, &oldprot);
+    }
     return res;
   }
 }
@@ -2703,7 +2746,7 @@
 void os::print_statistics() {
 }
 
-bool os::commit_memory(char* addr, size_t bytes) {
+bool os::commit_memory(char* addr, size_t bytes, bool exec) {
   if (bytes == 0) {
     // Don't bother the OS with noops.
     return true;
@@ -2712,11 +2755,19 @@
   assert(bytes % os::vm_page_size() == 0, "commit in page-sized chunks");
   // Don't attempt to print anything if the OS call fails. We're
   // probably low on resources, so the print itself may cause crashes.
-  return VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE) != NULL;
+  bool result = VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) != 0;
+  if (result != NULL && exec) {
+    DWORD oldprot;
+    // Windows doc says to use VirtualProtect to get execute permissions
+    return VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot) != 0;
+  } else {
+    return result;
+  }
 }
 
-bool os::commit_memory(char* addr, size_t size, size_t alignment_hint) {
-  return commit_memory(addr, size);
+bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
+                       bool exec) {
+  return commit_memory(addr, size, exec);
 }
 
 bool os::uncommit_memory(char* addr, size_t bytes) {
@@ -2750,7 +2801,7 @@
 
   // Strange enough, but on Win32 one can change protection only for committed
   // memory, not a big deal anyway, as bytes less or equal than 64K
-  if (!is_committed && !commit_memory(addr, bytes)) {
+  if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) {
     fatal("cannot commit protection page");
   }
   // One cannot use os::guard_memory() here, as on Win32 guard page
@@ -3248,10 +3299,10 @@
 #endif
 
   if (!UseMembar) {
-    address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_EXECUTE_READWRITE);
+    address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE);
     guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page");
 
-    return_page  = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
+    return_page  = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE);
     guarantee( return_page != NULL, "Commit Failed for memory serialize page");
 
     os::set_memory_serialize_page( mem_serialize_page );
--- a/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -195,7 +195,7 @@
 // check if the given path is considered a secure directory for
 // the backing store files. Returns true if the directory exists
 // and is considered a secure location. Returns false if the path
-// is a symbolic link or if an error occured.
+// is a symbolic link or if an error occurred.
 //
 static bool is_directory_secure(const char* path) {
 
@@ -994,7 +994,7 @@
     return false;
   }
 
-  // if running on windows 2000 or later, set the automatic inheritence
+  // if running on windows 2000 or later, set the automatic inheritance
   // control flags.
   SetSecurityDescriptorControlFnPtr _SetSecurityDescriptorControl;
   _SetSecurityDescriptorControl = (SetSecurityDescriptorControlFnPtr)
@@ -1002,7 +1002,7 @@
                       "SetSecurityDescriptorControl");
 
   if (_SetSecurityDescriptorControl != NULL) {
-    // We do not want to further propogate inherited DACLs, so making them
+    // We do not want to further propagate inherited DACLs, so making them
     // protected prevents that.
     if (!_SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED,
                                             SE_DACL_PROTECTED)) {
--- a/hotspot/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -30,5 +30,7 @@
 define_pd_global(uintx, JVMInvokeMethodSlack,    12288);
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
+// Only used on 64 bit platforms
+define_pd_global(uintx, HeapBaseMinAddress,      4*G);
 // Only used on 64 bit Windows platforms
 define_pd_global(bool, UseVectoredExceptions, false);
--- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -29,13 +29,11 @@
   static jint  (*atomic_cmpxchg_func)     (jint,  volatile jint*,  jint);
   static jlong (*atomic_cmpxchg_long_func)(jlong, volatile jlong*, jlong);
   static jint  (*atomic_add_func)         (jint,  volatile jint*);
-  static void  (*fence_func)              ();
 
   static jint  atomic_xchg_bootstrap        (jint,  volatile jint*);
   static jint  atomic_cmpxchg_bootstrap     (jint,  volatile jint*,  jint);
   static jlong atomic_cmpxchg_long_bootstrap(jlong, volatile jlong*, jlong);
   static jint  atomic_add_bootstrap         (jint,  volatile jint*);
-  static void  fence_bootstrap              ();
 
   static void setup_fpu() {}
 
--- a/hotspot/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -43,5 +43,7 @@
 
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
+// Only used on 64 bit platforms
+define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 // Only used on 64 bit Windows platforms
 define_pd_global(bool, UseVectoredExceptions,    false);
--- a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -44,11 +44,12 @@
 
 inline void OrderAccess::fence() {
   if (os::is_MP()) {
+    // always use locked addl since mfence is sometimes expensive
 #ifdef AMD64
-    __asm__ __volatile__ ("mfence":::"memory");
+    __asm__ volatile ("lock; addl $0,0(%%rsp)" : : : "cc", "memory");
 #else
     __asm__ volatile ("lock; addl $0,0(%%esp)" : : : "cc", "memory");
-#endif // AMD64
+#endif
   }
 }
 
--- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -30,5 +30,9 @@
 define_pd_global(uintx, JVMInvokeMethodSlack,    12288);
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
+// Only used on 64 bit platforms
+define_pd_global(uintx, HeapBaseMinAddress,      4*G);
 // Only used on 64 bit Windows platforms
 define_pd_global(bool, UseVectoredExceptions,    false);
+
+
--- a/hotspot/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -60,22 +60,10 @@
   dummy = 0;
 }
 
-#if defined(COMPILER2) || defined(_LP64)
-
 inline void OrderAccess::fence() {
   _OrderAccess_fence();
 }
 
-#else  // defined(COMPILER2) || defined(_LP64)
-
-inline void OrderAccess::fence() {
-  if (os::is_MP()) {
-    (*os::fence_func)();
-  }
-}
-
-#endif // defined(COMPILER2) || defined(_LP64)
-
 #endif // _GNU_SOURCE
 
 inline jbyte    OrderAccess::load_acquire(volatile jbyte*   p) { return *p; }
--- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -532,7 +532,7 @@
     if (oldAct.sa_sigaction != signalHandler) {
       void* sighand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
                                           : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
-      warning("Unexpected Signal %d occured under user-defined signal handler " INTPTR_FORMAT, sig, (intptr_t)sighand);
+      warning("Unexpected Signal %d occurred under user-defined signal handler " INTPTR_FORMAT, sig, (intptr_t)sighand);
     }
   }
 
@@ -619,7 +619,6 @@
 typedef jint  cmpxchg_func_t     (jint,  volatile jint*,  jint);
 typedef jlong cmpxchg_long_func_t(jlong, volatile jlong*, jlong);
 typedef jint  add_func_t         (jint,  volatile jint*);
-typedef void  fence_func_t       ();
 
 jint os::atomic_xchg_bootstrap(jint exchange_value, volatile jint* dest) {
   // try to use the stub:
@@ -681,25 +680,10 @@
   return (*dest) += add_value;
 }
 
-void os::fence_bootstrap() {
-  // try to use the stub:
-  fence_func_t* func = CAST_TO_FN_PTR(fence_func_t*, StubRoutines::fence_entry());
-
-  if (func != NULL) {
-    os::fence_func = func;
-    (*func)();
-    return;
-  }
-  assert(Threads::number_of_threads() == 0, "for bootstrap only");
-
-  // don't have to do anything for a single thread
-}
-
 xchg_func_t*         os::atomic_xchg_func         = os::atomic_xchg_bootstrap;
 cmpxchg_func_t*      os::atomic_cmpxchg_func      = os::atomic_cmpxchg_bootstrap;
 cmpxchg_long_func_t* os::atomic_cmpxchg_long_func = os::atomic_cmpxchg_long_bootstrap;
 add_func_t*          os::atomic_add_func          = os::atomic_add_bootstrap;
-fence_func_t*        os::fence_func               = os::fence_bootstrap;
 
 #endif // !_LP64 && !COMPILER2
 
--- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -29,13 +29,11 @@
   static jint  (*atomic_cmpxchg_func)     (jint,  volatile jint*,  jint);
   static jlong (*atomic_cmpxchg_long_func)(jlong, volatile jlong*, jlong);
   static jint  (*atomic_add_func)         (jint,  volatile jint*);
-  static void  (*fence_func)              ();
 
   static jint  atomic_xchg_bootstrap        (jint,  volatile jint*);
   static jint  atomic_cmpxchg_bootstrap     (jint,  volatile jint*,  jint);
   static jlong atomic_cmpxchg_long_bootstrap(jlong, volatile jlong*, jlong);
   static jint  atomic_add_bootstrap         (jint,  volatile jint*);
-  static void  fence_bootstrap              ();
 
   static void setup_fpu() {}
 
--- a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,58 +25,107 @@
 # include "incls/_precompiled.incl"
 # include "incls/_vm_version_solaris_sparc.cpp.incl"
 
+# include <sys/auxv.h>
+# include <sys/auxv_SPARC.h>
 # include <sys/systeminfo.h>
 
+// We need to keep these here as long as we have to build on Solaris
+// versions before 10.
+#ifndef SI_ARCHITECTURE_32
+#define SI_ARCHITECTURE_32      516     /* basic 32-bit SI_ARCHITECTURE */
+#endif
+
+#ifndef SI_ARCHITECTURE_64
+#define SI_ARCHITECTURE_64      517     /* basic 64-bit SI_ARCHITECTURE */
+#endif
+
+static void do_sysinfo(int si, const char* string, int* features, int mask) {
+  char   tmp;
+  size_t bufsize = sysinfo(si, &tmp, 1);
+
+  // All SI defines used below must be supported.
+  guarantee(bufsize != -1, "must be supported");
+
+  char* buf = (char*) malloc(bufsize);
+
+  if (buf == NULL)
+    return;
+
+  if (sysinfo(si, buf, bufsize) == bufsize) {
+    // Compare the string.
+    if (strcmp(buf, string) == 0) {
+      *features |= mask;
+    }
+  }
+
+  free(buf);
+}
+
 int VM_Version::platform_features(int features) {
-  // We determine what sort of hardware we have via sysinfo(SI_ISALIST, ...).
-  // This isn't the best of all possible ways because there's not enough
-  // detail in the isa list it returns, but it's a bit less arcane than
-  // generating assembly code and an illegal instruction handler.  We used
-  // to generate a getpsr trap, but that's even more arcane.
-  //
-  // Another possibility would be to use sysinfo(SI_PLATFORM, ...), but
-  // that would require more knowledge here than is wise.
+  // getisax(2), SI_ARCHITECTURE_32, and SI_ARCHITECTURE_64 are
+  // supported on Solaris 10 and later.
+  if (os::Solaris::supports_getisax()) {
+#ifndef PRODUCT
+    if (PrintMiscellaneous && Verbose)
+      tty->print_cr("getisax(2) supported.");
+#endif
 
-  // isalist spec via 'man isalist' as of 01-Aug-2001
+    // Check 32-bit architecture.
+    do_sysinfo(SI_ARCHITECTURE_32, "sparc", &features, v8_instructions_m);
+
+    // Check 64-bit architecture.
+    do_sysinfo(SI_ARCHITECTURE_64, "sparcv9", &features, generic_v9_m);
+
+    // Extract valid instruction set extensions.
+    uint_t av;
+    uint_t avn = os::Solaris::getisax(&av, 1);
+    assert(avn == 1, "should only return one av");
 
-  char   tmp;
-  size_t bufsize  = sysinfo(SI_ISALIST, &tmp, 1);
-  char*  buf      = (char*)malloc(bufsize);
+    if (av & AV_SPARC_MUL32)  features |= hardware_mul32_m;
+    if (av & AV_SPARC_DIV32)  features |= hardware_div32_m;
+    if (av & AV_SPARC_FSMULD) features |= hardware_fsmuld_m;
+    if (av & AV_SPARC_V8PLUS) features |= v9_instructions_m;
+    if (av & AV_SPARC_POPC)   features |= hardware_popc_m;
+    if (av & AV_SPARC_VIS)    features |= vis1_instructions_m;
+    if (av & AV_SPARC_VIS2)   features |= vis2_instructions_m;
+  } else {
+    // getisax(2) failed, use the old legacy code.
+#ifndef PRODUCT
+    if (PrintMiscellaneous && Verbose)
+      tty->print_cr("getisax(2) not supported.");
+#endif
+
+    char   tmp;
+    size_t bufsize = sysinfo(SI_ISALIST, &tmp, 1);
+    char*  buf     = (char*) malloc(bufsize);
 
-  if (buf != NULL) {
-    if (sysinfo(SI_ISALIST, buf, bufsize) == bufsize) {
-      // Figure out what kind of sparc we have
-      char *sparc_string = strstr(buf, "sparc");
-      if (sparc_string != NULL) {            features |= v8_instructions_m;
-        if (sparc_string[5] == 'v') {
-          if (sparc_string[6] == '8') {
-            if (sparc_string[7] == '-')      features |= hardware_int_muldiv_m;
-            else if (sparc_string[7] == 'p') features |= generic_v9_m;
-            else                      features |= generic_v8_m;
-          } else if (sparc_string[6] == '9') features |= generic_v9_m;
+    if (buf != NULL) {
+      if (sysinfo(SI_ISALIST, buf, bufsize) == bufsize) {
+        // Figure out what kind of sparc we have
+        char *sparc_string = strstr(buf, "sparc");
+        if (sparc_string != NULL) {              features |= v8_instructions_m;
+          if (sparc_string[5] == 'v') {
+            if (sparc_string[6] == '8') {
+              if (sparc_string[7] == '-') {      features |= hardware_mul32_m;
+                                                 features |= hardware_div32_m;
+              } else if (sparc_string[7] == 'p') features |= generic_v9_m;
+              else                               features |= generic_v8_m;
+            } else if (sparc_string[6] == '9')   features |= generic_v9_m;
+          }
+        }
+
+        // Check for visualization instructions
+        char *vis = strstr(buf, "vis");
+        if (vis != NULL) {                       features |= vis1_instructions_m;
+          if (vis[3] == '2')                     features |= vis2_instructions_m;
         }
       }
-
-      // Check for visualization instructions
-      char *vis = strstr(buf, "vis");
-      if (vis != NULL) {              features |= vis1_instructions_m;
-        if (vis[3] == '2')            features |= vis2_instructions_m;
-      }
+      free(buf);
     }
-    free(buf);
   }
 
-  bufsize = sysinfo(SI_MACHINE, &tmp, 1);
-  buf     = (char*)malloc(bufsize);
-
-  if (buf != NULL) {
-    if (sysinfo(SI_MACHINE, buf, bufsize) == bufsize) {
-      if (strstr(buf, "sun4v") != NULL) {
-        features |= sun4v_m;
-      }
-    }
-    free(buf);
-  }
+  // Determine the machine type.
+  do_sysinfo(SI_MACHINE, "sun4v", &features, sun4v_m);
 
   return features;
 }
--- a/hotspot/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -46,5 +46,7 @@
 
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
+// Only used on 64 bit platforms
+define_pd_global(uintx, HeapBaseMinAddress,      256*M);
 // Only used on 64 bit Windows platforms
 define_pd_global(bool, UseVectoredExceptions,    false);
--- a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -61,11 +61,8 @@
 #endif // AMD64
   }
   inline void _OrderAccess_fence() {
-#ifdef AMD64
-    __asm__ __volatile__ ("mfence":::"memory");
-#else
+    // Always use locked addl since mfence is sometimes expensive
     __asm__ volatile ("lock; addl $0,0(%%esp)" : : : "cc", "memory");
-#endif // AMD64
   }
 
 }
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -299,14 +299,18 @@
 
 }
 
+#endif // AMD64
+
 bool os::supports_sse() {
+#ifdef AMD64
+  return true;
+#else
   if (sse_status == SSE_UNKNOWN)
     check_for_sse_support();
   return sse_status == SSE_SUPPORTED;
+#endif // AMD64
 }
 
-#endif // AMD64
-
 bool os::is_allocatable(size_t bytes) {
 #ifdef AMD64
   return true;
@@ -690,7 +694,7 @@
     if (oldAct.sa_sigaction != signalHandler) {
       void* sighand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
                                           : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
-      warning("Unexpected Signal %d occured under user-defined signal handler %#lx", sig, (long)sighand);
+      warning("Unexpected Signal %d occurred under user-defined signal handler %#lx", sig, (long)sighand);
     }
   }
 
@@ -790,7 +794,6 @@
 typedef jint  cmpxchg_func_t     (jint,  volatile jint*,  jint);
 typedef jlong cmpxchg_long_func_t(jlong, volatile jlong*, jlong);
 typedef jint  add_func_t         (jint,  volatile jint*);
-typedef void  fence_func_t       ();
 
 jint os::atomic_xchg_bootstrap(jint exchange_value, volatile jint* dest) {
   // try to use the stub:
@@ -852,25 +855,10 @@
   return (*dest) += add_value;
 }
 
-void os::fence_bootstrap() {
-  // try to use the stub:
-  fence_func_t* func = CAST_TO_FN_PTR(fence_func_t*, StubRoutines::fence_entry());
-
-  if (func != NULL) {
-    os::fence_func = func;
-    (*func)();
-    return;
-  }
-  assert(Threads::number_of_threads() == 0, "for bootstrap only");
-
-  // don't have to do anything for a single thread
-}
-
 xchg_func_t*         os::atomic_xchg_func         = os::atomic_xchg_bootstrap;
 cmpxchg_func_t*      os::atomic_cmpxchg_func      = os::atomic_cmpxchg_bootstrap;
 cmpxchg_long_func_t* os::atomic_cmpxchg_long_func = os::atomic_cmpxchg_long_bootstrap;
 add_func_t*          os::atomic_add_func          = os::atomic_add_bootstrap;
-fence_func_t*        os::fence_func               = os::fence_bootstrap;
 
 extern "C" _solaris_raw_setup_fpu(address ptr);
 void os::setup_fpu() {
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,17 +32,16 @@
   static jint  (*atomic_cmpxchg_func)     (jint,  volatile jint*,  jint);
   static jlong (*atomic_cmpxchg_long_func)(jlong, volatile jlong*, jlong);
   static jint  (*atomic_add_func)         (jint,  volatile jint*);
-  static void  (*fence_func)              ();
 
   static jint  atomic_xchg_bootstrap        (jint,  volatile jint*);
   static jint  atomic_cmpxchg_bootstrap     (jint,  volatile jint*,  jint);
   static jlong atomic_cmpxchg_long_bootstrap(jlong, volatile jlong*, jlong);
   static jint  atomic_add_bootstrap         (jint,  volatile jint*);
-  static void  fence_bootstrap              ();
 
   static void setup_fpu();
+#endif // AMD64
+
   static bool supports_sse();
-#endif // AMD64
 
   static bool is_allocatable(size_t bytes);
 
--- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.il	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.il	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.il	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.il	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2004-2007 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/os_cpu/windows_x86/vm/globals_windows_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/globals_windows_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -45,5 +45,7 @@
 
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
+// Only used on 64 bit platforms
+define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 // Only used on 64 bit Windows platforms
 define_pd_global(bool, UseVectoredExceptions,    false);
--- a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -46,7 +46,7 @@
 
 inline void OrderAccess::fence() {
 #ifdef AMD64
-  (*os::fence_func)();
+  StubRoutines_fence();
 #else
   if (os::is_MP()) {
     __asm {
--- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -196,7 +196,6 @@
 typedef jlong     cmpxchg_long_func_t    (jlong,    volatile jlong*, jlong);
 typedef jint      add_func_t             (jint,     volatile jint*);
 typedef intptr_t  add_ptr_func_t         (intptr_t, volatile intptr_t*);
-typedef void      fence_func_t           ();
 
 #ifdef AMD64
 
@@ -292,27 +291,11 @@
   return (*dest) += add_value;
 }
 
-void os::fence_bootstrap() {
-  // try to use the stub:
-  fence_func_t* func = CAST_TO_FN_PTR(fence_func_t*, StubRoutines::fence_entry());
-
-  if (func != NULL) {
-    os::fence_func = func;
-    (*func)();
-    return;
-  }
-  assert(Threads::number_of_threads() == 0, "for bootstrap only");
-
-  // don't have to do anything for a single thread
-}
-
-
 xchg_func_t*         os::atomic_xchg_func         = os::atomic_xchg_bootstrap;
 xchg_ptr_func_t*     os::atomic_xchg_ptr_func     = os::atomic_xchg_ptr_bootstrap;
 cmpxchg_func_t*      os::atomic_cmpxchg_func      = os::atomic_cmpxchg_bootstrap;
 add_func_t*          os::atomic_add_func          = os::atomic_add_bootstrap;
 add_ptr_func_t*      os::atomic_add_ptr_func      = os::atomic_add_ptr_bootstrap;
-fence_func_t*        os::fence_func               = os::fence_bootstrap;
 
 #endif // AMD64
 
--- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -35,9 +35,6 @@
   static jint      (*atomic_add_func)           (jint,      volatile jint*);
   static intptr_t  (*atomic_add_ptr_func)       (intptr_t,  volatile intptr_t*);
 
-  static void      (*fence_func)                ();
-
-
   static jint      atomic_xchg_bootstrap        (jint,      volatile jint*);
   static intptr_t  atomic_xchg_ptr_bootstrap    (intptr_t,  volatile intptr_t*);
 
@@ -53,8 +50,6 @@
 #ifdef AMD64
   static jint      atomic_add_bootstrap         (jint,      volatile jint*);
   static intptr_t  atomic_add_ptr_bootstrap     (intptr_t,  volatile intptr_t*);
-
-  static void      fence_bootstrap              ();
 #endif // AMD64
 
   static void setup_fpu();
--- a/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -68,6 +68,9 @@
     PVOID HandlerData;
 } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;
 
+#if MSC_VER < 1500
+
+/* Not needed for VS2008 compiler, comes from winnt.h. */
 typedef EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE) (
     IN PEXCEPTION_RECORD ExceptionRecord,
     IN ULONG64 EstablisherFrame,
@@ -75,4 +78,6 @@
     IN OUT PDISPATCHER_CONTEXT DispatcherContext
 );
 
+#endif
+
 #endif // AMD64
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,75 @@
+#
+# Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+# 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#  
+#
+PKGLIST = \
+com.sun.hotspot.tools.compiler
+#END PKGLIST
+
+FILELIST = com/sun/hotspot/tools/compiler/*.java
+
+ifneq "x$(ALT_BOOTDIR)" "x"
+  BOOTDIR := $(ALT_BOOTDIR)
+endif
+
+ifeq "x$(BOOTDIR)" "x"
+  JDK_HOME := $(shell dirname $(shell which java))/..
+else
+  JDK_HOME := $(BOOTDIR)
+endif
+
+isUnix := $(shell test -r c:/; echo $$?)
+
+ifeq "$(isUnix)" "1"
+    CPS := :
+else
+    CPS := ";"
+endif
+
+SRC_DIR    = src
+BUILD_DIR  = build
+OUTPUT_DIR = $(BUILD_DIR)/classes
+
+# gnumake 3.78.1 does not accept the *s, 
+# so use the shell to expand them
+ALLFILES := $(patsubst %,$(SRC_DIR)/%,$(FILELIST))
+ALLFILES := $(shell /bin/ls $(ALLFILES))
+
+JAVAC = $(JDK_HOME)/bin/javac
+JAR = $(JDK_HOME)/bin/jar
+
+# Tagging it on because there's no reason not to run it
+all: logc.jar
+
+logc.jar: filelist manifest.mf
+	@mkdir -p $(OUTPUT_DIR)
+	$(JAVAC) -source 1.5 -deprecation -sourcepath $(SRC_DIR) -d $(OUTPUT_DIR) @filelist
+	$(JAR) cvfm logc.jar manifest.mf -C $(OUTPUT_DIR) com
+
+.PHONY: filelist
+filelist: $(ALLFILES)
+	@rm -f $@
+	@echo $(ALLFILES) > $@
+
+clean::
+	rm -rf filelist logc.jar
+	rm -rf $(BUILD_DIR)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/README	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,18 @@
+This is a very rough tool for parsing -XX:+LogCompilation output.
+It's main purpose is to recreate output similar to
+-XX:+PrintCompilation -XX:+PrintInlining output from a debug JVM.  It
+requires a 1.5 JDK to build and simply typing make should build it.
+
+It produces a jar file, logc.jar, that can be run on the
+hotspot.log from LogCompilation output like this:
+
+  java -jar logc.jar hotspot.log
+
+This will produce something like the normal PrintCompilation output.
+Adding the -i option with also report inlining like PrintInlining.
+
+More information about the LogCompilation output can be found at 
+
+http://wikis.sun.com/display/HotSpotInternals/LogCompilation+overview
+http://wikis.sun.com/display/HotSpotInternals/PrintCompilation
+http://wikis.sun.com/display/HotSpotInternals/LogCompilation+tool
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/manifest.mf	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,1 @@
+Main-Class: com.sun.hotspot.tools.compiler.LogCompilation
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/BasicLogEvent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+
+/**
+ *
+ * @author never
+ */
+public abstract class BasicLogEvent implements LogEvent {
+
+    protected final String id;
+    protected final double start;
+    protected double end;
+    protected Compilation compilation;
+
+    BasicLogEvent(double start, String id) {
+        this.start = start;
+        this.end = start;
+        this.id = id;
+    }
+
+    public double getStart() {
+        return start;
+    }
+
+    public double getEnd() {
+        return end;
+    }
+
+    public void setEnd(double end) {
+        this.end = end;
+    }
+
+    public double getElapsedTime() {
+        return ((int) ((getEnd() - getStart()) * 1000)) / 1000.0;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public Compilation getCompilation() {
+        return compilation;
+    }
+
+    public void setCompilation(Compilation compilation) {
+        this.compilation = compilation;
+    }
+
+    abstract public void print(PrintStream stream);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/CallSite.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,183 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.List;
+
+public class CallSite {
+
+    private int bci;
+    private Method method;
+    private int count;
+    private String receiver;
+    private int receiver_count;
+    private String reason;
+    private List<CallSite> calls;
+
+    CallSite() {
+    }
+
+    CallSite(int bci, Method m) {
+        this.bci = bci;
+        this.method = m;
+    }
+
+    void add(CallSite site) {
+        if (getCalls() == null) {
+            setCalls(new ArrayList<CallSite>());
+        }
+        getCalls().add(site);
+    }
+
+    CallSite last() {
+        return last(-1);
+    }
+
+    CallSite last(int fromEnd) {
+        return getCalls().get(getCalls().size() + fromEnd);
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        if (getReason() == null) {
+            sb.append("  @ " + getBci() + " " + getMethod());
+        } else {
+            sb.append("- @ " + getBci() + " " + getMethod() + " " + getReason());
+        }
+        sb.append("\n");
+        if (getCalls() != null) {
+            for (CallSite site : getCalls()) {
+                sb.append(site);
+                sb.append("\n");
+            }
+        }
+        return sb.toString();
+    }
+
+    public void print(PrintStream stream) {
+        print(stream, 0);
+    }
+
+    void emit(PrintStream stream, int indent) {
+        for (int i = 0; i < indent; i++) {
+            stream.print(' ');
+        }
+    }
+    private static boolean compat = true;
+
+    public void print(PrintStream stream, int indent) {
+        emit(stream, indent);
+        String m = getMethod().getHolder().replace('/', '.') + "::" + getMethod().getName();
+        if (getReason() == null) {
+            stream.println("  @ " + getBci() + " " + m + " (" + getMethod().getBytes() + " bytes)");
+
+        } else {
+            if (isCompat()) {
+                stream.println("  @ " + getBci() + " " + m + " " + getReason());
+            } else {
+                stream.println("- @ " + getBci() + " " + m +
+                        " (" + getMethod().getBytes() + " bytes) " + getReason());
+            }
+        }
+        if (getReceiver() != null) {
+            emit(stream, indent + 3);
+            //                 stream.println("type profile " + method.holder + " -> " + receiver + " (" +
+            //                                receiver_count + "/" + count + "," + (receiver_count * 100 / count) + "%)");
+            stream.println("type profile " + getMethod().getHolder() + " -> " + getReceiver() + " (" +
+                    (getReceiverCount() * 100 / getCount()) + "%)");
+        }
+        if (getCalls() != null) {
+            for (CallSite site : getCalls()) {
+                site.print(stream, indent + 2);
+            }
+        }
+    }
+
+    public int getBci() {
+        return bci;
+    }
+
+    public void setBci(int bci) {
+        this.bci = bci;
+    }
+
+    public Method getMethod() {
+        return method;
+    }
+
+    public void setMethod(Method method) {
+        this.method = method;
+    }
+
+    public int getCount() {
+        return count;
+    }
+
+    public void setCount(int count) {
+        this.count = count;
+    }
+
+    public String getReceiver() {
+        return receiver;
+    }
+
+    public void setReceiver(String receiver) {
+        this.receiver = receiver;
+    }
+
+    public int getReceiverCount() {
+        return receiver_count;
+    }
+
+    public void setReceiver_count(int receiver_count) {
+        this.receiver_count = receiver_count;
+    }
+
+    public String getReason() {
+        return reason;
+    }
+
+    public void setReason(String reason) {
+        this.reason = reason;
+    }
+
+    public List<CallSite> getCalls() {
+        return calls;
+    }
+
+    public void setCalls(List<CallSite> calls) {
+        this.calls = calls;
+    }
+
+    public static boolean isCompat() {
+        return compat;
+    }
+
+    public static void setCompat(boolean aCompat) {
+        compat = aCompat;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/Compilation.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,236 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+import java.util.ArrayList;
+
+public class Compilation implements LogEvent {
+
+    private int id;
+    private boolean osr;
+    private Method method;
+    private CallSite call = new CallSite();
+    private int osrBci;
+    private String icount;
+    private String bcount;
+    private String special;
+    private double start;
+    private double end;
+    private int attempts;
+    private NMethod nmethod;
+    private ArrayList<Phase> phases = new ArrayList<Phase>(4);
+    private String failureReason;
+
+    Compilation(int id) {
+        this.id = id;
+    }
+
+    Phase getPhase(String s) {
+        for (Phase p : getPhases()) {
+            if (p.getName().equals(s)) {
+                return p;
+            }
+        }
+        return null;
+    }
+
+    double getRegallocTime() {
+        return getPhase("regalloc").getElapsedTime();
+    }
+
+    public double getStart() {
+        return start;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append(getId());
+        sb.append(" ");
+        sb.append(getMethod());
+        sb.append(" ");
+        sb.append(getIcount());
+        sb.append("+");
+        sb.append(getBcount());
+        sb.append("\n");
+        for (CallSite site : getCall().getCalls()) {
+            sb.append(site);
+            sb.append("\n");
+        }
+        return sb.toString();
+    }
+
+    public void printShort(PrintStream stream) {
+        if (getMethod() == null) {
+            stream.println(getSpecial());
+        } else {
+            int bc = isOsr() ? getOsr_bci() : -1;
+            stream.print(getId() + getMethod().decodeFlags(bc) + getMethod().format(bc));
+        }
+    }
+
+    public void print(PrintStream stream) {
+        print(stream, 0, false);
+    }
+
+    public void print(PrintStream stream, boolean printInlining) {
+        print(stream, 0, printInlining);
+    }
+
+    public void print(PrintStream stream, int indent, boolean printInlining) {
+        if (getMethod() == null) {
+            stream.println(getSpecial());
+        } else {
+            int bc = isOsr() ? getOsr_bci() : -1;
+            stream.print(getId() + getMethod().decodeFlags(bc) + getMethod().format(bc));
+            stream.println();
+            if (getFailureReason() != null) {
+                stream.println("COMPILE FAILED " + getFailureReason());
+            }
+            if (printInlining && call.getCalls() != null) {
+                for (CallSite site : call.getCalls()) {
+                    site.print(stream, indent + 2);
+                }
+            }
+        }
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public boolean isOsr() {
+        return osr;
+    }
+
+    public void setOsr(boolean osr) {
+        this.osr = osr;
+    }
+
+    public int getOsr_bci() {
+        return osrBci;
+    }
+
+    public void setOsr_bci(int osrBci) {
+        this.osrBci = osrBci;
+    }
+
+    public String getIcount() {
+        return icount;
+    }
+
+    public void setICount(String icount) {
+        this.icount = icount;
+    }
+
+    public String getBcount() {
+        return bcount;
+    }
+
+    public void setBCount(String bcount) {
+        this.bcount = bcount;
+    }
+
+    public String getSpecial() {
+        return special;
+    }
+
+    public void setSpecial(String special) {
+        this.special = special;
+    }
+
+    public void setStart(double start) {
+        this.start = start;
+    }
+
+    public double getEnd() {
+        return end;
+    }
+
+    public void setEnd(double end) {
+        this.end = end;
+    }
+
+    public int getAttempts() {
+        return attempts;
+    }
+
+    public void setAttempts(int attempts) {
+        this.attempts = attempts;
+    }
+
+    public NMethod getNMethod() {
+        return nmethod;
+    }
+
+    public void setNMethod(NMethod NMethod) {
+        this.nmethod = NMethod;
+    }
+
+    public ArrayList<Phase> getPhases() {
+        return phases;
+    }
+
+    public void setPhases(ArrayList<Phase> phases) {
+        this.setPhases(phases);
+    }
+
+    public String getFailureReason() {
+        return failureReason;
+    }
+
+    public void setFailureReason(String failureReason) {
+        this.failureReason = failureReason;
+    }
+
+    public Method getMethod() {
+        return method;
+    }
+
+    public void setMethod(Method method) {
+        this.method = method;
+    }
+
+    public CallSite getCall() {
+        return call;
+    }
+
+    public void setCall(CallSite call) {
+        this.call = call;
+    }
+
+    public double getElapsedTime() {
+        return end - start;
+    }
+
+    public Compilation getCompilation() {
+        return this;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/Constants.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+interface Constants {
+    static final int  JVM_ACC_PUBLIC        = 0x0001;  /* visible to everyone */
+    static final int  JVM_ACC_PRIVATE       = 0x0002;  /* visible only to the defining class */
+    static final int  JVM_ACC_PROTECTED     = 0x0004;  /* visible to subclasses */
+    static final int  JVM_ACC_STATIC        = 0x0008;  /* instance variable is static */
+    static final int  JVM_ACC_FINAL         = 0x0010;  /* no further subclassing, overriding */
+    static final int  JVM_ACC_SYNCHRONIZED  = 0x0020;  /* wrap method call in monitor lock */
+    static final int  JVM_ACC_SUPER         = 0x0020;  /* funky handling of invokespecial */
+    static final int  JVM_ACC_VOLATILE      = 0x0040;  /* can not cache in registers */
+    static final int  JVM_ACC_BRIDGE        = 0x0040;  /* bridge method generated by compiler */
+    static final int  JVM_ACC_TRANSIENT     = 0x0080;  /* not persistent */
+    static final int  JVM_ACC_VARARGS       = 0x0080;  /* method declared with variable number of args */
+    static final int  JVM_ACC_NATIVE        = 0x0100;  /* implemented in C */
+    static final int  JVM_ACC_INTERFACE     = 0x0200;  /* class is an interface */
+    static final int  JVM_ACC_ABSTRACT      = 0x0400;  /* no definition provided */
+    static final int  JVM_ACC_STRICT        = 0x0800;  /* strict floating point */
+    static final int  JVM_ACC_SYNTHETIC     = 0x1000;  /* compiler-generated class, method or field */
+    static final int  JVM_ACC_ANNOTATION    = 0x2000;  /* annotation type */
+    static final int  JVM_ACC_ENUM          = 0x4000;  /* field is declared as element of enum */
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/LogCleanupReader.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,212 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.*;
+import java.util.regex.*;
+
+/**
+ * This class is a filter class to deal with malformed XML that used
+ * to be produced by the JVM when generating LogCompilation.  In 1.6
+ * and later releases it shouldn't be required.
+ * @author never
+ */
+
+class LogCleanupReader extends Reader {
+    private Reader reader;
+
+    private char[] buffer = new char[4096];
+
+    private int bufferCount;
+
+    private int bufferOffset;
+
+    private char[] line = new char[1024];
+
+    private int index;
+
+    private int length;
+
+    private char[] one = new char[1];
+
+    LogCleanupReader(Reader r) {
+        reader = r;
+    }
+
+    static final private Matcher pattern = Pattern.compile(".+ compile_id='[0-9]+'.*( compile_id='[0-9]+)").matcher("");
+    static final private Matcher pattern2 = Pattern.compile("' (C[12]) compile_id=").matcher("");
+    static final private Matcher pattern3 = Pattern.compile("'(destroy_vm)/").matcher("");
+
+    private void fill() throws IOException {
+        rawFill();
+        if (length != -1) {
+            boolean changed = false;
+            String s = new String(line, 0, length);
+            String orig = s;
+
+            pattern2.reset(s);
+            if (pattern2.find()) {
+                s = s.substring(0, pattern2.start(1)) + s.substring(pattern2.end(1) + 1);
+                changed = true;
+            }
+
+            pattern.reset(s);
+            if (pattern.lookingAt()) {
+                s = s.substring(0, pattern.start(1)) + s.substring(pattern.end(1) + 1);
+                changed = true;
+            }
+
+            pattern3.reset(s);
+            if (pattern3.find()) {
+                s = s.substring(0, pattern3.start(1)) + s.substring(pattern3.end(1));
+                changed = true;
+            }
+
+            if (changed) {
+                s.getChars(0, s.length(), line, 0);
+                length = s.length();
+            }
+        }
+    }
+
+    private void rawFill() throws IOException {
+        if (bufferCount == -1) {
+            length = -1;
+            return;
+        }
+
+        int i = 0;
+        boolean fillNonEOL = true;
+        outer:
+        while (true) {
+            if (fillNonEOL) {
+                int p;
+                for (p = bufferOffset; p < bufferCount; p++) {
+                    char c = buffer[p];
+                    if (c == '\r' || c == '\n') {
+                        bufferOffset = p;
+                        fillNonEOL = false;
+                        continue outer;
+                    }
+                    if (i >= line.length) {
+                        // copy and enlarge the line array
+                        char[] newLine = new char[line.length * 2];
+                        System.arraycopy(line, 0, newLine, 0, line.length);
+                        line = newLine;
+                    }
+                    line[i++] = c;
+                }
+                bufferOffset = p;
+            } else {
+                int p;
+                for (p = bufferOffset; p < bufferCount; p++) {
+                    char c = buffer[p];
+                    if (c != '\r' && c != '\n') {
+                        bufferOffset = p;
+                        length = i;
+                        index = 0;
+                        return;
+                    }
+                    line[i++] = c;
+                }
+                bufferOffset = p;
+            }
+            if (bufferCount == -1) {
+                if (i == 0) {
+                    length = -1;
+                } else {
+                    length = i;
+                }
+                index = 0;
+                return;
+            }
+            if (bufferOffset != bufferCount) {
+                System.out.println(bufferOffset);
+                System.out.println(bufferCount);
+                throw new InternalError("how did we get here");
+            }
+            // load more data and try again.
+            bufferCount = reader.read(buffer, 0, buffer.length);
+            bufferOffset = 0;
+        }
+    }
+
+    public int read() throws java.io.IOException {
+        read(one, 0, 1);
+        return one[0];
+    }
+
+    public int read(char[] buffer) throws java.io.IOException {
+        return read(buffer, 0, buffer.length);
+    }
+
+    public int read(char[] b, int off, int len) throws java.io.IOException {
+        if (length == -1) {
+            return -1;
+        }
+
+        if (index == length) {
+            fill();
+            if (length == -1) {
+                return -1;
+            }
+        }
+        int n = Math.min(length - index, Math.min(b.length - off, len));
+        // System.out.printf("%d %d %d %d %d\n", index, length, off, len, n);
+        System.arraycopy(line, index, b, off, n);
+        index += n;
+        return n;
+    }
+
+    public long skip(long n) throws java.io.IOException {
+        long result = n;
+        while (n-- > 0) read();
+        return result;
+    }
+
+    public boolean ready() throws java.io.IOException {
+        return reader.ready() || (line != null && length > 0);
+    }
+
+    public boolean markSupported() {
+        return false;
+    }
+
+    public void mark(int unused) throws java.io.IOException {
+        throw new UnsupportedOperationException("mark not supported");
+    }
+
+    public void reset() throws java.io.IOException {
+        reader.reset();
+        line = null;
+        index = 0;
+    }
+
+    public void close() throws java.io.IOException {
+        reader.close();
+        line = null;
+        index = 0;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/LogCompilation.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,177 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/**
+ * The main command line driver of a parser for LogCompilation output.
+ * @author never
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+import java.util.*;
+import org.xml.sax.*;
+import org.xml.sax.helpers.*;
+
+public class LogCompilation extends DefaultHandler implements ErrorHandler, Constants {
+
+    public static void usage(int exitcode) {
+        System.out.println("Usage: LogCompilation [ -v ] [ -c ] [ -s ] [ -e | -N ] file1 ...");
+        System.out.println("  -c:   clean up malformed 1.5 xml");
+        System.out.println("  -i:   print inlining decisions");
+        System.out.println("  -S:   print compilation statistics");
+        System.out.println("  -s:   sort events by start time");
+        System.out.println("  -e:   sort events by elapsed time");
+        System.out.println("  -N:   sort events by name and start");
+        System.exit(exitcode);
+    }
+
+    public static void main(String[] args) throws Exception {
+        Comparator<LogEvent> defaultSort = LogParser.sortByStart;
+        boolean statistics = false;
+        boolean printInlining = false;
+        boolean cleanup = false;
+        int index = 0;
+
+        while (args.length > index) {
+            if (args[index].equals("-e")) {
+                defaultSort = LogParser.sortByElapsed;
+                index++;
+            } else if (args[index].equals("-n")) {
+                defaultSort = LogParser.sortByNameAndStart;
+                index++;
+            } else if (args[index].equals("-s")) {
+                defaultSort = LogParser.sortByStart;
+                index++;
+            } else if (args[index].equals("-c")) {
+                cleanup = true;
+                index++;
+            } else if (args[index].equals("-S")) {
+                statistics = true;
+                index++;
+            } else if (args[index].equals("-h")) {
+                usage(0);
+            } else if (args[index].equals("-i")) {
+                printInlining = true;
+                index++;
+            } else {
+                break;
+            }
+        }
+
+        if (index >= args.length) {
+            usage(1);
+        }
+
+        while (index < args.length) {
+            ArrayList<LogEvent> events = LogParser.parse(args[index], cleanup);
+
+            if (statistics) {
+                printStatistics(events, System.out);
+            } else {
+                Collections.sort(events, defaultSort);
+                for (LogEvent c : events) {
+                    if (printInlining && c instanceof Compilation) {
+                        Compilation comp = (Compilation)c;
+                        comp.print(System.out, true);
+                    } else {
+                        c.print(System.out);
+                    }
+                }
+            }
+            index++;
+        }
+    }
+
+    public static void printStatistics(ArrayList<LogEvent> events, PrintStream out) {
+        long cacheSize = 0;
+        long maxCacheSize = 0;
+        int nmethodsCreated = 0;
+        int nmethodsLive = 0;
+        int[] attempts = new int[32];
+        double regallocTime = 0;
+        int maxattempts = 0;
+
+        LinkedHashMap<String, Double> phaseTime = new LinkedHashMap<String, Double>(7);
+        LinkedHashMap<String, Integer> phaseNodes = new LinkedHashMap<String, Integer>(7);
+        double elapsed = 0;
+
+        for (LogEvent e : events) {
+            if (e instanceof Compilation) {
+                Compilation c = (Compilation) e;
+                c.printShort(out);
+                out.printf(" %6.4f\n", c.getElapsedTime());
+                attempts[c.getAttempts()]++;
+                maxattempts = Math.max(maxattempts,c.getAttempts());
+                elapsed += c.getElapsedTime();
+                for (Phase phase : c.getPhases()) {
+                    out.printf("\t%s %6.4f\n", phase.getName(), phase.getElapsedTime());
+                    Double v = phaseTime.get(phase.getName());
+                    if (v == null) {
+                        v = Double.valueOf(0.0);
+                    }
+                    phaseTime.put(phase.getName(), Double.valueOf(v.doubleValue() + phase.getElapsedTime()));
+
+                    Integer v2 = phaseNodes.get(phase.getName());
+                    if (v2 == null) {
+                        v2 = Integer.valueOf(0);
+                    }
+                    phaseNodes.put(phase.getName(), Integer.valueOf(v2.intValue() + phase.getNodes()));
+                }
+            } else if (e instanceof MakeNotEntrantEvent) {
+                MakeNotEntrantEvent mne = (MakeNotEntrantEvent) e;
+                NMethod nm = mne.getNMethod();
+                if (mne.isZombie()) {
+                    if (nm == null) {
+                        System.err.println(mne.getId());
+                    }
+                    cacheSize -= nm.getSize();
+                    nmethodsLive--;
+                }
+            } else if (e instanceof NMethod) {
+                nmethodsLive++;
+                nmethodsCreated++;
+                NMethod nm = (NMethod) e;
+                cacheSize += nm.getSize();
+                maxCacheSize = Math.max(cacheSize, maxCacheSize);
+            }
+        }
+        out.printf("NMethods: %d created %d live %d bytes (%d peak) in the code cache\n",
+                          nmethodsCreated, nmethodsLive, cacheSize, maxCacheSize);
+        out.println("Phase times:");
+        for (String name : phaseTime.keySet()) {
+            Double v = phaseTime.get(name);
+            Integer v2 = phaseNodes.get(name);
+            out.printf("%20s %6.4f %d\n", name, v.doubleValue(), v2.intValue());
+        }
+        out.printf("%20s %6.4f\n", "total", elapsed);
+
+        if (maxattempts > 0) {
+            out.println("Distribution of regalloc passes:");
+            for (int i = 0; i <= maxattempts; i++) {
+                out.printf("%2d %8d\n", i, attempts[i]);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/LogEvent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+import java.util.*;
+
+public interface LogEvent {
+    public double getStart();
+
+    public double getElapsedTime();
+
+    public Compilation getCompilation();
+
+    public void print(PrintStream stream);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/LogParser.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,430 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+/**
+ * A SAX based parser of LogCompilation output from HotSpot.  It takes a complete
+ * @author never
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.FileReader;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Stack;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+import org.xml.sax.Attributes;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.helpers.DefaultHandler;
+
+public class LogParser extends DefaultHandler implements ErrorHandler, Constants {
+
+    static final HashMap<String, String> typeMap;
+    static {
+        typeMap = new HashMap<String, String>();
+        typeMap.put("[I", "int[]");
+        typeMap.put("[C", "char[]");
+        typeMap.put("[Z", "boolean[]");
+        typeMap.put("[L", "Object[]");
+        typeMap.put("[B", "byte[]");
+    }
+
+    static Comparator<LogEvent> sortByStart = new Comparator<LogEvent>() {
+
+        public int compare(LogEvent a, LogEvent b) {
+            double difference = (a.getStart() - b.getStart());
+            if (difference < 0) {
+                return -1;
+            }
+            if (difference > 0) {
+                return 1;
+            }
+            return 0;
+        }
+
+        @Override
+        public boolean equals(Object other) {
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return 7;
+        }
+    };
+    static Comparator<LogEvent> sortByNameAndStart = new Comparator<LogEvent>() {
+
+        public int compare(LogEvent a, LogEvent b) {
+            Compilation c1 = a.getCompilation();
+            Compilation c2 = b.getCompilation();
+            if (c1 != null && c2 != null) {
+                int result = c1.getMethod().toString().compareTo(c2.getMethod().toString());
+                if (result != 0) {
+                    return result;
+                }
+            }
+            double difference = (a.getStart() - b.getStart());
+            if (difference < 0) {
+                return -1;
+            }
+            if (difference > 0) {
+                return 1;
+            }
+            return 0;
+        }
+
+        public boolean equals(Object other) {
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return 7;
+        }
+    };
+    static Comparator<LogEvent> sortByElapsed = new Comparator<LogEvent>() {
+
+        public int compare(LogEvent a, LogEvent b) {
+            double difference = (a.getElapsedTime() - b.getElapsedTime());
+            if (difference < 0) {
+                return -1;
+            }
+            if (difference > 0) {
+                return 1;
+            }
+            return 0;
+        }
+
+        @Override
+        public boolean equals(Object other) {
+            return false;
+        }
+
+        @Override
+        public int hashCode() {
+            return 7;
+        }
+    };
+
+    private ArrayList<LogEvent> events = new ArrayList<LogEvent>();
+
+    private HashMap<String, String> types = new HashMap<String, String>();
+    private HashMap<String, Method> methods = new HashMap<String, Method>();
+    private LinkedHashMap<String, NMethod> nmethods = new LinkedHashMap<String, NMethod>();
+    private HashMap<String, Compilation> compiles = new HashMap<String, Compilation>();
+    private String failureReason;
+    private int bci;
+    private Stack<CallSite> scopes = new Stack<CallSite>();
+    private Compilation compile;
+    private CallSite site;
+    private Stack<Phase> phaseStack = new Stack<Phase>();
+    private UncommonTrapEvent currentTrap;
+
+    long parseLong(String l) {
+        try {
+            return Long.decode(l).longValue();
+        } catch (NumberFormatException nfe) {
+            int split = l.length() - 8;
+            String s1 = "0x" + l.substring(split);
+            String s2 = l.substring(0, split);
+            long v1 = Long.decode(s1).longValue() & 0xffffffffL;
+            long v2 = (Long.decode(s2).longValue() & 0xffffffffL) << 32;
+            if (!l.equals("0x" + Long.toHexString(v1 + v2))) {
+                System.out.println(l);
+                System.out.println(s1);
+                System.out.println(s2);
+                System.out.println(v1);
+                System.out.println(v2);
+                System.out.println(Long.toHexString(v1 + v2));
+                throw new InternalError("bad conversion");
+            }
+            return v1 + v2;
+        }
+    }
+
+    public static ArrayList<LogEvent> parse(String file, boolean cleanup) throws Exception {
+        return parse(new FileReader(file), cleanup);
+    }
+
+    public static ArrayList<LogEvent> parse(Reader reader, boolean cleanup) throws Exception {
+        // Create the XML input factory
+        SAXParserFactory factory = SAXParserFactory.newInstance();
+
+        // Create the XML LogEvent reader
+        SAXParser p = factory.newSAXParser();
+
+        if (cleanup) {
+            // some versions of the log have slightly malformed XML, so clean it
+            // up before passing it to SAX
+            reader = new LogCleanupReader(reader);
+        }
+
+        LogParser log = new LogParser();
+        p.parse(new InputSource(reader), log);
+
+        // Associate compilations with their NMethods
+        for (NMethod nm : log.nmethods.values()) {
+            Compilation c = log.compiles.get(nm.getId());
+            nm.setCompilation(c);
+            // Native wrappers for methods don't have a compilation
+            if (c != null) {
+                c.setNMethod(nm);
+            }
+        }
+
+        // Initially we want the LogEvent log sorted by timestamp
+        Collections.sort(log.events, sortByStart);
+
+        return log.events;
+    }
+
+    String search(Attributes attr, String name) {
+        return search(attr, name, null);
+    }
+
+    String search(Attributes attr, String name, String defaultValue) {
+        String result = attr.getValue(name);
+        if (result != null) {
+            return result;
+        }
+        if (defaultValue != null) {
+            return defaultValue;
+        }
+        for (int i = 0; i < attr.getLength(); i++) {
+            System.out.println(attr.getQName(i) + " " + attr.getValue(attr.getQName(i)));
+        }
+        throw new InternalError("can't find " + name);
+    }
+    int indent = 0;
+    String compile_id;
+
+    String type(String id) {
+        String result = types.get(id);
+        if (result == null) {
+            throw new InternalError(id);
+        }
+        String remapped = typeMap.get(result);
+        if (remapped != null) {
+            return remapped;
+        }
+        return result;
+    }
+
+    void type(String id, String name) {
+        assert type(id) == null;
+        types.put(id, name);
+    }
+
+    Method method(String id) {
+        Method result = methods.get(id);
+        if (result == null) {
+            throw new InternalError(id);
+        }
+        return result;
+    }
+
+    public String makeId(Attributes atts) {
+        String id = atts.getValue("compile_id");
+        String kind = atts.getValue("kind");
+        if (kind != null && kind.equals("osr")) {
+            id += "%";
+        }
+        return id;
+    }
+
+    @Override
+    public void startElement(String uri,
+            String localName,
+            String qname,
+            Attributes atts) {
+        if (qname.equals("phase")) {
+            Phase p = new Phase(search(atts, "name"),
+                    Double.parseDouble(search(atts, "stamp")),
+                    Integer.parseInt(search(atts, "nodes")));
+            phaseStack.push(p);
+        } else if (qname.equals("phase_done")) {
+            Phase p = phaseStack.pop();
+            p.setEndNodes(Integer.parseInt(search(atts, "nodes")));
+            p.setEnd(Double.parseDouble(search(atts, "stamp")));
+            compile.getPhases().add(p);
+        } else if (qname.equals("task")) {
+            compile = new Compilation(Integer.parseInt(search(atts, "compile_id", "-1")));
+            compile.setStart(Double.parseDouble(search(atts, "stamp")));
+            compile.setICount(search(atts, "count", "0"));
+            compile.setBCount(search(atts, "backedge_count", "0"));
+
+            String method = atts.getValue("method");
+            int space = method.indexOf(' ');
+            method = method.substring(0, space) + "::" +
+                    method.substring(space + 1, method.indexOf(' ', space + 1) + 1);
+            String compiler = atts.getValue("compiler");
+            if (compiler == null) {
+                compiler = "";
+            }
+            String kind = atts.getValue("compile_kind");
+            if (kind == null) {
+                kind = "normal";
+            }
+            if (kind.equals("osr")) {
+                compile.setOsr(true);
+                compile.setOsr_bci(Integer.parseInt(search(atts, "osr_bci")));
+            } else if (kind.equals("c2i")) {
+                compile.setSpecial("--- adapter " + method);
+            } else {
+                compile.setSpecial(compile.getId() + " " + method + " (0 bytes)");
+            }
+            events.add(compile);
+            compiles.put(makeId(atts), compile);
+        } else if (qname.equals("type")) {
+            type(search(atts, "id"), search(atts, "name"));
+        } else if (qname.equals("bc")) {
+            bci = Integer.parseInt(search(atts, "bci"));
+        } else if (qname.equals("klass")) {
+            type(search(atts, "id"), search(atts, "name"));
+        } else if (qname.equals("method")) {
+            String id = search(atts, "id");
+            Method m = new Method();
+            m.setHolder(type(search(atts, "holder")));
+            m.setName(search(atts, "name"));
+            m.setReturnType(type(search(atts, "return")));
+            m.setArguments(search(atts, "arguments", "void"));
+            m.setBytes(search(atts, "bytes"));
+            m.setIICount(search(atts, "iicount"));
+            m.setFlags(search(atts, "flags"));
+            methods.put(id, m);
+        } else if (qname.equals("call")) {
+            site = new CallSite(bci, method(search(atts, "method")));
+            site.setCount(Integer.parseInt(search(atts, "count")));
+            String receiver = atts.getValue("receiver");
+            if (receiver != null) {
+                site.setReceiver(type(receiver));
+                site.setReceiver_count(Integer.parseInt(search(atts, "receiver_count")));
+            }
+            scopes.peek().add(site);
+        } else if (qname.equals("regalloc")) {
+            compile.setAttempts(Integer.parseInt(search(atts, "attempts")));
+        } else if (qname.equals("inline_fail")) {
+            scopes.peek().last().setReason(search(atts, "reason"));
+        } else if (qname.equals("failure")) {
+            failureReason = search(atts, "reason");
+        } else if (qname.equals("task_done")) {
+            compile.setEnd(Double.parseDouble(search(atts, "stamp")));
+            if (Integer.parseInt(search(atts, "success")) == 0) {
+                compile.setFailureReason(failureReason);
+            }
+        } else if (qname.equals("make_not_entrant")) {
+            String id = makeId(atts);
+            NMethod nm = nmethods.get(id);
+            if (nm == null) throw new InternalError();
+            LogEvent e = new MakeNotEntrantEvent(Double.parseDouble(search(atts, "stamp")), id,
+                                                 atts.getValue("zombie") != null, nm);
+            events.add(e);
+        } else if (qname.equals("uncommon_trap")) {
+            String id = atts.getValue("compile_id");
+            if (id != null) {
+                id = makeId(atts);
+                currentTrap = new UncommonTrapEvent(Double.parseDouble(search(atts, "stamp")),
+                        id,
+                        atts.getValue("reason"),
+                        atts.getValue("action"),
+                        Integer.parseInt(search(atts, "count", "0")));
+                events.add(currentTrap);
+            } else {
+                // uncommon trap inserted during parsing.
+                // ignore for now
+            }
+        } else if (qname.equals("jvms")) {
+            // <jvms bci='4' method='java/io/DataInputStream readChar ()C' bytes='40' count='5815' iicount='20815'/>
+            if (currentTrap != null) {
+                currentTrap.addJVMS(atts.getValue("method"), Integer.parseInt(atts.getValue("bci")));
+            } else {
+                System.err.println("Missing uncommon_trap for jvms");
+            }
+        } else if (qname.equals("nmethod")) {
+            String id = makeId(atts);
+            NMethod nm = new NMethod(Double.parseDouble(search(atts, "stamp")),
+                    id,
+                    parseLong(atts.getValue("address")),
+                    parseLong(atts.getValue("size")));
+            nmethods.put(id, nm);
+            events.add(nm);
+        } else if (qname.equals("parse")) {
+            Method m = method(search(atts, "method"));
+            if (scopes.size() == 0) {
+                compile.setMethod(m);
+                scopes.push(compile.getCall());
+            } else {
+                if (site.getMethod() == m) {
+                    scopes.push(site);
+                } else if (scopes.peek().getCalls().size() > 2 && m == scopes.peek().last(-2).getMethod()) {
+                    scopes.push(scopes.peek().last(-2));
+                } else {
+                    System.out.println(site.getMethod());
+                    System.out.println(m);
+                    throw new InternalError("call site and parse don't match");
+                }
+            }
+        }
+    }
+
+    @Override
+    public void endElement(String uri,
+            String localName,
+            String qname) {
+        if (qname.equals("parse")) {
+            indent -= 2;
+            scopes.pop();
+        } else if (qname.equals("uncommon_trap")) {
+            currentTrap = null;
+        } else if (qname.equals("task")) {
+            types.clear();
+            methods.clear();
+            site = null;
+        }
+    }
+
+    @Override
+    public void warning(org.xml.sax.SAXParseException e) {
+        System.err.println(e.getMessage() + " at line " + e.getLineNumber() + ", column " + e.getColumnNumber());
+        e.printStackTrace();
+    }
+
+    @Override
+    public void error(org.xml.sax.SAXParseException e) {
+        System.err.println(e.getMessage() + " at line " + e.getLineNumber() + ", column " + e.getColumnNumber());
+        e.printStackTrace();
+    }
+
+    @Override
+    public void fatalError(org.xml.sax.SAXParseException e) {
+        System.err.println(e.getMessage() + " at line " + e.getLineNumber() + ", column " + e.getColumnNumber());
+        e.printStackTrace();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/MakeNotEntrantEvent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+
+class MakeNotEntrantEvent extends BasicLogEvent {
+    private final boolean zombie;
+
+    private NMethod nmethod;
+
+    MakeNotEntrantEvent(double s, String i, boolean z, NMethod nm) {
+        super(s, i);
+        zombie = z;
+        nmethod = nm;
+    }
+
+    public NMethod getNMethod() {
+        return nmethod;
+    }
+
+    public void print(PrintStream stream) {
+        if (isZombie()) {
+            stream.printf("%s make_zombie\n", getId());
+        } else {
+            stream.printf("%s make_not_entrant\n", getId());
+        }
+    }
+
+    public boolean isZombie() {
+        return zombie;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/Method.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.util.Arrays;
+
+public class Method implements Constants {
+
+    private String holder;
+    private String name;
+    private String returnType;
+    private String arguments;
+    private String bytes;
+    private String iicount;
+    private String flags;
+
+    String decodeFlags(int osr_bci) {
+        int f = Integer.parseInt(getFlags());
+        char[] c = new char[4];
+        Arrays.fill(c, ' ');
+        if (osr_bci >= 0) {
+            c[0] = '%';
+        }
+        if ((f & JVM_ACC_SYNCHRONIZED) != 0) {
+            c[1] = 's';
+        }
+        return new String(c);
+    }
+
+    String format(int osr_bci) {
+        if (osr_bci >= 0) {
+            return getHolder().replace('/', '.') + "::" + getName() + " @ " + osr_bci + " (" + getBytes() + " bytes)";
+        } else {
+            return getHolder().replace('/', '.') + "::" + getName() + " (" + getBytes() + " bytes)";
+        }
+    }
+
+    @Override
+    public String toString() {
+        return getHolder().replace('/', '.') + "::" + getName() + " (" + getBytes() + " bytes)";
+    }
+
+    public String getHolder() {
+        return holder;
+    }
+
+    public void setHolder(String holder) {
+        this.holder = holder;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getReturnType() {
+        return returnType;
+    }
+
+    public void setReturnType(String returnType) {
+        this.returnType = returnType;
+    }
+
+    public String getArguments() {
+        return arguments;
+    }
+
+    public void setArguments(String arguments) {
+        this.arguments = arguments;
+    }
+
+    public String getBytes() {
+        return bytes;
+    }
+
+    public void setBytes(String bytes) {
+        this.bytes = bytes;
+    }
+
+    public String getIICount() {
+        return iicount;
+    }
+
+    public void setIICount(String iicount) {
+        this.iicount = iicount;
+    }
+
+    public String getFlags() {
+        return flags;
+    }
+
+    public void setFlags(String flags) {
+        this.flags = flags;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/NMethod.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+
+public class NMethod extends BasicLogEvent {
+
+    private long address;
+    private long size;
+
+    NMethod(double s, String i, long a, long sz) {
+        super(s, i);
+        address = a;
+        size = sz;
+    }
+
+    public void print(PrintStream out) {
+        // XXX Currently we do nothing
+        // throw new InternalError();
+    }
+
+    public long getAddress() {
+        return address;
+    }
+
+    public void setAddress(long address) {
+        this.address = address;
+    }
+
+    public long getSize() {
+        return size;
+    }
+
+    public void setSize(long size) {
+        this.size = size;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/Phase.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+
+public class Phase extends BasicLogEvent {
+
+    private final int startNodes;
+    private int endNodes;
+
+    Phase(String n, double s, int nodes) {
+        super(s, n);
+        startNodes = nodes;
+    }
+
+    int getNodes() {
+        return getStartNodes();
+    }
+
+    void setEndNodes(int n) {
+        endNodes = n;
+    }
+
+    public String getName() {
+        return getId();
+    }
+
+    public int getStartNodes() {
+        return startNodes;
+    }
+
+    public int getEndNodes() {
+        return endNodes;
+    }
+
+    @Override
+    public void print(PrintStream stream) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/LogCompilation/src/com/sun/hotspot/tools/compiler/UncommonTrapEvent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+package com.sun.hotspot.tools.compiler;
+
+import java.io.PrintStream;
+
+class UncommonTrapEvent extends BasicLogEvent {
+
+    private final String reason;
+    private final String action;
+    private int count;
+    private String jvms = "";
+
+    UncommonTrapEvent(double s, String i, String r, String a, int c) {
+        super(s, i);
+        reason = r;
+        action = a;
+        count = c;
+    }
+
+
+    public void addJVMS(String method, int bci) {
+        setJvms(getJvms() + "  @" + bci + " " + method + "\n");
+    }
+
+    public void updateCount(UncommonTrapEvent trap) {
+        setCount(Math.max(getCount(), trap.getCount()));
+    }
+
+    public void print(PrintStream stream) {
+        stream.printf("%s uncommon trap %s %s\n", getId(), getReason(), getAction());
+        stream.print(getJvms());
+    }
+
+    public String getReason() {
+        return reason;
+    }
+
+    public String getAction() {
+        return action;
+    }
+
+    public int getCount() {
+        return count;
+    }
+
+    public void setCount(int count) {
+        this.count = count;
+    }
+
+    public String getJvms() {
+        return jvms;
+    }
+
+    public void setJvms(String jvms) {
+        this.jvms = jvms;
+    }
+
+    public void setCompilation(Compilation compilation) {
+        this.compilation = compilation;
+    }
+}
--- a/hotspot/src/share/tools/MakeDeps/BuildConfig.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/tools/MakeDeps/BuildConfig.java	Fri Apr 10 13:05:12 2009 -0700
@@ -247,6 +247,7 @@
         sysDefines.add("HOTSPOT_BUILD_USER="+System.getProperty("user.name"));
         sysDefines.add("HOTSPOT_BUILD_TARGET=\\\""+get("Build")+"\\\"");
         sysDefines.add("_JNI_IMPLEMENTATION_");
+        sysDefines.add("HOTSPOT_LIB_ARCH=\\\"i486\\\"");
 
         sysDefines.addAll(defines);
 
--- a/hotspot/src/share/tools/MakeDeps/Database.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/tools/MakeDeps/Database.java	Fri Apr 10 13:05:12 2009 -0700
@@ -365,7 +365,7 @@
 
     // HACK ALERT. The compilation of ad_<arch> files is very slow.
     // We want to start compiling them as early as possible. The compilation
-    // order on unix is dependant on the order we emit files here.
+    // order on unix is dependent on the order we emit files here.
     // By sorting the output before emitting it, we expect
     // that ad_<arch> will be compiled early.
     boolean shouldSortObjFiles = true;
--- a/hotspot/src/share/tools/MakeDeps/WinGammaPlatformVC7.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/tools/MakeDeps/WinGammaPlatformVC7.java	Fri Apr 10 13:05:12 2009 -0700
@@ -27,6 +27,8 @@
 
 public class WinGammaPlatformVC7 extends WinGammaPlatform {
 
+    String projectVersion() {return "7.10";};
+
     public void writeProjectFile(String projectFileName, String projectName,
                                  Vector allConfigs) throws IOException {
         System.out.println();
@@ -40,7 +42,7 @@
             "VisualStudioProject",
             new String[] {
                 "ProjectType", "Visual C++",
-                "Version", "7.10",
+                "Version", projectVersion(),
                 "Name", projectName,
                 "ProjectGUID", "{8822CB5C-1C41-41C2-8493-9F6E1994338B}",
                 "SccProjectName", "",
@@ -417,7 +419,9 @@
             new String[] {
                 "Name", "VCPreLinkEventTool",
                 "Description", BuildConfig.getFieldString(null, "PrelinkDescription"),
-                "CommandLine", cfg.expandFormat(BuildConfig.getFieldString(null, "PrelinkCommand").replace('\t', '\n'))
+                //Caution: String.replace(String,String) is available from JDK5 onwards only
+                "CommandLine", cfg.expandFormat(BuildConfig.getFieldString(null, "PrelinkCommand").replace
+                   ("\t", "&#x0D;&#x0A;"))
             }
             );
 
@@ -542,25 +546,41 @@
 }
 
 class CompilerInterfaceVC7 extends CompilerInterface {
-    Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir) {
-        Vector rv = new Vector();
+    void getBaseCompilerFlags_common(Vector defines, Vector includes, String outDir,Vector rv) {
 
         // advanced M$ IDE (2003) can only recognize name if it's first or
         // second attribute in the tag - go guess
         addAttr(rv, "Name", "VCCLCompilerTool");
         addAttr(rv, "AdditionalIncludeDirectories", Util.join(",", includes));
-        addAttr(rv, "PreprocessorDefinitions", Util.join(";", defines).replace("\"","&quot;"));
-        addAttr(rv, "UsePrecompiledHeader", "3");
-        addAttr(rv, "PrecompiledHeaderThrough", "incls"+Util.sep+"_precompiled.incl");
+        addAttr(rv, "PreprocessorDefinitions",
+                                Util.join(";", defines).replace("\"","&quot;"));
+        addAttr(rv, "PrecompiledHeaderThrough",
+                                "incls"+Util.sep+"_precompiled.incl");
         addAttr(rv, "PrecompiledHeaderFile", outDir+Util.sep+"vm.pch");
         addAttr(rv, "AssemblerListingLocation", outDir);
         addAttr(rv, "ObjectFile", outDir+Util.sep);
         addAttr(rv, "ProgramDataBaseFileName", outDir+Util.sep+"vm.pdb");
+        // Set /nologo optin
         addAttr(rv, "SuppressStartupBanner", "TRUE");
+        // Surpass the default /Tc or /Tp. 0 is compileAsDefault
         addAttr(rv, "CompileAs", "0");
+        // Set /W3 option. 3 is warningLevel_3
         addAttr(rv, "WarningLevel", "3");
+        // Set /WX option,
         addAttr(rv, "WarnAsError", "TRUE");
+        // Set /GS option
         addAttr(rv, "BufferSecurityCheck", "FALSE");
+        // Set /Zi option. 3 is debugEnabled
+        addAttr(rv, "DebugInformationFormat", "3");
+    }
+    Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir) {
+        Vector rv = new Vector();
+
+        getBaseCompilerFlags_common(defines,includes, outDir, rv);
+        // Set /Yu option. 3 is pchUseUsingSpecific
+        // Note: Starting VC8 pchUseUsingSpecific is 2 !!!
+        addAttr(rv, "UsePrecompiledHeader", "3");
+        // Set /EHsc- option
         addAttr(rv, "ExceptionHandling", "FALSE");
 
         return rv;
@@ -579,27 +599,39 @@
                 "/export:jio_vsnprintf ");
         addAttr(rv, "AdditionalDependencies", "Wsock32.lib winmm.lib");
         addAttr(rv, "OutputFile", outDll);
+        // Set /INCREMENTAL option. 1 is linkIncrementalNo
         addAttr(rv, "LinkIncremental", "1");
         addAttr(rv, "SuppressStartupBanner", "TRUE");
         addAttr(rv, "ModuleDefinitionFile", outDir+Util.sep+"vm.def");
         addAttr(rv, "ProgramDatabaseFile", outDir+Util.sep+"vm.pdb");
+        // Set /SUBSYSTEM option. 2 is subSystemWindows
         addAttr(rv, "SubSystem", "2");
         addAttr(rv, "BaseAddress", "0x8000000");
         addAttr(rv, "ImportLibrary", outDir+Util.sep+"jvm.lib");
+        // Set /MACHINE option. 1 is machineX86
         addAttr(rv, "TargetMachine", "1");
 
         return rv;
     }
 
+    void  getDebugCompilerFlags_common(String opt,Vector rv) {
+
+        // Set /On option
+        addAttr(rv, "Optimization", opt);
+        // Set /FR option. 1 is brAllInfo
+        addAttr(rv, "BrowseInformation", "1");
+        addAttr(rv, "BrowseInformationFile", "$(IntDir)" + Util.sep);
+        // Set /MD option. 2 is rtMultiThreadedDLL
+        addAttr(rv, "RuntimeLibrary", "2");
+        // Set /Oy- option
+        addAttr(rv, "OmitFramePointers", "FALSE");
+
+    }
+
     Vector getDebugCompilerFlags(String opt) {
         Vector rv = new Vector();
 
-        addAttr(rv, "Optimization", opt);
-        addAttr(rv, "OptimizeForProcessor", "1");
-        addAttr(rv, "DebugInformationFormat", "3");
-        addAttr(rv, "RuntimeLibrary", "2");
-        addAttr(rv, "BrowseInformation", "1");
-        addAttr(rv, "BrowseInformationFile", "$(IntDir)" + Util.sep);
+        getDebugCompilerFlags_common(opt,rv);
 
         return rv;
     }
@@ -607,18 +639,29 @@
     Vector getDebugLinkerFlags() {
         Vector rv = new Vector();
 
-        addAttr(rv, "GenerateDebugInformation", "TRUE");
+        addAttr(rv, "GenerateDebugInformation", "TRUE"); // == /DEBUG option
 
         return rv;
     }
 
+    void getProductCompilerFlags_common(Vector rv) {
+        // Set /O2 option. 2 is optimizeMaxSpeed
+        addAttr(rv, "Optimization", "2");
+        // Set /Oy- option
+        addAttr(rv, "OmitFramePointers", "FALSE");
+    }
+
     Vector getProductCompilerFlags() {
         Vector rv = new Vector();
 
-        addAttr(rv, "Optimization", "2");
+        getProductCompilerFlags_common(rv);
+        // Set /Ob option.  1 is expandOnlyInline
         addAttr(rv, "InlineFunctionExpansion", "1");
+        // Set /GF option.
         addAttr(rv, "StringPooling", "TRUE");
+        // Set /MD option. 2 is rtMultiThreadedDLL
         addAttr(rv, "RuntimeLibrary", "2");
+        // Set /Gy option
         addAttr(rv, "EnableFunctionLevelLinking", "TRUE");
 
         return rv;
@@ -627,7 +670,9 @@
     Vector getProductLinkerFlags() {
         Vector rv = new Vector();
 
+        // Set /OPT:REF option. 2 is optReferences
         addAttr(rv, "OptimizeReferences", "2");
+        // Set /OPT:optFolding option. 2 is optFolding
         addAttr(rv, "EnableCOMDATFolding", "2");
 
         return rv;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/MakeDeps/WinGammaPlatformVC8.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2005-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+import java.io.*;
+import java.util.*;
+
+public class WinGammaPlatformVC8 extends WinGammaPlatformVC7 {
+
+    String projectVersion() {return "8.00";};
+
+}
+
+class CompilerInterfaceVC8 extends CompilerInterfaceVC7 {
+
+    Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir) {
+        Vector rv = new Vector();
+
+        getBaseCompilerFlags_common(defines,includes, outDir, rv);
+        // Set /Yu option. 2 is pchUseUsingSpecific
+        addAttr(rv, "UsePrecompiledHeader", "2");
+        // Set /EHsc- option. 0 is cppExceptionHandlingNo
+        addAttr(rv, "ExceptionHandling", "0");
+
+        return rv;
+    }
+
+
+    Vector getDebugCompilerFlags(String opt) {
+        Vector rv = new Vector();
+
+        getDebugCompilerFlags_common(opt,rv);
+
+        return rv;
+    }
+
+    Vector getProductCompilerFlags() {
+        Vector rv = new Vector();
+
+        getProductCompilerFlags_common(rv);
+
+        return rv;
+    }
+
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/share/tools/MakeDeps/WinGammaPlatformVC9.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2005-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ *
+ */
+
+import java.io.*;
+import java.util.*;
+
+public class WinGammaPlatformVC9 extends WinGammaPlatformVC8 {
+
+    String projectVersion() {return "9.00";};
+
+}
+
+class CompilerInterfaceVC9 extends CompilerInterfaceVC8 {
+}
--- a/hotspot/src/share/vm/adlc/Doc/Syntax.doc	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/Doc/Syntax.doc	Fri Apr 10 13:05:12 2009 -0700
@@ -88,7 +88,7 @@
                          // these are used for constraints, etc.
 
 alloc_class class1(AX, BX); // form an allocation class of registers
-                            // used by the register allocator for seperate
+                            // used by the register allocator for separate
                             // allocation of target register classes
 
 	3. Pipeline Syntax for Scheduling
@@ -150,7 +150,7 @@
 		b. %}  (block terminator)
 		c. EOF (file terminator)
 
-	4. Each statement must start on a seperate line
+	4. Each statement must start on a separate line
 
 	5. Identifiers cannot contain: (){}%;,"/\
 
--- a/hotspot/src/share/vm/adlc/adlc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/adlc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -44,7 +44,7 @@
 #error "Something is wrong with the detection of MSC_VER in the makefiles"
 #endif
 
-#if _MSC_VER >= 1400 && !defined(_WIN64)
+#if _MSC_VER >= 1400
 #define strdup _strdup
 #endif
 
@@ -79,6 +79,7 @@
 
 // Macros
 // Debugging note:  Put a breakpoint on "abort".
+#undef assert
 #define assert(cond, msg) { if (!(cond)) { fprintf(stderr, "assert fails %s %d: %s\n", __FILE__, __LINE__, msg); abort(); }}
 #define max(a, b)   (((a)>(b)) ? (a) : (b))
 
--- a/hotspot/src/share/vm/adlc/adlparse.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/adlparse.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -298,7 +298,7 @@
   rule->count_commutative_op(count);
   if (count > 0) {
     // Clone match rule and swap commutative operation's operands.
-    rule->swap_commutative_op(instr_ident, count, match_rules_cnt);
+    rule->matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
   }
 }
 
@@ -2586,7 +2586,7 @@
   while( _curchar != ')' ) {
     // Get information on the left instruction and its operand
     // left-instructions's number
-    intptr_t   left_inst = get_int();
+    int left_inst = get_int();
     // Left-instruction's operand
     skipws();
     if( _curchar != '.' ) {
@@ -2602,7 +2602,7 @@
 
     skipws();
     // Get information on the right instruction and its operand
-    intptr_t right_inst;        // Right-instructions's number
+    int right_inst;        // Right-instructions's number
     if( isdigit(_curchar) ) {
       right_inst = get_int();
       // Right-instruction's operand
@@ -3497,22 +3497,24 @@
 
     // (1)
     // Check if there is a string to pass through to output
-    char *start = _ptr;       // Record start of the next string
-    while ((_curchar != '$') && ((_curchar != '%') || (*(_ptr+1) != '}')) ) {
-      // If at the start of a comment, skip past it
-      if( (_curchar == '/') && ((*(_ptr+1) == '/') || (*(_ptr+1) == '*')) ) {
-        skipws_no_preproc();
-      } else {
-        // ELSE advance to the next character, or start of the next line
-        next_char_or_line();
+    {
+      char *start = _ptr;       // Record start of the next string
+      while ((_curchar != '$') && ((_curchar != '%') || (*(_ptr+1) != '}')) ) {
+        // If at the start of a comment, skip past it
+        if( (_curchar == '/') && ((*(_ptr+1) == '/') || (*(_ptr+1) == '*')) ) {
+          skipws_no_preproc();
+        } else {
+          // ELSE advance to the next character, or start of the next line
+          next_char_or_line();
+        }
       }
-    }
-    // If a string was found, terminate it and record in EncClass
-    if ( start != _ptr ) {
-      *_ptr  = '\0';          // Terminate the string
-      // Add flag to _strings list indicating we should check _rep_vars
-      format->_strings.addName(NameList::_signal2);
-      format->_strings.addName(start);
+      // If a string was found, terminate it and record in EncClass
+      if ( start != _ptr ) {
+        *_ptr  = '\0';          // Terminate the string
+        // Add flag to _strings list indicating we should check _rep_vars
+        format->_strings.addName(NameList::_signal2);
+        format->_strings.addName(start);
+      }
     }
 
     // (2)
@@ -3563,10 +3565,10 @@
             // copy it and record in FormatRule
             if ( _curchar == '$' ) {
               next_char();          // Move past the '$'
-              char* rep_var = get_ident(); // Nil terminate the variable name
-              rep_var = strdup(rep_var);// Copy the string
+              char* next_rep_var = get_ident(); // Nil terminate the variable name
+              next_rep_var = strdup(next_rep_var);// Copy the string
               *_ptr   = _curchar;     // and replace Nil with original character
-              format->_rep_vars.addName(rep_var);
+              format->_rep_vars.addName(next_rep_var);
               // Add flag to _strings list indicating we should check _rep_vars
               format->_strings.addName(NameList::_signal);
             }
@@ -3714,13 +3716,13 @@
           parse_err(SYNERR, "identifier expected at %c\n", _curchar);
           continue;
         }                            // Check that you have a valid operand
-        const Form *form = instr->_localNames[ident2];
-        if (!form) {
+        const Form *form2 = instr->_localNames[ident2];
+        if (!form2) {
           parse_err(SYNERR, "operand name expected at %s\n", ident2);
           continue;
         }
-        oper = form->is_operand();
-        if (oper == NULL && !form->is_opclass()) {
+        oper = form2->is_operand();
+        if (oper == NULL && !form2->is_opclass()) {
           parse_err(SYNERR, "operand name expected at %s\n", ident2);
           continue;
         }                            // Add operand to list
@@ -4271,7 +4273,7 @@
   int           result;           // Storage for integer result
 
   if( _curline == NULL )          // Return NULL at EOF.
-    return NULL;
+    return 0;
 
   skipws();                       // Skip whitespace before identifier
   start = end = _ptr;             // Start points at first character
@@ -4553,7 +4555,7 @@
 
 //---------------------------ensure_start_of_line------------------------------
 // A preprocessor directive has been encountered.  Be sure it has fallen at
-// the begining of a line, or else report an error.
+// the beginning of a line, or else report an error.
 void ADLParser::ensure_start_of_line(void) {
   if (_curchar == '\n') { next_line(); return; }
   assert( _ptr >= _curline && _ptr < _curline+strlen(_curline),
--- a/hotspot/src/share/vm/adlc/adlparse.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/adlparse.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/adlc/archDesc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/archDesc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -436,10 +436,12 @@
   if ((oper->_matrule) && (oper->_matrule->_lChild == NULL) &&
       (oper->_matrule->_rChild == NULL)) {
 
-    const Form *form = _globalNames[oper->_matrule->_opType];
-    if ((form) && form->is_operand() &&
-        (form->ideal_only() == false)) {
-      add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
+    {
+      const Form *form = _globalNames[oper->_matrule->_opType];
+      if ((form) && form->is_operand() &&
+          (form->ideal_only() == false)) {
+        add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
+      }
     }
     // Check for additional chain rules
     if (oper->_matrule->_next) {
@@ -1015,12 +1017,12 @@
   int idealIndex = 0;
   for (idealIndex = 1; idealIndex < _last_machine_leaf; ++idealIndex) {
     const char *idealName = NodeClassNames[idealIndex];
-    _idealIndex.Insert((void*)idealName, (void*)idealIndex);
+    _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
   }
   for ( idealIndex = _last_machine_leaf+1;
         idealIndex < _last_opcode; ++idealIndex) {
     const char *idealName = NodeClassNames[idealIndex];
-    _idealIndex.Insert((void*)idealName, (void*)idealIndex);
+    _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
   }
 
 }
--- a/hotspot/src/share/vm/adlc/dfa.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/dfa.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -870,7 +870,7 @@
 }
 
 // Print out the dictionary contents as key-value pairs
-static void dumpekey(const void* key)  { fprintf(stdout, "%s", key); }
+static void dumpekey(const void* key)  { fprintf(stdout, "%s", (char*) key); }
 static void dumpexpr(const void* expr) { fflush(stdout); ((Expr*)expr)->print(); }
 
 void ExprDict::dump() {
@@ -1020,7 +1020,7 @@
 }
 
 // Print out the dictionary contents as key-value pairs
-static void print_key (const void* key)              { fprintf(stdout, "%s", key); }
+static void print_key (const void* key)              { fprintf(stdout, "%s", (char*) key); }
 static void print_production(const void* production) { fflush(stdout); ((Production*)production)->print(); }
 
 void ProductionState::print() {
--- a/hotspot/src/share/vm/adlc/dict2.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/dict2.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2002 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -275,7 +275,7 @@
 // Convert string to hash key.  This algorithm implements a universal hash
 // function with the multipliers frozen (ok, so it's not universal).  The
 // multipliers (and allowable characters) are all odd, so the resultant sum
-// is odd - guarenteed not divisible by any power of two, so the hash tables
+// is odd - guaranteed not divisible by any power of two, so the hash tables
 // can be any power of two with good results.  Also, I choose multipliers
 // that have only 2 bits set (the low is always set to be odd) so
 // multiplication requires only shifts and adds.  Characters are required to
@@ -296,7 +296,7 @@
 }
 
 //------------------------------hashptr--------------------------------------
-// Slimey cheap hash function; no guarenteed performance.  Better than the
+// Slimey cheap hash function; no guaranteed performance.  Better than the
 // default for pointers, especially on MS-DOS machines.
 int hashptr(const void *key) {
 #ifdef __TURBOC__
@@ -306,7 +306,7 @@
 #endif
 }
 
-// Slimey cheap hash function; no guarenteed performance.
+// Slimey cheap hash function; no guaranteed performance.
 int hashkey(const void *key) {
   return (int)((intptr_t)key);
 }
--- a/hotspot/src/share/vm/adlc/dict2.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/dict2.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -89,10 +89,10 @@
 
 // Hashing functions
 int hashstr(const void *s);        // Nice string hash
-// Slimey cheap hash function; no guarenteed performance.  Better than the
+// Slimey cheap hash function; no guaranteed performance.  Better than the
 // default for pointers, especially on MS-DOS machines.
 int hashptr(const void *key);
-// Slimey cheap hash function; no guarenteed performance.
+// Slimey cheap hash function; no guaranteed performance.
 int hashkey(const void *key);
 
 // Key comparators
--- a/hotspot/src/share/vm/adlc/filebuff.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/filebuff.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
 // FILEBUFF.CPP - Routines for handling a parser file buffer
 #include "adlc.hpp"
 
+using namespace std;
+
 //------------------------------FileBuff---------------------------------------
 // Create a new parsing buffer
 FileBuff::FileBuff( BufferedFile *fptr, ArchDesc& archDesc) : _fp(fptr), _AD(archDesc) {
@@ -48,10 +50,10 @@
     file_error(SEMERR, 0, "Buffer allocation failed\n");
     exit(1);                    // Exit on allocation failure
   }
-  *_bigbuf = '\n';               // Lead with a sentinal newline
-  _buf = _bigbuf+1;                     // Skip sentinal
+  *_bigbuf = '\n';               // Lead with a sentinel newline
+  _buf = _bigbuf+1;                     // Skip sentinel
   _bufmax = _buf;               // Buffer is empty
-  _bufeol = _bigbuf;              // _bufeol points at sentinal
+  _bufeol = _bigbuf;              // _bufeol points at sentinel
   _filepos = -1;                 // filepos is in sync with _bufeol
   _bufoff = _offset = 0L;       // Offset at file start
 
@@ -60,8 +62,8 @@
     file_error(SEMERR, 0, "File read error, no input read\n");
     exit(1);                     // Exit on read error
   }
-  *_bufmax = '\n';               // End with a sentinal new-line
-  *(_bufmax+1) = '\0';           // Then end with a sentinal NULL
+  *_bufmax = '\n';               // End with a sentinel new-line
+  *(_bufmax+1) = '\0';           // Then end with a sentinel NULL
 }
 
 //------------------------------~FileBuff--------------------------------------
@@ -79,7 +81,7 @@
 
   _linenum++;
   retval = ++_bufeol;      // return character following end of previous line
-  if (*retval == '\0') return NULL; // Check for EOF sentinal
+  if (*retval == '\0') return NULL; // Check for EOF sentinel
   // Search for newline character which must end each line
   for(_filepos++; *_bufeol != '\n'; _bufeol++)
     _filepos++;                    // keep filepos in sync with _bufeol
@@ -217,7 +219,7 @@
     off = expandtab(os,off,*s++,'-','-');
   if( i == len ) os << '^';     // Mark end of region
   os << '\n';                   // End of marked line
-  return 0L;                    // All done
+  return 0;                     // All done
 }
 
 //------------------------------print------------------------------------------
--- a/hotspot/src/share/vm/adlc/filebuff.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/filebuff.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 #include <iostream>
 
 using namespace std;
+
 // STRUCTURE FOR HANDLING INPUT AND OUTPUT FILES
 typedef struct {
   const char *_name;
@@ -36,7 +37,7 @@
 
 //------------------------------FileBuff--------------------------------------
 // This class defines a nicely behaved buffer of text.  Entire file of text
-// is read into buffer at creation, with sentinals at start and end.
+// is read into buffer at creation, with sentinels at start and end.
 class FileBuff {
   friend class FileBuffRegion;
  private:
@@ -45,8 +46,8 @@
   long  _bufoff;                // Start of buffer file offset
 
   char *_buf;                   // The buffer itself.
-  char *_bigbuf;                // The buffer plus sentinals; actual heap area
-  char *_bufmax;                // A pointer to the buffer end sentinal
+  char *_bigbuf;                // The buffer plus sentinels; actual heap area
+  char *_bufmax;                // A pointer to the buffer end sentinel
   char *_bufeol;                // A pointer to the last complete line end
 
   int   _err;                   // Error flag for file seek/read operations
@@ -72,7 +73,7 @@
 
   // This converts a pointer into the buffer to a file offset.  It only works
   // when the pointer is valid (i.e. just obtained from getline()).
-  int getoff(const char *s) { return _bufoff+(int)(s-_buf); }
+  long getoff(const char* s) { return _bufoff + (s - _buf); }
 };
 
 //------------------------------FileBuffRegion---------------------------------
@@ -95,8 +96,6 @@
   FileBuffRegion *copy();                   // Deep copy
   FileBuffRegion *merge(FileBuffRegion*); // Merge 2 regions; delete input
 
-//  void print(std::ostream&);
-//  friend std::ostream& operator<< (std::ostream&, FileBuffRegion&);
   void print(ostream&);
   friend ostream& operator<< (ostream&, FileBuffRegion&);
 };
--- a/hotspot/src/share/vm/adlc/forms.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/forms.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,6 +70,7 @@
   else return (_iter <_cur-1 ? _names[++_iter] : NULL);
 }
 const char  *NameList::current() { return (_iter < _cur ? _names[_iter] : NULL); }
+const char  *NameList::peek(int skip) { return (_iter + skip < _cur ? _names[_iter + skip] : NULL); }
 
 // Return 'true' if current entry is signal
 bool  NameList::current_is_signal() {
@@ -248,11 +249,13 @@
 // True if 'opType', an ideal name, loads or stores.
 Form::DataType Form::is_load_from_memory(const char *opType) const {
   if( strcmp(opType,"LoadB")==0 )  return Form::idealB;
+  if( strcmp(opType,"LoadUB")==0 )  return Form::idealB;
   if( strcmp(opType,"LoadUS")==0 )  return Form::idealC;
   if( strcmp(opType,"LoadD")==0 )  return Form::idealD;
   if( strcmp(opType,"LoadD_unaligned")==0 )  return Form::idealD;
   if( strcmp(opType,"LoadF")==0 )  return Form::idealF;
   if( strcmp(opType,"LoadI")==0 )  return Form::idealI;
+  if( strcmp(opType,"LoadUI2L")==0 )  return Form::idealI;
   if( strcmp(opType,"LoadKlass")==0 )  return Form::idealP;
   if( strcmp(opType,"LoadNKlass")==0 ) return Form::idealN;
   if( strcmp(opType,"LoadL")==0 )  return Form::idealL;
@@ -370,7 +373,7 @@
 }
 
 // Print out the dictionary contents as key-value pairs
-static void dumpkey (const void* key)  { fprintf(stdout, "%s", key); }
+static void dumpkey (const void* key)  { fprintf(stdout, "%s", (char*) key); }
 static void dumpform(const void* form) { fflush(stdout); ((Form*)form)->dump(); }
 
 void FormDict::dump() {
--- a/hotspot/src/share/vm/adlc/forms.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/forms.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -124,7 +124,7 @@
 public:
   // Public Data
   Form *_next;                     // Next pointer for form lists
-  long  _linenum;                  // Line number for debugging
+  int   _linenum;                  // Line number for debugging
 
   // Dynamic type check for common forms.
   virtual OpClassForm   *is_opclass()     const;
@@ -342,6 +342,7 @@
   void  reset();                   // Reset iteration
   const char *iter();              // after reset(), first element : else next
   const char *current();           // return current element in iteration.
+  const char *peek(int skip = 1);  // returns element + skip in iteration if there is one
 
   bool  current_is_signal();       // Return 'true' if current entry is signal
   bool  is_signal(const char *entry); // Return true if entry is a signal
--- a/hotspot/src/share/vm/adlc/formsopt.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/formsopt.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -273,13 +273,13 @@
   for(_regDefs.reset(); (name = _regDefs.iter()) != NULL;) {
     int rnum = ((RegDef*)_regDef[name])->register_num();
     if( (rnum >> 5) == wordnum )
-      word |= (1L<<(rnum&31));
+      word |= (1 << (rnum & 31));
   }
   if( stack_also ) {
     // Now also collect stack bits
     for( int i = 0; i < 32; i++ )
       if( wordnum*32+i >= RegisterForm::_reg_ctr )
-        word |= (1L<<i);
+        word |= (1 << i);
   }
 
   return word;
@@ -592,10 +592,10 @@
                                  int input) {
   if( position > _max_position ) _max_position = position;
 
-  _parent.addName((char *)parent);
-  _position.addName((char *)position);
+  _parent.addName((char*) (intptr_t) parent);
+  _position.addName((char*) (intptr_t) position);
   _instrs.addName(name);
-  _input.addName((char *)input);
+  _input.addName((char*) (intptr_t) input);
 }
 
 // Access info about instructions in the peep-match rule
@@ -603,7 +603,7 @@
   return _max_position;
 }
 
-const char *PeepMatch::instruction_name(intptr_t position) {
+const char *PeepMatch::instruction_name(int position) {
   return _instrs.name(position);
 }
 
@@ -615,11 +615,11 @@
   _input.reset();
 }
 
-void  PeepMatch::next_instruction( intptr_t &parent, intptr_t &position, const char * &name, intptr_t &input ){
-  parent   = (intptr_t)_parent.iter();
-  position = (intptr_t)_position.iter();
+void  PeepMatch::next_instruction(int &parent, int &position, const char* &name, int &input) {
+  parent   = (int) (intptr_t) _parent.iter();
+  position = (int) (intptr_t) _position.iter();
   name     = _instrs.iter();
-  input    = (intptr_t)_input.iter();
+  input    = (int) (intptr_t) _input.iter();
 }
 
 // 'true' if current position in iteration is a placeholder, not matched.
@@ -637,15 +637,15 @@
 }
 
 //------------------------------PeepConstraint---------------------------------
-PeepConstraint::PeepConstraint(intptr_t  left_inst,  char *left_op, char *relation,
-                               intptr_t  right_inst, char *right_op)
+PeepConstraint::PeepConstraint(int left_inst,  char* left_op, char* relation,
+                               int right_inst, char* right_op)
   : _left_inst(left_inst), _left_op(left_op), _relation(relation),
     _right_inst(right_inst), _right_op(right_op), _next(NULL) {}
 PeepConstraint::~PeepConstraint() {
 }
 
 // Check if constraints use instruction at position
-bool PeepConstraint::constrains_instruction(intptr_t position) {
+bool PeepConstraint::constrains_instruction(int position) {
   // Check local instruction constraints
   if( _left_inst  == position ) return true;
   if( _right_inst == position ) return true;
@@ -692,7 +692,7 @@
 }
 void  PeepReplace::add_operand( int inst_num, char *inst_operand ) {
   _instruction.add_signal();
-  _operand_inst_num.addName((char*)inst_num);
+  _operand_inst_num.addName((char*) (intptr_t) inst_num);
   _operand_op_name.addName(inst_operand);
 }
 
@@ -702,15 +702,15 @@
   _operand_inst_num.reset();
   _operand_op_name.reset();
 }
-void  PeepReplace::next_instruction(const char * &inst){
+void  PeepReplace::next_instruction(const char* &inst){
   inst                     = _instruction.iter();
-  intptr_t   inst_num      = (intptr_t)_operand_inst_num.iter();
-  const char *inst_operand = _operand_op_name.iter();
+  int         inst_num     = (int) (intptr_t) _operand_inst_num.iter();
+  const char* inst_operand = _operand_op_name.iter();
 }
-void  PeepReplace::next_operand( intptr_t &inst_num, const char * &inst_operand ) {
-  const char *inst   = _instruction.iter();
-  inst_num           = (intptr_t)_operand_inst_num.iter();
-  inst_operand       = _operand_op_name.iter();
+void  PeepReplace::next_operand(int &inst_num, const char* &inst_operand) {
+  const char* inst = _instruction.iter();
+  inst_num         = (int) (intptr_t) _operand_inst_num.iter();
+  inst_operand     = _operand_op_name.iter();
 }
 
 
--- a/hotspot/src/share/vm/adlc/formsopt.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/formsopt.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -457,10 +457,10 @@
 
   // Access info about instructions in the peep-match rule
   int   max_position();
-  const char *instruction_name(intptr_t position);
+  const char *instruction_name(int position);
   // Iterate through all info on matched instructions
   void  reset();
-  void  next_instruction( intptr_t &parent, intptr_t &position, const char * &name, intptr_t &input );
+  void  next_instruction(int &parent, int &position, const char* &name, int &input);
   // 'true' if current position in iteration is a placeholder, not matched.
   bool  is_placeholder();
 
@@ -474,20 +474,20 @@
   PeepConstraint *_next;           // Additional constraints ANDed together
 
 public:
-  const intptr_t  _left_inst;
-  const char      *_left_op;
-  const char      *_relation;
-  const intptr_t  _right_inst;
-  const char      *_right_op;
+  const int   _left_inst;
+  const char* _left_op;
+  const char* _relation;
+  const int   _right_inst;
+  const char* _right_op;
 
 public:
   // Public Methods
-  PeepConstraint(intptr_t  left_inst,  char *left_op, char *relation,
-                 intptr_t  right_inst, char *right_op);
+  PeepConstraint(int left_inst,  char* left_op, char* relation,
+                 int right_inst, char* right_op);
   ~PeepConstraint();
 
   // Check if constraints use instruction at position
-  bool constrains_instruction(intptr_t position);
+  bool constrains_instruction(int position);
 
   // Add another constraint
   void append(PeepConstraint *next_peep_constraint);
@@ -519,7 +519,7 @@
   // Access contents of peepreplace
   void  reset();
   void  next_instruction(const char * &root);
-  void  next_operand( intptr_t &inst_num, const char * &inst_operand );
+  void  next_operand(int &inst_num, const char * &inst_operand );
 
   // Utilities
   void dump();
--- a/hotspot/src/share/vm/adlc/formssel.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/formssel.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -574,9 +574,13 @@
   // TEMPORARY
   // if( is_simple_chain_rule(globals) )  return false;
 
-  // String-compare uses many memorys edges, but writes none
+  // String.(compareTo/equals/indexOf) and Arrays.equals use many memorys edges,
+  // but writes none
   if( _matrule && _matrule->_rChild &&
-      strcmp(_matrule->_rChild->_opType,"StrComp")==0 )
+      ( strcmp(_matrule->_rChild->_opType,"StrComp"    )==0 ||
+        strcmp(_matrule->_rChild->_opType,"StrEquals"  )==0 ||
+        strcmp(_matrule->_rChild->_opType,"StrIndexOf" )==0 ||
+        strcmp(_matrule->_rChild->_opType,"AryEq"      )==0 ))
     return true;
 
   // Check if instruction has a USE of a memory operand class, but no defs
@@ -815,8 +819,10 @@
     return AdlcVMDeps::Parms;   // Skip the machine-state edges
 
   if( _matrule->_rChild &&
-          strcmp(_matrule->_rChild->_opType,"StrComp")==0 ) {
-        // String compare takes 1 control and 4 memory edges.
+      ( strcmp(_matrule->_rChild->_opType,"StrComp"   )==0 ||
+        strcmp(_matrule->_rChild->_opType,"StrEquals" )==0 ||
+        strcmp(_matrule->_rChild->_opType,"StrIndexOf")==0 )) {
+        // String.(compareTo/equals/indexOf) take 1 control and 4 memory edges.
     return 5;
   }
 
@@ -844,8 +850,12 @@
   for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
     OperandForm *opForm = (OperandForm*)_localNames[name];
 
-    const Form *form = _effects[name];
-    Effect     *e    = form ? form->is_effect() : NULL;
+    Effect* e = NULL;
+    {
+      const Form* form = _effects[name];
+      e = form ? form->is_effect() : NULL;
+    }
+
     if (e != NULL) {
       has_temp |= e->is(Component::TEMP);
 
@@ -858,19 +868,7 @@
         OperandForm* kill = (OperandForm*)_localNames[kill_name];
         globalAD->syntax_err(_linenum, "%s: %s %s must be at the end of the argument list\n",
                              _ident, kill->_ident, kill_name);
-      } else if (e->isa(Component::KILL)) {
-        kill_name = name;
-      }
-
-      // TEMPs are real uses and need to be among the first parameters
-      // listed, otherwise the numbering of operands and inputs gets
-      // screwy, so enforce this restriction during parse.
-      if (kill_name != NULL &&
-          e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
-        OperandForm* kill = (OperandForm*)_localNames[kill_name];
-        globalAD->syntax_err(_linenum, "%s: %s %s must follow %s %s in the argument list\n",
-                             _ident, kill->_ident, kill_name, opForm->_ident, name);
-      } else if (e->isa(Component::KILL)) {
+      } else if (e->isa(Component::KILL) && !e->isa(Component::USE)) {
         kill_name = name;
       }
     }
@@ -1122,7 +1120,7 @@
   const char *op_name            = NULL;
   const char *reg_type           = NULL;
   FormDict   &globals            = AD.globalNames();
-  cisc_spill_operand = _matrule->cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
+  cisc_spill_operand = _matrule->matchrule_cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
   if( (cisc_spill_operand != Not_cisc_spillable) && (op_name != NULL) && equivalent_predicates(this, instr) ) {
     cisc_spill_operand = operand_position(op_name, Component::USE);
     int def_oper  = operand_position(op_name, Component::DEF);
@@ -1217,13 +1215,17 @@
 // Seach through operands to determine parameters unique positions.
 void InstructForm::set_unique_opnds() {
   uint* uniq_idx = NULL;
-  uint  nopnds = num_opnds();
+  int  nopnds = num_opnds();
   uint  num_uniq = nopnds;
-  uint i;
+  int i;
+  _uniq_idx_length = 0;
   if ( nopnds > 0 ) {
-    // Allocate index array with reserve.
-    uniq_idx = (uint*) malloc(sizeof(uint)*(nopnds + 2));
-    for( i = 0; i < nopnds+2; i++ ) {
+    // Allocate index array.  Worst case we're mapping from each
+    // component back to an index and any DEF always goes at 0 so the
+    // length of the array has to be the number of components + 1.
+    _uniq_idx_length = _components.count() + 1;
+    uniq_idx = (uint*) malloc(sizeof(uint)*(_uniq_idx_length));
+    for( i = 0; i < _uniq_idx_length; i++ ) {
       uniq_idx[i] = i;
     }
   }
@@ -1238,8 +1240,8 @@
     _parameters.reset();
     while( (name = _parameters.iter()) != NULL ) {
       count = 0;
-      uint position = 0;
-      uint uniq_position = 0;
+      int position = 0;
+      int uniq_position = 0;
       _components.reset();
       Component *comp = NULL;
       if( sets_result() ) {
@@ -1255,6 +1257,7 @@
         }
         if( strcmp(name, comp->_name)==0 ) {
           if( ++count > 1 ) {
+            assert(position < _uniq_idx_length, "out of bounds");
             uniq_idx[position] = uniq_position;
             has_dupl_use = true;
           } else {
@@ -1284,7 +1287,7 @@
   _num_uniq = num_uniq;
 }
 
-// Generate index values needed for determing the operand position
+// Generate index values needed for determining the operand position
 void InstructForm::index_temps(FILE *fp, FormDict &globals, const char *prefix, const char *receiver) {
   uint  idx = 0;                  // position of operand in match rule
   int   cur_num_opnds = num_opnds();
@@ -2200,8 +2203,8 @@
 // Return zero-based position in component list, only counting constants;
 // Return -1 if not in list.
 int OperandForm::constant_position(FormDict &globals, const Component *last) {
-  // Iterate through components and count constants preceeding 'constant'
-  uint  position = 0;
+  // Iterate through components and count constants preceding 'constant'
+  int position = 0;
   Component *comp;
   _components.reset();
   while( (comp = _components.iter()) != NULL  && (comp != last) ) {
@@ -2238,7 +2241,7 @@
 // Return zero-based position in component list, only counting constants;
 // Return -1 if not in list.
 int OperandForm::register_position(FormDict &globals, const char *reg_name) {
-  // Iterate through components and count registers preceeding 'last'
+  // Iterate through components and count registers preceding 'last'
   uint  position = 0;
   Component *comp;
   _components.reset();
@@ -2304,7 +2307,7 @@
   if ( op->is_base_constant(globals) == Form::idealP ) {
     // Find the constant's index:  _c0, _c1, _c2, ... , _cN
     uint idx  = op->constant_position( globals, rep_var);
-    fprintf(fp,"  virtual bool disp_is_oop() const {", _ident);
+    fprintf(fp,"  virtual bool disp_is_oop() const {");
     fprintf(fp,  "  return _c%d->isa_oop_ptr();", idx);
     fprintf(fp, " }\n");
   }
@@ -3042,9 +3045,9 @@
 
 // Recursive call collecting info on top-level operands, not transitive.
 // Implementation does not modify state of internal structures.
-void MatchNode::append_components(FormDict &locals, ComponentList &components,
-                                  bool deflag) const {
-  int   usedef = deflag ? Component::DEF : Component::USE;
+void MatchNode::append_components(FormDict& locals, ComponentList& components,
+                                  bool def_flag) const {
+  int usedef = def_flag ? Component::DEF : Component::USE;
   FormDict &globals = _AD.globalNames();
 
   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
@@ -3062,10 +3065,10 @@
     return;
   }
   // Promote results of "Set" to DEF
-  bool def_flag = (!strcmp(_opType, "Set")) ? true : false;
-  if (_lChild) _lChild->append_components(locals, components, def_flag);
-  def_flag = false;   // only applies to component immediately following 'Set'
-  if (_rChild) _rChild->append_components(locals, components, def_flag);
+  bool tmpdef_flag = (!strcmp(_opType, "Set")) ? true : false;
+  if (_lChild) _lChild->append_components(locals, components, tmpdef_flag);
+  tmpdef_flag = false;   // only applies to component immediately following 'Set'
+  if (_rChild) _rChild->append_components(locals, components, tmpdef_flag);
 }
 
 // Find the n'th base-operand in the match node,
@@ -3313,8 +3316,8 @@
   static const char *needs_ideal_memory_list[] = {
     "StoreI","StoreL","StoreP","StoreN","StoreD","StoreF" ,
     "StoreB","StoreC","Store" ,"StoreFP",
-    "LoadI" ,"LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
-    "LoadB" ,"LoadUS" ,"LoadS" ,"Load"   ,
+    "LoadI", "LoadUI2L", "LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
+    "LoadB" , "LoadUB", "LoadUS" ,"LoadS" ,"Load"   ,
     "Store4I","Store2I","Store2L","Store2D","Store4F","Store2F","Store16B",
     "Store8B","Store4B","Store8C","Store4C","Store2C",
     "Load4I" ,"Load2I" ,"Load2L" ,"Load2D" ,"Load4F" ,"Load2F" ,"Load16B" ,
@@ -3411,9 +3414,9 @@
   return (form1 == form2);
 }
 
-//-------------------------cisc_spill_match------------------------------------
+//-------------------------cisc_spill_match_node-------------------------------
 // Recursively check two MatchRules for legal conversion via cisc-spilling
-int  MatchNode::cisc_spill_match(FormDict &globals, RegisterForm *registers, MatchNode *mRule2, const char * &operand, const char * &reg_type) {
+int MatchNode::cisc_spill_match(FormDict& globals, RegisterForm* registers, MatchNode* mRule2, const char* &operand, const char* &reg_type) {
   int cisc_spillable  = Maybe_cisc_spillable;
   int left_spillable  = Maybe_cisc_spillable;
   int right_spillable = Maybe_cisc_spillable;
@@ -3434,10 +3437,16 @@
     const InstructForm *form2_inst = form2 ? form2->is_instruction() : NULL;
     const char *name_left  = mRule2->_lChild ? mRule2->_lChild->_opType : NULL;
     const char *name_right = mRule2->_rChild ? mRule2->_rChild->_opType : NULL;
+    DataType data_type = Form::none;
+    if (form->is_operand()) {
+      // Make sure the loadX matches the type of the reg
+      data_type = form->ideal_to_Reg_type(form->is_operand()->ideal_type(globals));
+    }
     // Detect reg vs (loadX memory)
     if( form->is_cisc_reg(globals)
         && form2_inst
-        && (is_load_from_memory(mRule2->_opType) != Form::none) // reg vs. (load memory)
+        && data_type != Form::none
+        && (is_load_from_memory(mRule2->_opType) == data_type) // reg vs. (load memory)
         && (name_left != NULL)       // NOT (load)
         && (name_right == NULL) ) {  // NOT (load memory foo)
       const Form *form2_left = name_left ? globals[name_left] : NULL;
@@ -3487,13 +3496,13 @@
   return cisc_spillable;
 }
 
-//---------------------------cisc_spill_match----------------------------------
+//---------------------------cisc_spill_match_rule------------------------------
 // Recursively check two MatchRules for legal conversion via cisc-spilling
 // This method handles the root of Match tree,
 // general recursive checks done in MatchNode
-int  MatchRule::cisc_spill_match(FormDict &globals, RegisterForm *registers,
-                                 MatchRule *mRule2, const char * &operand,
-                                 const char * &reg_type) {
+int  MatchRule::matchrule_cisc_spill_match(FormDict& globals, RegisterForm* registers,
+                                           MatchRule* mRule2, const char* &operand,
+                                           const char* &reg_type) {
   int cisc_spillable  = Maybe_cisc_spillable;
   int left_spillable  = Maybe_cisc_spillable;
   int right_spillable = Maybe_cisc_spillable;
@@ -3531,7 +3540,7 @@
 //----------------------------- equivalent ------------------------------------
 // Recursively check to see if two match rules are equivalent.
 // This rule handles the root.
-bool MatchRule::equivalent(FormDict &globals, MatchRule *mRule2) {
+bool MatchRule::equivalent(FormDict &globals, MatchNode *mRule2) {
   // Check that each sets a result
   if (sets_result() != mRule2->sets_result()) {
     return false;
@@ -3647,7 +3656,7 @@
 
 //-------------------------- swap_commutative_op ------------------------------
 // Recursively swap specified commutative operation with subtree operands.
-void MatchRule::swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt) {
+void MatchRule::matchrule_swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt) {
   assert(match_rules_cnt < 100," too many match rule clones");
   // Clone
   MatchRule* clone = new MatchRule(_AD, this);
@@ -3660,8 +3669,8 @@
   clone->_next = this->_next;
   this-> _next = clone;
   if( (--count) > 0 ) {
-    this-> swap_commutative_op(instr_ident, count, match_rules_cnt);
-    clone->swap_commutative_op(instr_ident, count, match_rules_cnt);
+    this-> matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
+    clone->matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
   }
 }
 
@@ -3693,7 +3702,7 @@
 
 // Recursive call collecting info on top-level operands, not transitive.
 // Implementation does not modify state of internal structures.
-void MatchRule::append_components(FormDict &locals, ComponentList &components) const {
+void MatchRule::append_components(FormDict& locals, ComponentList& components, bool def_flag) const {
   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
 
   MatchNode::append_components(locals, components,
--- a/hotspot/src/share/vm/adlc/formssel.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/formssel.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -101,6 +101,7 @@
   const char    *_ins_pipe;        // Instruction Scheduline description class
 
   uint          *_uniq_idx;        // Indexes of unique operands
+  int            _uniq_idx_length; // Length of _uniq_idx array
   uint           _num_uniq;        // Number  of unique operands
   ComponentList  _components;      // List of Components matches MachNode's
                                    // operand structure
@@ -257,11 +258,13 @@
   void                set_unique_opnds();
   uint                num_unique_opnds() { return _num_uniq; }
   uint                unique_opnds_idx(int idx) {
-                        if( _uniq_idx != NULL && idx > 0 )
+                        if( _uniq_idx != NULL && idx > 0 ) {
+                          assert(idx < _uniq_idx_length, "out of bounds");
                           return _uniq_idx[idx];
-                        else
+                        } else {
                           return idx;
-                      }
+                        }
+  }
 
   // Operands which are only KILLs aren't part of the input array and
   // require special handling in some cases.  Their position in this
@@ -274,7 +277,7 @@
   //
   // Generate the format call for the replacement variable
   void                rep_var_format(FILE *fp, const char *rep_var);
-  // Generate index values needed for determing the operand position
+  // Generate index values needed for determining the operand position
   void                index_temps   (FILE *fp, FormDict &globals, const char *prefix = "", const char *receiver = "");
   // ---------------------------
 
@@ -341,7 +344,7 @@
 
   // --------------------------- Code Block
   // Add code
-  void add_code(const char *string_preceeding_replacement_var);
+  void add_code(const char *string_preceding_replacement_var);
   // Add a replacement variable or one of its subfields
   // Subfields are stored with a leading '$'
   void add_rep_var(char *replacement_var);
@@ -917,8 +920,8 @@
   // return 1 if found and position is incremented by operand offset in rule
   bool       find_name(const char *str, int &position) const;
   bool       find_type(const char *str, int &position) const;
-  void       append_components(FormDict &locals, ComponentList &components,
-                               bool def_flag) const;
+  virtual void append_components(FormDict& locals, ComponentList& components,
+                                 bool def_flag = false) const;
   bool       base_operand(uint &position, FormDict &globals,
                          const char * &result, const char * &name,
                          const char * &opType) const;
@@ -944,12 +947,12 @@
   const char *reduce_left (FormDict &globals)  const;
 
   // Recursive version of check in MatchRule
-  int        cisc_spill_match(FormDict &globals, RegisterForm *registers,
-                              MatchNode *mRule2, const char * &operand,
-                              const char * &reg_type);
+  int        cisc_spill_match(FormDict& globals, RegisterForm* registers,
+                              MatchNode* mRule2, const char* &operand,
+                              const char* &reg_type);
   int        cisc_spill_merge(int left_result, int right_result);
 
-  bool       equivalent(FormDict &globals, MatchNode *mNode2);
+  virtual bool equivalent(FormDict& globals, MatchNode* mNode2);
 
   void       count_commutative_op(int& count);
   void       swap_commutative_op(bool atroot, int count);
@@ -976,7 +979,7 @@
   MatchRule(ArchDesc &ad, MatchNode* mroot, int depth, char* construct, int numleaves);
   ~MatchRule();
 
-  void       append_components(FormDict &locals, ComponentList &components) const;
+  virtual void append_components(FormDict& locals, ComponentList& components, bool def_flag = false) const;
   // Recursive call on all operands' match rules in my match rule.
   bool       base_operand(uint &position, FormDict &globals,
                          const char * &result, const char * &name,
@@ -1003,14 +1006,14 @@
   Form::DataType is_ideal_store() const;// node matches ideal 'StoreXNode'
 
   // Check if 'mRule2' is a cisc-spill variant of this MatchRule
-  int        cisc_spill_match(FormDict &globals, RegisterForm *registers,
-                              MatchRule *mRule2, const char * &operand,
-                              const char * &reg_type);
+  int        matchrule_cisc_spill_match(FormDict &globals, RegisterForm* registers,
+                                        MatchRule* mRule2, const char* &operand,
+                                        const char* &reg_type);
 
   // Check if 'mRule2' is equivalent to this MatchRule
-  bool       equivalent(FormDict &globals, MatchRule *mRule2);
+  virtual bool equivalent(FormDict& globals, MatchNode* mRule2);
 
-  void       swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt);
+  void       matchrule_swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt);
 
   void dump();
   void output(FILE *fp);
--- a/hotspot/src/share/vm/adlc/main.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/main.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -349,7 +349,7 @@
     }
     else {
       if (_ADL_file._name) printf("%s --> ", _ADL_file._name);
-      printf("%s, %s, %s, %s, %s, %s, %s, %s, %s",
+      printf("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
              _CPP_file._name,
              _CPP_CLONE_file._name,
              _CPP_EXPAND_file._name,
@@ -358,7 +358,8 @@
              _CPP_MISC_file._name,
              _CPP_PEEPHOLE_file._name,
              _CPP_PIPELINE_file._name,
-             _HPP_file._name, _DFA_file._name);
+             _HPP_file._name,
+             _DFA_file._name);
     }
     printf("\n");
   }
@@ -431,7 +432,7 @@
     legal_end = fbuf.get_line();
   }
   *legal_text = legal_start;
-  return (legal_end - legal_start);
+  return (int) (legal_end - legal_start);
 }
 
 // VS2005 has its own definition, identical to this one.
--- a/hotspot/src/share/vm/adlc/output_c.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/output_c.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -225,11 +225,11 @@
     pipeclass->_parameters.reset();
 
   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
-    const PipeClassOperandForm *pipeopnd =
+    const PipeClassOperandForm *tmppipeopnd =
         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 
-    if (pipeopnd)
-      templen += 10 + (int)strlen(pipeopnd->_stage);
+    if (tmppipeopnd)
+      templen += 10 + (int)strlen(tmppipeopnd->_stage);
     else
       templen += 19;
 
@@ -253,10 +253,10 @@
     pipeclass->_parameters.reset();
 
   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
-    const PipeClassOperandForm *pipeopnd =
+    const PipeClassOperandForm *tmppipeopnd =
         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
     templen += sprintf(&operand_stages[templen], "  stage_%s%c\n",
-      pipeopnd ? pipeopnd->_stage : "undefined",
+      tmppipeopnd ? tmppipeopnd->_stage : "undefined",
       (++i < paramcount ? ',' : ' ') );
   }
 
@@ -1042,10 +1042,10 @@
 
 // Scan the peepmatch and output a test for each instruction
 static void check_peepmatch_instruction_tree(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
-  intptr_t   parent        = -1;
-  intptr_t   inst_position = 0;
-  const char *inst_name    = NULL;
-  intptr_t   input         = 0;
+  int         parent        = -1;
+  int         inst_position = 0;
+  const char* inst_name     = NULL;
+  int         input         = 0;
   fprintf(fp, "      // Check instruction sub-tree\n");
   pmatch->reset();
   for( pmatch->next_instruction( parent, inst_position, inst_name, input );
@@ -1055,14 +1055,14 @@
     if( ! pmatch->is_placeholder() ) {
       // Define temporaries 'inst#', based on parent and parent's input index
       if( parent != -1 ) {                // root was initialized
-        fprintf(fp, "  inst%ld = inst%ld->in(%ld);\n",
+        fprintf(fp, "  inst%d = inst%d->in(%d);\n",
                 inst_position, parent, input);
       }
 
       // When not the root
       // Test we have the correct instruction by comparing the rule
       if( parent != -1 ) {
-        fprintf(fp, "  matches = matches &&  ( inst%ld->rule() == %s_rule );",
+        fprintf(fp, "  matches = matches &&  ( inst%d->rule() == %s_rule );",
                 inst_position, inst_name);
       }
     } else {
@@ -1073,20 +1073,20 @@
   }
 }
 
-static void print_block_index(FILE *fp, intptr_t inst_position) {
+static void print_block_index(FILE *fp, int inst_position) {
   assert( inst_position >= 0, "Instruction number less than zero");
   fprintf(fp, "block_index");
   if( inst_position != 0 ) {
-    fprintf(fp, " - %ld", inst_position);
+    fprintf(fp, " - %d", inst_position);
   }
 }
 
 // Scan the peepmatch and output a test for each instruction
 static void check_peepmatch_instruction_sequence(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
-  intptr_t   parent        = -1;
-  intptr_t   inst_position = 0;
-  const char *inst_name    = NULL;
-  intptr_t   input         = 0;
+  int         parent        = -1;
+  int         inst_position = 0;
+  const char* inst_name     = NULL;
+  int         input         = 0;
   fprintf(fp, "  // Check instruction sub-tree\n");
   pmatch->reset();
   for( pmatch->next_instruction( parent, inst_position, inst_name, input );
@@ -1101,14 +1101,14 @@
         print_block_index(fp, inst_position);
         fprintf(fp, " > 0 ) {\n    Node *n = block->_nodes.at(");
         print_block_index(fp, inst_position);
-        fprintf(fp, ");\n    inst%ld = (n->is_Mach()) ? ", inst_position);
+        fprintf(fp, ");\n    inst%d = (n->is_Mach()) ? ", inst_position);
         fprintf(fp, "n->as_Mach() : NULL;\n  }\n");
       }
 
       // When not the root
       // Test we have the correct instruction by comparing the rule.
       if( parent != -1 ) {
-        fprintf(fp, "  matches = matches && (inst%ld != NULL) && (inst%ld->rule() == %s_rule);\n",
+        fprintf(fp, "  matches = matches && (inst%d != NULL) && (inst%d->rule() == %s_rule);\n",
                 inst_position, inst_position, inst_name);
       }
     } else {
@@ -1121,10 +1121,10 @@
 
 // Build mapping for register indices, num_edges to input
 static void build_instruction_index_mapping( FILE *fp, FormDict &globals, PeepMatch *pmatch ) {
-  intptr_t   parent        = -1;
-  intptr_t   inst_position = 0;
-  const char *inst_name    = NULL;
-  intptr_t   input         = 0;
+  int         parent        = -1;
+  int         inst_position = 0;
+  const char* inst_name     = NULL;
+  int         input         = 0;
   fprintf(fp, "      // Build map to register info\n");
   pmatch->reset();
   for( pmatch->next_instruction( parent, inst_position, inst_name, input );
@@ -1136,9 +1136,9 @@
       InstructForm *inst = globals[inst_name]->is_instruction();
       if( inst != NULL ) {
         char inst_prefix[]  = "instXXXX_";
-        sprintf(inst_prefix, "inst%ld_",   inst_position);
+        sprintf(inst_prefix, "inst%d_",   inst_position);
         char receiver[]     = "instXXXX->";
-        sprintf(receiver,    "inst%ld->", inst_position);
+        sprintf(receiver,    "inst%d->", inst_position);
         inst->index_temps( fp, globals, inst_prefix, receiver );
       }
     }
@@ -1168,7 +1168,7 @@
       }
 
       // LEFT
-      intptr_t left_index  = pconstraint->_left_inst;
+      int left_index       = pconstraint->_left_inst;
       const char *left_op  = pconstraint->_left_op;
       // Access info on the instructions whose operands are compared
       InstructForm *inst_left = globals[pmatch->instruction_name(left_index)]->is_instruction();
@@ -1191,7 +1191,7 @@
 
       // RIGHT
       int right_op_index = -1;
-      intptr_t right_index = pconstraint->_right_inst;
+      int right_index      = pconstraint->_right_inst;
       const char *right_op = pconstraint->_right_op;
       if( right_index != -1 ) { // Match operand
         // Access info on the instructions whose operands are compared
@@ -1351,7 +1351,7 @@
     assert( root_form != NULL, "Replacement instruction was not previously defined");
     fprintf(fp, "        %sNode *root = new (C) %sNode();\n", root_inst, root_inst);
 
-    intptr_t    inst_num;
+    int         inst_num;
     const char *op_name;
     int         opnds_index = 0;            // define result operand
     // Then install the use-operands for the new sub-tree
@@ -1362,7 +1362,6 @@
       InstructForm *inst_form;
       inst_form  = globals[pmatch->instruction_name(inst_num)]->is_instruction();
       assert( inst_form, "Parser should guaranty this is an instruction");
-      int op_base     = inst_form->oper_input_base(globals);
       int inst_op_num = inst_form->operand_position(op_name, Component::USE);
       if( inst_op_num == NameList::Not_in_list )
         inst_op_num = inst_form->operand_position(op_name, Component::USE_DEF);
@@ -1379,32 +1378,32 @@
         // Add unmatched edges from root of match tree
         int op_base = root_form->oper_input_base(globals);
         for( int unmatched_edge = 1; unmatched_edge < op_base; ++unmatched_edge ) {
-          fprintf(fp, "        root->add_req(inst%ld->in(%d));        // unmatched ideal edge\n",
+          fprintf(fp, "        root->add_req(inst%d->in(%d));        // unmatched ideal edge\n",
                                           inst_num, unmatched_edge);
         }
         // If new instruction captures bottom type
         if( root_form->captures_bottom_type() ) {
           // Get bottom type from instruction whose result we are replacing
-          fprintf(fp, "        root->_bottom_type = inst%ld->bottom_type();\n", inst_num);
+          fprintf(fp, "        root->_bottom_type = inst%d->bottom_type();\n", inst_num);
         }
         // Define result register and result operand
-        fprintf(fp, "        ra_->add_reference(root, inst%ld);\n", inst_num);
-        fprintf(fp, "        ra_->set_oop (root, ra_->is_oop(inst%ld));\n", inst_num);
-        fprintf(fp, "        ra_->set_pair(root->_idx, ra_->get_reg_second(inst%ld), ra_->get_reg_first(inst%ld));\n", inst_num, inst_num);
-        fprintf(fp, "        root->_opnds[0] = inst%ld->_opnds[0]->clone(C); // result\n", inst_num);
+        fprintf(fp, "        ra_->add_reference(root, inst%d);\n", inst_num);
+        fprintf(fp, "        ra_->set_oop (root, ra_->is_oop(inst%d));\n", inst_num);
+        fprintf(fp, "        ra_->set_pair(root->_idx, ra_->get_reg_second(inst%d), ra_->get_reg_first(inst%d));\n", inst_num, inst_num);
+        fprintf(fp, "        root->_opnds[0] = inst%d->_opnds[0]->clone(C); // result\n", inst_num);
         fprintf(fp, "        // ----- Done with initial setup -----\n");
       } else {
         if( (op_form == NULL) || (op_form->is_base_constant(globals) == Form::none) ) {
           // Do not have ideal edges for constants after matching
-          fprintf(fp, "        for( unsigned x%d = inst%ld_idx%d; x%d < inst%ld_idx%d; x%d++ )\n",
+          fprintf(fp, "        for( unsigned x%d = inst%d_idx%d; x%d < inst%d_idx%d; x%d++ )\n",
                   inst_op_num, inst_num, inst_op_num,
                   inst_op_num, inst_num, inst_op_num+1, inst_op_num );
-          fprintf(fp, "          root->add_req( inst%ld->in(x%d) );\n",
+          fprintf(fp, "          root->add_req( inst%d->in(x%d) );\n",
                   inst_num, inst_op_num );
         } else {
           fprintf(fp, "        // no ideal edge for constants after matching\n");
         }
-        fprintf(fp, "        root->_opnds[%d] = inst%ld->_opnds[%d]->clone(C);\n",
+        fprintf(fp, "        root->_opnds[%d] = inst%d->_opnds[%d]->clone(C);\n",
                 opnds_index, inst_num, inst_op_num );
       }
       ++opnds_index;
@@ -1443,7 +1442,7 @@
   }
   for( int i = 0; i <= max_position; ++i ) {
     if( i == 0 ) {
-      fprintf(fp, "  MachNode *inst0 = this;\n", i);
+      fprintf(fp, "  MachNode *inst0 = this;\n");
     } else {
       fprintf(fp, "  MachNode *inst%d = NULL;\n", i);
     }
@@ -1743,7 +1742,7 @@
       }
       // delete the rest of edges
       fprintf(fp,"  for(int i = idx%d - 1; i >= (int)idx%d; i--) {\n", cur_num_opnds, new_num_opnds);
-      fprintf(fp,"    del_req(i);\n", i);
+      fprintf(fp,"    del_req(i);\n");
       fprintf(fp,"  }\n");
       fprintf(fp,"  _num_opnds = %d;\n", new_num_opnds);
     }
@@ -1817,7 +1816,7 @@
 
   fprintf(fp,"\n");
   if( node->expands() ) {
-    fprintf(fp,"  return result;\n",cnt-1);
+    fprintf(fp,"  return result;\n");
   } else {
     fprintf(fp,"  return this;\n");
   }
@@ -2140,8 +2139,59 @@
         // A subfield variable, '$$' prefix
         emit_field( rep_var );
       } else {
-        // A replacement variable, '$' prefix
-        emit_rep_var( rep_var );
+        if (_strings_to_emit.peek() != NULL &&
+            strcmp(_strings_to_emit.peek(), "$Address") == 0) {
+          fprintf(_fp, "Address::make_raw(");
+
+          emit_rep_var( rep_var );
+          fprintf(_fp,"->base(ra_,this,idx%d), ", _operand_idx);
+
+          _reg_status = LITERAL_ACCESSED;
+          emit_rep_var( rep_var );
+          fprintf(_fp,"->index(ra_,this,idx%d), ", _operand_idx);
+
+          _reg_status = LITERAL_ACCESSED;
+          emit_rep_var( rep_var );
+          fprintf(_fp,"->scale(), ");
+
+          _reg_status = LITERAL_ACCESSED;
+          emit_rep_var( rep_var );
+          Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
+          if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
+            fprintf(_fp,"->disp(ra_,this,0), ");
+          } else {
+            fprintf(_fp,"->disp(ra_,this,idx%d), ", _operand_idx);
+          }
+
+          _reg_status = LITERAL_ACCESSED;
+          emit_rep_var( rep_var );
+          fprintf(_fp,"->disp_is_oop())");
+
+          // skip trailing $Address
+          _strings_to_emit.iter();
+        } else {
+          // A replacement variable, '$' prefix
+          const char* next = _strings_to_emit.peek();
+          const char* next2 = _strings_to_emit.peek(2);
+          if (next != NULL && next2 != NULL && strcmp(next2, "$Register") == 0 &&
+              (strcmp(next, "$base") == 0 || strcmp(next, "$index") == 0)) {
+            // handle $rev_var$$base$$Register and $rev_var$$index$$Register by
+            // producing as_Register(opnd_array(#)->base(ra_,this,idx1)).
+            fprintf(_fp, "as_Register(");
+            // emit the operand reference
+            emit_rep_var( rep_var );
+            rep_var = _strings_to_emit.iter();
+            assert(strcmp(rep_var, "$base") == 0 || strcmp(rep_var, "$index") == 0, "bad pattern");
+            // handle base or index
+            emit_field(rep_var);
+            rep_var = _strings_to_emit.iter();
+            assert(strcmp(rep_var, "$Register") == 0, "bad pattern");
+            // close up the parens
+            fprintf(_fp, ")");
+          } else {
+            emit_rep_var( rep_var );
+          }
+        }
       } // end replacement and/or subfield
     }
   }
--- a/hotspot/src/share/vm/adlc/output_h.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/adlc/output_h.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -574,7 +574,7 @@
   // Generate the user-defined portion of the format
   if( inst._format ) {
     // If there are replacement variables,
-    // Generate index values needed for determing the operand position
+    // Generate index values needed for determining the operand position
     if( inst._format->_rep_vars.count() )
       inst.index_temps(fp, globals);
 
@@ -1832,7 +1832,7 @@
         break;
       case Form::idealP:
       case Form::idealN:
-        fprintf(fp,"    return  opnd_array(1)->type();\n",result);
+        fprintf(fp,"    return  opnd_array(1)->type();\n");
         break;
       case Form::idealD:
         fprintf(fp,"    return  TypeD::make(opnd_array(1)->constantD());\n");
--- a/hotspot/src/share/vm/asm/assembler.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/asm/assembler.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -31,7 +31,7 @@
 // The AbstractAssembler is generating code into a CodeBuffer. To make code generation faster,
 // the assembler keeps a copy of the code buffers boundaries & modifies them when
 // emitting bytes rather than using the code buffers accessor functions all the time.
-// The code buffer is updated via set_code_end(...) after emiting a whole instruction.
+// The code buffer is updated via set_code_end(...) after emitting a whole instruction.
 
 AbstractAssembler::AbstractAssembler(CodeBuffer* code) {
   if (code == NULL)  return;
@@ -239,6 +239,78 @@
   }
 }
 
+struct DelayedConstant {
+  typedef void (*value_fn_t)();
+  BasicType type;
+  intptr_t value;
+  value_fn_t value_fn;
+  // This limit of 20 is generous for initial uses.
+  // The limit needs to be large enough to store the field offsets
+  // into classes which do not have statically fixed layouts.
+  // (Initial use is for method handle object offsets.)
+  // Look for uses of "delayed_value" in the source code
+  // and make sure this number is generous enough to handle all of them.
+  enum { DC_LIMIT = 20 };
+  static DelayedConstant delayed_constants[DC_LIMIT];
+  static DelayedConstant* add(BasicType type, value_fn_t value_fn);
+  bool match(BasicType t, value_fn_t cfn) {
+    return type == t && value_fn == cfn;
+  }
+  static void update_all();
+};
+
+DelayedConstant DelayedConstant::delayed_constants[DC_LIMIT];
+// Default C structure initialization rules have the following effect here:
+// = { { (BasicType)0, (intptr_t)NULL }, ... };
+
+DelayedConstant* DelayedConstant::add(BasicType type,
+                                      DelayedConstant::value_fn_t cfn) {
+  for (int i = 0; i < DC_LIMIT; i++) {
+    DelayedConstant* dcon = &delayed_constants[i];
+    if (dcon->match(type, cfn))
+      return dcon;
+    if (dcon->value_fn == NULL) {
+      // (cmpxchg not because this is multi-threaded but because I'm paranoid)
+      if (Atomic::cmpxchg_ptr(CAST_FROM_FN_PTR(void*, cfn), &dcon->value_fn, NULL) == NULL) {
+        dcon->type = type;
+        return dcon;
+      }
+    }
+  }
+  // If this assert is hit (in pre-integration testing!) then re-evaluate
+  // the comment on the definition of DC_LIMIT.
+  guarantee(false, "too many delayed constants");
+  return NULL;
+}
+
+void DelayedConstant::update_all() {
+  for (int i = 0; i < DC_LIMIT; i++) {
+    DelayedConstant* dcon = &delayed_constants[i];
+    if (dcon->value_fn != NULL && dcon->value == 0) {
+      typedef int     (*int_fn_t)();
+      typedef address (*address_fn_t)();
+      switch (dcon->type) {
+      case T_INT:     dcon->value = (intptr_t) ((int_fn_t)    dcon->value_fn)(); break;
+      case T_ADDRESS: dcon->value = (intptr_t) ((address_fn_t)dcon->value_fn)(); break;
+      }
+    }
+  }
+}
+
+intptr_t* AbstractAssembler::delayed_value_addr(int(*value_fn)()) {
+  DelayedConstant* dcon = DelayedConstant::add(T_INT, (DelayedConstant::value_fn_t) value_fn);
+  return &dcon->value;
+}
+intptr_t* AbstractAssembler::delayed_value_addr(address(*value_fn)()) {
+  DelayedConstant* dcon = DelayedConstant::add(T_ADDRESS, (DelayedConstant::value_fn_t) value_fn);
+  return &dcon->value;
+}
+void AbstractAssembler::update_delayed_values() {
+  DelayedConstant::update_all();
+}
+
+
+
 
 void AbstractAssembler::block_comment(const char* comment) {
   if (sect() == CodeBuffer::SECT_INSTS) {
@@ -249,16 +321,19 @@
 bool MacroAssembler::needs_explicit_null_check(intptr_t offset) {
   // Exception handler checks the nmethod's implicit null checks table
   // only when this method returns false.
-  if (UseCompressedOops) {
+#ifdef _LP64
+  if (UseCompressedOops && Universe::narrow_oop_base() != NULL) {
+    assert (Universe::heap() != NULL, "java heap should be initialized");
     // The first page after heap_base is unmapped and
     // the 'offset' is equal to [heap_base + offset] for
     // narrow oop implicit null checks.
-    uintptr_t heap_base = (uintptr_t)Universe::heap_base();
-    if ((uintptr_t)offset >= heap_base) {
+    uintptr_t base = (uintptr_t)Universe::narrow_oop_base();
+    if ((uintptr_t)offset >= base) {
       // Normalize offset for the next check.
-      offset = (intptr_t)(pointer_delta((void*)offset, (void*)heap_base, 1));
+      offset = (intptr_t)(pointer_delta((void*)offset, (void*)base, 1));
     }
   }
+#endif
   return offset < 0 || os::vm_page_size() <= offset;
 }
 
--- a/hotspot/src/share/vm/asm/assembler.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/asm/assembler.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains platform-independant assembler declarations.
+// This file contains platform-independent assembler declarations.
 
 class CodeBuffer;
 class MacroAssembler;
@@ -140,6 +140,28 @@
   }
 };
 
+// A union type for code which has to assemble both constant and
+// non-constant operands, when the distinction cannot be made
+// statically.
+class RegisterOrConstant VALUE_OBJ_CLASS_SPEC {
+ private:
+  Register _r;
+  intptr_t _c;
+
+ public:
+  RegisterOrConstant(): _r(noreg), _c(0) {}
+  RegisterOrConstant(Register r): _r(r), _c(0) {}
+  RegisterOrConstant(intptr_t c): _r(noreg), _c(c) {}
+
+  Register as_register() const { assert(is_register(),""); return _r; }
+  intptr_t as_constant() const { assert(is_constant(),""); return _c; }
+
+  Register register_or_noreg() const { return _r; }
+  intptr_t constant_or_zero() const  { return _c; }
+
+  bool is_register() const { return _r != noreg; }
+  bool is_constant() const { return _r == noreg; }
+};
 
 // The Abstract Assembler: Pure assembler doing NO optimizations on the
 // instruction level; i.e., what you write is what you get.
@@ -280,6 +302,26 @@
   inline address address_constant(Label& L);
   inline address address_table_constant(GrowableArray<Label*> label);
 
+  // Bootstrapping aid to cope with delayed determination of constants.
+  // Returns a static address which will eventually contain the constant.
+  // The value zero (NULL) stands instead of a constant which is still uncomputed.
+  // Thus, the eventual value of the constant must not be zero.
+  // This is fine, since this is designed for embedding object field
+  // offsets in code which must be generated before the object class is loaded.
+  // Field offsets are never zero, since an object's header (mark word)
+  // is located at offset zero.
+  RegisterOrConstant delayed_value(int(*value_fn)(), Register tmp, int offset = 0) {
+    return delayed_value_impl(delayed_value_addr(value_fn), tmp, offset);
+  }
+  RegisterOrConstant delayed_value(address(*value_fn)(), Register tmp, int offset = 0) {
+    return delayed_value_impl(delayed_value_addr(value_fn), tmp, offset);
+  }
+  virtual RegisterOrConstant delayed_value_impl(intptr_t* delayed_value_addr, Register tmp, int offset) = 0;
+  // Last overloading is platform-dependent; look in assembler_<arch>.cpp.
+  static intptr_t* delayed_value_addr(int(*constant_fn)());
+  static intptr_t* delayed_value_addr(address(*constant_fn)());
+  static void update_delayed_values();
+
   // Bang stack to trigger StackOverflowError at a safe location
   // implementation delegates to machine-specific bang_stack_with_offset
   void generate_stack_overflow_check( int frame_size_in_bytes );
--- a/hotspot/src/share/vm/asm/codeBuffer.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/asm/codeBuffer.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/c1/c1_Optimizer.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/c1/c1_Optimizer.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -284,6 +284,11 @@
       //
       int ex_start = handler->start();
       int ex_end = handler->limit();
+      // ensure a block at the start of exception range and start of following code
+      (void) make_block_at(ex_start);
+      if (ex_end < _code_size)
+        (void) make_block_at(ex_end);
+
       if (eb->is_handler()) {
         // Extend old handler exception range to cover additional range.
         int old_ex_start = eb->ex_start_bci();
@@ -295,10 +300,6 @@
         eb->clear_exception_handler(); // Reset exception information
       }
       eb->set_exception_range(ex_start, ex_end);
-      // ensure a block at the start of exception range and start of following code
-      (void) make_block_at(ex_start);
-      if (ex_end < _code_size)
-        (void) make_block_at(ex_end);
     }
   }
 
--- a/hotspot/src/share/vm/ci/ciTypeFlow.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/ci/ciTypeFlow.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -541,7 +541,7 @@
     // is report a value that will meet correctly with any downstream
     // reference types on paths that will truly be executed.  This null type
     // meets with any reference type to yield that same reference type.
-    // (The compiler will generate an unconditonal exception here.)
+    // (The compiler will generate an unconditional exception here.)
     push(null_type());
     return;
   }
@@ -2237,7 +2237,6 @@
   for (SuccIter iter(tail); !iter.done(); iter.next()) {
     if (iter.succ() == head) {
       iter.set_succ(clone);
-      break;
     }
   }
   flow_block(tail, temp_vector, temp_set);
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2747,9 +2747,10 @@
                                                       super_klass(),
                                                       methods(),
                                                       access_flags,
-                                                      class_loader(),
-                                                      class_name(),
-                                                      local_interfaces());
+                                                      class_loader,
+                                                      class_name,
+                                                      local_interfaces(),
+                                                      CHECK_(nullHandle));
 
     // Size of Java itable (in words)
     itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(transitive_interfaces);
@@ -3229,7 +3230,7 @@
       // print out the superclass.
       const char * from = Klass::cast(this_klass())->external_name();
       if (this_klass->java_super() != NULL) {
-        tty->print("RESOLVE %s %s\n", from, instanceKlass::cast(this_klass->java_super())->external_name());
+        tty->print("RESOLVE %s %s (super)\n", from, instanceKlass::cast(this_klass->java_super())->external_name());
       }
       // print out each of the interface classes referred to by this class.
       objArrayHandle local_interfaces(THREAD, this_klass->local_interfaces());
@@ -3239,7 +3240,7 @@
           klassOop k = klassOop(local_interfaces->obj_at(i));
           instanceKlass* to_class = instanceKlass::cast(k);
           const char * to = to_class->external_name();
-          tty->print("RESOLVE %s %s\n", from, to);
+          tty->print("RESOLVE %s %s (interface)\n", from, to);
         }
       }
     }
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -239,22 +239,20 @@
   typeArrayOop value  = java_lang_String::value(obj);
   int          offset = java_lang_String::offset(obj);
   int          length = java_lang_String::length(obj);
-
-  ResourceMark rm(THREAD);
-  symbolHandle result;
-
-  if (length > 0) {
-    int utf8_length = UNICODE::utf8_length(value->char_at_addr(offset), length);
-    char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);
-    UNICODE::convert_to_utf8(value->char_at_addr(offset), length, chars);
-    // Allocate the symbol
-    result = oopFactory::new_symbol_handle(chars, utf8_length, CHECK_(symbolHandle()));
-  } else {
-    result = oopFactory::new_symbol_handle("", 0, CHECK_(symbolHandle()));
-  }
-  return result;
+  jchar* base = value->char_at_addr(offset);
+  symbolOop sym = SymbolTable::lookup_unicode(base, length, THREAD);
+  return symbolHandle(THREAD, sym);
 }
 
+symbolOop java_lang_String::as_symbol_or_null(oop java_string) {
+  typeArrayOop value  = java_lang_String::value(java_string);
+  int          offset = java_lang_String::offset(java_string);
+  int          length = java_lang_String::length(java_string);
+  jchar* base = value->char_at_addr(offset);
+  return SymbolTable::probe_unicode(base, length);
+}
+
+
 int java_lang_String::utf8_length(oop java_string) {
   typeArrayOop value  = java_lang_String::value(java_string);
   int          offset = java_lang_String::offset(java_string);
@@ -385,6 +383,48 @@
 }
 
 
+void java_lang_Class::print_signature(oop java_class, outputStream* st) {
+  assert(java_lang_Class::is_instance(java_class), "must be a Class object");
+  symbolOop name = NULL;
+  bool is_instance = false;
+  if (is_primitive(java_class)) {
+    name = vmSymbols::type_signature(primitive_type(java_class));
+  } else {
+    klassOop k = as_klassOop(java_class);
+    is_instance = Klass::cast(k)->oop_is_instance();
+    name = Klass::cast(k)->name();
+  }
+  if (name == NULL) {
+    st->print("<null>");
+    return;
+  }
+  if (is_instance)  st->print("L");
+  st->write((char*) name->base(), (int) name->utf8_length());
+  if (is_instance)  st->print(";");
+}
+
+symbolOop java_lang_Class::as_signature(oop java_class, bool intern_if_not_found, TRAPS) {
+  assert(java_lang_Class::is_instance(java_class), "must be a Class object");
+  symbolOop name = NULL;
+  if (is_primitive(java_class)) {
+    return vmSymbols::type_signature(primitive_type(java_class));
+  } else {
+    klassOop k = as_klassOop(java_class);
+    if (!Klass::cast(k)->oop_is_instance()) {
+      return Klass::cast(k)->name();
+    } else {
+      ResourceMark rm;
+      const char* sigstr = Klass::cast(k)->signature_name();
+      int         siglen = (int) strlen(sigstr);
+      if (!intern_if_not_found)
+        return SymbolTable::probe(sigstr, siglen);
+      else
+        return oopFactory::new_symbol(sigstr, siglen, THREAD);
+    }
+  }
+}
+
+
 klassOop java_lang_Class::array_klass(oop java_class) {
   klassOop k = klassOop(java_class->obj_field(array_klass_offset));
   assert(k == NULL || k->is_klass() && Klass::cast(k)->oop_is_javaArray(), "should be array klass");
@@ -412,6 +452,8 @@
 
 
 bool java_lang_Class::is_primitive(oop java_class) {
+  // should assert:
+  //assert(java_lang_Class::is_instance(java_class), "must be a Class object");
   klassOop k = klassOop(java_class->obj_field(klass_offset));
   return k == NULL;
 }
@@ -431,6 +473,19 @@
   return type;
 }
 
+BasicType java_lang_Class::as_BasicType(oop java_class, klassOop* reference_klass) {
+  assert(java_lang_Class::is_instance(java_class), "must be a Class object");
+  if (is_primitive(java_class)) {
+    if (reference_klass != NULL)
+      (*reference_klass) = NULL;
+    return primitive_type(java_class);
+  } else {
+    if (reference_klass != NULL)
+      (*reference_klass) = as_klassOop(java_class);
+    return T_OBJECT;
+  }
+}
+
 
 oop java_lang_Class::primitive_mirror(BasicType t) {
   oop mirror = Universe::java_mirror(t);
@@ -1988,6 +2043,21 @@
 }
 
 
+void java_lang_boxing_object::print(BasicType type, jvalue* value, outputStream* st) {
+  switch (type) {
+  case T_BOOLEAN:   st->print("%s", value->z ? "true" : "false");   break;
+  case T_CHAR:      st->print("%d", value->c);                      break;
+  case T_BYTE:      st->print("%d", value->b);                      break;
+  case T_SHORT:     st->print("%d", value->s);                      break;
+  case T_INT:       st->print("%d", value->i);                      break;
+  case T_LONG:      st->print(INT64_FORMAT, value->j);              break;
+  case T_FLOAT:     st->print("%f", value->f);                      break;
+  case T_DOUBLE:    st->print("%lf", value->d);                     break;
+  default:          st->print("type %d?", type);                    break;
+  }
+}
+
+
 // Support for java_lang_ref_Reference
 oop java_lang_ref_Reference::pending_list_lock() {
   instanceKlass* ik = instanceKlass::cast(SystemDictionary::reference_klass());
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -107,6 +107,7 @@
 
   // Conversion
   static symbolHandle as_symbol(Handle java_string, TRAPS);
+  static symbolOop as_symbol_or_null(oop java_string);
 
   // Testers
   static bool is_instance(oop obj) {
@@ -149,6 +150,9 @@
   static oop  create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS);
   // Conversion
   static klassOop as_klassOop(oop java_class);
+  static BasicType as_BasicType(oop java_class, klassOop* reference_klass = NULL);
+  static symbolOop as_signature(oop java_class, bool intern_if_not_found, TRAPS);
+  static void print_signature(oop java_class, outputStream *st);
   // Testing
   static bool is_instance(oop obj) {
     return obj != NULL && obj->klass() == SystemDictionary::class_klass();
@@ -668,6 +672,8 @@
   static BasicType basic_type(oop box);
   static bool is_instance(oop box)                 { return basic_type(box) != T_ILLEGAL; }
   static bool is_instance(oop box, BasicType type) { return basic_type(box) == type; }
+  static void print(oop box, outputStream* st)     { jvalue value;  print(get_value(box, &value), &value, st); }
+  static void print(BasicType type, jvalue* value, outputStream* st);
 
   static int value_offset_in_bytes(BasicType type) {
     return ( type == T_LONG || type == T_DOUBLE ) ? long_value_offset :
--- a/hotspot/src/share/vm/classfile/loaderConstraints.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/loaderConstraints.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,8 +60,10 @@
   bool add_entry(symbolHandle name, klassOop klass1, Handle loader1,
                                     klassOop klass2, Handle loader2);
 
-  void check_signature_loaders(symbolHandle signature, Handle loader1,
-                               Handle loader2, bool is_method, TRAPS);
+  // Note:  The main entry point for this module is via SystemDictionary.
+  // SystemDictionary::check_signature_loaders(symbolHandle signature,
+  //                                           Handle loader1, Handle loader2,
+  //                                           bool is_method, TRAPS)
 
   klassOop find_constrained_klass(symbolHandle name, Handle loader);
   klassOop find_constrained_elem_klass(symbolHandle name, symbolHandle elem_name,
--- a/hotspot/src/share/vm/classfile/symbolTable.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/symbolTable.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -109,6 +109,40 @@
   return the_table()->lookup(index, name, len, hash);
 }
 
+// Suggestion: Push unicode-based lookup all the way into the hashing
+// and probing logic, so there is no need for convert_to_utf8 until
+// an actual new symbolOop is created.
+symbolOop SymbolTable::lookup_unicode(const jchar* name, int utf16_length, TRAPS) {
+  int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
+  char stack_buf[128];
+  if (utf8_length < (int) sizeof(stack_buf)) {
+    char* chars = stack_buf;
+    UNICODE::convert_to_utf8(name, utf16_length, chars);
+    return lookup(chars, utf8_length, THREAD);
+  } else {
+    ResourceMark rm(THREAD);
+    char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
+    UNICODE::convert_to_utf8(name, utf16_length, chars);
+    return lookup(chars, utf8_length, THREAD);
+  }
+}
+
+symbolOop SymbolTable::lookup_only_unicode(const jchar* name, int utf16_length,
+                                           unsigned int& hash) {
+  int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
+  char stack_buf[128];
+  if (utf8_length < (int) sizeof(stack_buf)) {
+    char* chars = stack_buf;
+    UNICODE::convert_to_utf8(name, utf16_length, chars);
+    return lookup_only(chars, utf8_length, hash);
+  } else {
+    ResourceMark rm;
+    char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
+    UNICODE::convert_to_utf8(name, utf16_length, chars);
+    return lookup_only(chars, utf8_length, hash);
+  }
+}
+
 void SymbolTable::add(constantPoolHandle cp, int names_count,
                       const char** names, int* lengths, int* cp_indices,
                       unsigned int* hashValues, TRAPS) {
@@ -126,15 +160,6 @@
   }
 }
 
-// Needed for preloading classes in signatures when compiling.
-
-symbolOop SymbolTable::probe(const char* name, int len) {
-  unsigned int hashValue = hash_symbol(name, len);
-  int index = the_table()->hash_to_index(hashValue);
-  return the_table()->lookup(index, name, len, hashValue);
-}
-
-
 symbolOop SymbolTable::basic_add(int index, u1 *name, int len,
                                  unsigned int hashValue, TRAPS) {
   assert(!Universe::heap()->is_in_reserved(name) || GC_locker::is_active(),
@@ -156,7 +181,7 @@
 
   symbolOop test = lookup(index, (char*)name, len, hashValue);
   if (test != NULL) {
-    // A race occured and another thread introduced the symbol, this one
+    // A race occurred and another thread introduced the symbol, this one
     // will be dropped and collected.
     return test;
   }
@@ -193,7 +218,7 @@
     int index = hash_to_index(hashValues[i]);
     symbolOop test = lookup(index, names[i], lengths[i], hashValues[i]);
     if (test != NULL) {
-      // A race occured and another thread introduced the symbol, this one
+      // A race occurred and another thread introduced the symbol, this one
       // will be dropped and collected. Use test instead.
       cp->symbol_at_put(cp_indices[i], test);
     } else {
--- a/hotspot/src/share/vm/classfile/symbolTable.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/symbolTable.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -91,6 +91,10 @@
   // Only copy to C string to be added if lookup failed.
   static symbolOop lookup(symbolHandle sym, int begin, int end, TRAPS);
 
+  // jchar (utf16) version of lookups
+  static symbolOop lookup_unicode(const jchar* name, int len, TRAPS);
+  static symbolOop lookup_only_unicode(const jchar* name, int len, unsigned int& hash);
+
   static void add(constantPoolHandle cp, int names_count,
                   const char** names, int* lengths, int* cp_indices,
                   unsigned int* hashValues, TRAPS);
@@ -112,7 +116,14 @@
   // Needed for preloading classes in signatures when compiling.
   // Returns the symbol is already present in symbol table, otherwise
   // NULL.  NO ALLOCATION IS GUARANTEED!
-  static symbolOop probe(const char* name, int len);
+  static symbolOop probe(const char* name, int len) {
+    unsigned int ignore_hash;
+    return lookup_only(name, len, ignore_hash);
+  }
+  static symbolOop probe_unicode(const jchar* name, int len) {
+    unsigned int ignore_hash;
+    return lookup_only_unicode(name, len, ignore_hash);
+  }
 
   // Histogram
   static void print_histogram()     PRODUCT_RETURN;
--- a/hotspot/src/share/vm/classfile/systemDictionary.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1964,6 +1964,13 @@
   return T_OBJECT;
 }
 
+KlassHandle SystemDictionaryHandles::box_klass(BasicType t) {
+  if (t >= T_BOOLEAN && t <= T_VOID)
+    return KlassHandle(&SystemDictionary::_box_klasses[t], true);
+  else
+    return KlassHandle();
+}
+
 // Constraints on class loaders. The details of the algorithm can be
 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
@@ -2174,11 +2181,56 @@
 }
 
 
+// Signature constraints ensure that callers and callees agree about
+// the meaning of type names in their signatures.  This routine is the
+// intake for constraints.  It collects them from several places:
+//
+//  * LinkResolver::resolve_method (if check_access is true) requires
+//    that the resolving class (the caller) and the defining class of
+//    the resolved method (the callee) agree on each type in the
+//    method's signature.
+//
+//  * LinkResolver::resolve_interface_method performs exactly the same
+//    checks.
+//
+//  * LinkResolver::resolve_field requires that the constant pool
+//    attempting to link to a field agree with the field's defining
+//    class about the type of the field signature.
+//
+//  * klassVtable::initialize_vtable requires that, when a class
+//    overrides a vtable entry allocated by a superclass, that the
+//    overriding method (i.e., the callee) agree with the superclass
+//    on each type in the method's signature.
+//
+//  * klassItable::initialize_itable requires that, when a class fills
+//    in its itables, for each non-abstract method installed in an
+//    itable, the method (i.e., the callee) agree with the interface
+//    on each type in the method's signature.
+//
+// All those methods have a boolean (check_access, checkconstraints)
+// which turns off the checks.  This is used from specialized contexts
+// such as bootstrapping, dumping, and debugging.
+//
+// No direct constraint is placed between the class and its
+// supertypes.  Constraints are only placed along linked relations
+// between callers and callees.  When a method overrides or implements
+// an abstract method in a supertype (superclass or interface), the
+// constraints are placed as if the supertype were the caller to the
+// overriding method.  (This works well, since callers to the
+// supertype have already established agreement between themselves and
+// the supertype.)  As a result of all this, a class can disagree with
+// its supertype about the meaning of a type name, as long as that
+// class neither calls a relevant method of the supertype, nor is
+// called (perhaps via an override) from the supertype.
+//
+//
+// SystemDictionary::check_signature_loaders(sig, l1, l2)
+//
 // Make sure all class components (including arrays) in the given
 // signature will be resolved to the same class in both loaders.
 // Returns the name of the type that failed a loader constraint check, or
 // NULL if no constraint failed. The returned C string needs cleaning up
-// with a ResourceMark in the caller
+// with a ResourceMark in the caller.  No exception except OOME is thrown.
 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
                                                Handle loader1, Handle loader2,
                                                bool is_method, TRAPS)  {
--- a/hotspot/src/share/vm/classfile/systemDictionary.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/systemDictionary.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -161,6 +161,7 @@
 class SystemDictionary : AllStatic {
   friend class VMStructs;
   friend class CompactingPermGenGen;
+  friend class SystemDictionaryHandles;
   NOT_PRODUCT(friend class instanceKlassKlass;)
 
  public:
@@ -595,3 +596,18 @@
   static bool _has_loadClassInternal;
   static bool _has_checkPackageAccess;
 };
+
+// Cf. vmSymbols vs. vmSymbolHandles
+class SystemDictionaryHandles : AllStatic {
+public:
+  #define WK_KLASS_HANDLE_DECLARE(name, ignore_symbol, option) \
+    static KlassHandle name() { \
+      SystemDictionary::name(); \
+      klassOop* loc = &SystemDictionary::_well_known_klasses[SystemDictionary::WK_KLASS_ENUM_NAME(name)]; \
+      return KlassHandle(loc, true); \
+    }
+  WK_KLASSES_DO(WK_KLASS_HANDLE_DECLARE);
+  #undef WK_KLASS_HANDLE_DECLARE
+
+  static KlassHandle box_klass(BasicType t);
+};
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,6 +49,8 @@
   template(java_lang_Object,                          "java/lang/Object")                         \
   template(java_lang_Class,                           "java/lang/Class")                          \
   template(java_lang_String,                          "java/lang/String")                         \
+  template(java_lang_StringValue,                     "java/lang/StringValue")                    \
+  template(java_lang_StringCache,                     "java/lang/StringValue$StringCache")        \
   template(java_lang_Thread,                          "java/lang/Thread")                         \
   template(java_lang_ThreadGroup,                     "java/lang/ThreadGroup")                    \
   template(java_lang_Cloneable,                       "java/lang/Cloneable")                      \
@@ -284,6 +286,9 @@
   template(value_name,                                "value")                                    \
   template(frontCacheEnabled_name,                    "frontCacheEnabled")                        \
   template(stringCacheEnabled_name,                   "stringCacheEnabled")                       \
+  template(bitCount_name,                             "bitCount")                                 \
+  template(profile_name,                              "profile")                                  \
+  template(equals_name,                               "equals")                                   \
                                                                                                   \
   /* non-intrinsic name/signature pairs: */                                                       \
   template(register_method_name,                      "register")                                 \
@@ -304,6 +309,7 @@
   template(double_long_signature,                     "(D)J")                                     \
   template(double_double_signature,                   "(D)D")                                     \
   template(int_float_signature,                       "(I)F")                                     \
+  template(long_int_signature,                        "(J)I")                                     \
   template(long_long_signature,                       "(J)J")                                     \
   template(long_double_signature,                     "(J)D")                                     \
   template(byte_signature,                            "B")                                        \
@@ -376,7 +382,7 @@
   template(unknown_class_name,                        "<Unknown>")                                                \
                                                                                                                   \
   /* used to identify class loaders handling parallel class loading */                                            \
-  template(parallelCapable_name,                      "parallelLockMap;")                                         \
+  template(parallelCapable_name,                      "parallelLockMap")                                          \
                                                                                                                   \
   /* JVM monitoring and management support */                                                                     \
   template(java_lang_StackTraceElement_array,          "[Ljava/lang/StackTraceElement;")                          \
@@ -507,6 +513,10 @@
    do_name(     doubleToLongBits_name,                           "doubleToLongBits")                                    \
   do_intrinsic(_longBitsToDouble,         java_lang_Double,       longBitsToDouble_name,    long_double_signature, F_S) \
    do_name(     longBitsToDouble_name,                           "longBitsToDouble")                                    \
+                                                                                                                        \
+  do_intrinsic(_bitCount_i,               java_lang_Integer,      bitCount_name,            int_int_signature,   F_S)   \
+  do_intrinsic(_bitCount_l,               java_lang_Long,         bitCount_name,            long_int_signature,  F_S)   \
+                                                                                                                        \
   do_intrinsic(_reverseBytes_i,           java_lang_Integer,      reverseBytes_name,        int_int_signature,   F_S)   \
    do_name(     reverseBytes_name,                               "reverseBytes")                                        \
   do_intrinsic(_reverseBytes_l,           java_lang_Long,         reverseBytes_name,        long_long_signature, F_S)   \
@@ -570,7 +580,6 @@
    do_signature(copyOfRange_signature,        "([Ljava/lang/Object;IILjava/lang/Class;)[Ljava/lang/Object;")            \
                                                                                                                         \
   do_intrinsic(_equalsC,                  java_util_Arrays,       equals_name,    equalsC_signature,             F_S)   \
-   do_name(     equals_name,                                     "equals")                                              \
    do_signature(equalsC_signature,                               "([C[C)Z")                                             \
                                                                                                                         \
   do_intrinsic(_invoke,                   java_lang_reflect_Method, invoke_name, object_array_object_object_signature, F_R) \
@@ -580,6 +589,7 @@
    do_name(     compareTo_name,                                  "compareTo")                                           \
   do_intrinsic(_indexOf,                  java_lang_String,       indexOf_name, string_int_signature,            F_R)   \
    do_name(     indexOf_name,                                    "indexOf")                                             \
+  do_intrinsic(_equals,                   java_lang_String,       equals_name, object_boolean_signature,         F_R)   \
                                                                                                                         \
   do_class(java_nio_Buffer,               "java/nio/Buffer")                                                            \
   do_intrinsic(_checkIndex,               java_nio_Buffer,        checkIndex_name, int_int_signature,            F_R)   \
@@ -696,7 +706,6 @@
   do_signature(putShort_raw_signature,    "(JS)V")                                                                      \
   do_signature(getChar_raw_signature,     "(J)C")                                                                       \
   do_signature(putChar_raw_signature,     "(JC)V")                                                                      \
-  do_signature(getInt_raw_signature,      "(J)I")                                                                       \
   do_signature(putInt_raw_signature,      "(JI)V")                                                                      \
       do_alias(getLong_raw_signature,    /*(J)J*/ long_long_signature)                                                  \
       do_alias(putLong_raw_signature,    /*(JJ)V*/ long_long_void_signature)                                            \
@@ -713,7 +722,7 @@
   do_intrinsic(_getByte_raw,              sun_misc_Unsafe,        getByte_name, getByte_raw_signature,           F_RN)  \
   do_intrinsic(_getShort_raw,             sun_misc_Unsafe,        getShort_name, getShort_raw_signature,         F_RN)  \
   do_intrinsic(_getChar_raw,              sun_misc_Unsafe,        getChar_name, getChar_raw_signature,           F_RN)  \
-  do_intrinsic(_getInt_raw,               sun_misc_Unsafe,        getInt_name, getInt_raw_signature,             F_RN)  \
+  do_intrinsic(_getInt_raw,               sun_misc_Unsafe,        getInt_name, long_int_signature,               F_RN)  \
   do_intrinsic(_getLong_raw,              sun_misc_Unsafe,        getLong_name, getLong_raw_signature,           F_RN)  \
   do_intrinsic(_getFloat_raw,             sun_misc_Unsafe,        getFloat_name, getFloat_raw_signature,         F_RN)  \
   do_intrinsic(_getDouble_raw,            sun_misc_Unsafe,        getDouble_name, getDouble_raw_signature,       F_RN)  \
--- a/hotspot/src/share/vm/code/nmethod.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -380,7 +380,7 @@
 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
   // There are potential race conditions during exception cache updates, so we
   // must own the ExceptionCache_lock before doing ANY modifications. Because
-  // we dont lock during reads, it is possible to have several threads attempt
+  // we don't lock during reads, it is possible to have several threads attempt
   // to update the cache with the same data. We need to check for already inserted
   // copies of the current data before adding it.
 
--- a/hotspot/src/share/vm/code/nmethod.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/code/nmethod.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -167,7 +167,7 @@
   nmFlags flags;           // various flags to keep track of nmethod state
   bool _markedForDeoptimization;       // Used for stack deoptimization
   enum { alive        = 0,
-         not_entrant  = 1, // uncommon trap has happend but activations may still exist
+         not_entrant  = 1, // uncommon trap has happened but activations may still exist
          zombie       = 2,
          unloaded     = 3 };
 
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -393,7 +393,7 @@
    // Restarts the concurrent phases timer.
    void concurrent_phases_resume();
 
-   // Time begining and end of the marking phase for
+   // Time beginning and end of the marking phase for
    // a synchronous MS collection.  A MS collection
    // that finishes in the foreground can have started
    // in the background.  These methods capture the
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -69,7 +69,7 @@
   // end of the sweep of the tenured generation.
   PerfVariable* _avg_cms_free_counter;
   // Average of the free space in the tenured generation at the
-  // start of the sweep of the tenured genertion.
+  // start of the sweep of the tenured generation.
   PerfVariable* _avg_cms_free_at_sweep_counter;
   // Average of the free space in the tenured generation at the
   // after any resizing of the tenured generation at the end
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -3847,7 +3847,7 @@
   MutexLockerEx ml(ovflw_stk->par_lock(),
                    Mutex::_no_safepoint_check_flag);
   // Grab up to 1/4 the size of the work queue
-  size_t num = MIN2((size_t)work_q->max_elems()/4,
+  size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
                     (size_t)ParGCDesiredObjsFromOverflowList);
   num = MIN2(num, ovflw_stk->length());
   for (int i = (int) num; i > 0; i--) {
@@ -4178,7 +4178,7 @@
     // and is deferred for now; see CR# TBF. 07252005YSR. XXX
     assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
     // If _restart_addr is non-NULL, a marking stack overflow
-    // occured; we need to do a fresh marking iteration from the
+    // occurred; we need to do a fresh marking iteration from the
     // indicated restart address.
     if (_foregroundGCIsActive && asynch) {
       // We may be running into repeated stack overflows, having
@@ -4221,7 +4221,7 @@
   // should be incremental with periodic yields.
   _markBitMap.iterate(&markFromRootsClosure);
   // If _restart_addr is non-NULL, a marking stack overflow
-  // occured; we need to do a fresh iteration from the
+  // occurred; we need to do a fresh iteration from the
   // indicated restart address.
   while (_restart_addr != NULL) {
     if (_foregroundGCIsActive && asynch) {
@@ -5204,13 +5204,12 @@
   NOT_PRODUCT(int num_steals = 0;)
   oop obj_to_scan;
   CMSBitMap* bm = &(_collector->_markBitMap);
-  size_t num_from_overflow_list =
-           MIN2((size_t)work_q->max_elems()/4,
-                (size_t)ParGCDesiredObjsFromOverflowList);
 
   while (true) {
     // Completely finish any left over work from (an) earlier round(s)
     cl->trim_queue(0);
+    size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
+                                         (size_t)ParGCDesiredObjsFromOverflowList);
     // Now check if there's any work in the overflow list
     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
                                                 work_q)) {
@@ -5622,13 +5621,12 @@
   OopTaskQueue* work_q = work_queue(i);
   NOT_PRODUCT(int num_steals = 0;)
   oop obj_to_scan;
-  size_t num_from_overflow_list =
-           MIN2((size_t)work_q->max_elems()/4,
-                (size_t)ParGCDesiredObjsFromOverflowList);
 
   while (true) {
     // Completely finish any left over work from (an) earlier round(s)
     drain->trim_queue(0);
+    size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
+                                         (size_t)ParGCDesiredObjsFromOverflowList);
     // Now check if there's any work in the overflow list
     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
                                                 work_q)) {
@@ -9021,7 +9019,7 @@
 // Transfer some number of overflown objects to usual marking
 // stack. Return true if some objects were transferred.
 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
-  size_t num = MIN2((size_t)_mark_stack->capacity()/4,
+  size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
                     (size_t)ParGCDesiredObjsFromOverflowList);
 
   bool res = _collector->take_from_overflow_list(num, _mark_stack);
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -277,8 +277,6 @@
     gclog_or_tty->print("H: ");
   if (hr->in_collection_set())
     gclog_or_tty->print("CS: ");
-  if (hr->popular())
-    gclog_or_tty->print("pop: ");
   gclog_or_tty->print_cr("Region " PTR_FORMAT " (%s%s) "
                          "[" PTR_FORMAT ", " PTR_FORMAT"] "
                          "Used: " SIZE_FORMAT "K, garbage: " SIZE_FORMAT "K.",
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -145,14 +145,9 @@
   if (G1RSBarrierUseQueue) {
     DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
     dcqs.abandon_logs();
-    if (_cg1rThread->do_traversal()) {
-      _pya = PYA_restart;
-    } else {
-      _cg1rThread->set_do_traversal(true);
-      // Reset the post-yield actions.
-      _pya = PYA_continue;
-      _last_pya = PYA_continue;
-    }
+    // Reset the post-yield actions.
+    _pya = PYA_continue;
+    _last_pya = PYA_continue;
   } else {
     _pya = PYA_restart;
   }
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -133,14 +133,12 @@
       _co_tracker.update(false);
 
       if (G1SmoothConcRefine) {
-        start_vtime_sec = os::elapsedVTime();
         prev_buffer_num = curr_buffer_num;
-
         _sts.leave();
         os::sleep(Thread::current(), (jlong) _interval_ms, false);
         _sts.join();
+        start_vtime_sec = os::elapsedVTime();
       }
-
       n_logs++;
     }
     // Make sure we harvest the PYA, if any.
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -107,7 +107,7 @@
 #ifndef PRODUCT
 bool CMBitMapRO::covers(ReservedSpace rs) const {
   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
-  assert(((size_t)_bm.size() * (1 << _shifter)) == _bmWordSize,
+  assert(((size_t)_bm.size() * (size_t)(1 << _shifter)) == _bmWordSize,
          "size inconsistency");
   return _bmStartWord == (HeapWord*)(rs.base()) &&
          _bmWordSize  == rs.size()>>LogHeapWordSize;
@@ -420,6 +420,10 @@
 
   _has_overflown(false),
   _concurrent(false),
+  _has_aborted(false),
+  _restart_for_overflow(false),
+  _concurrent_marking_in_progress(false),
+  _should_gray_objects(false),
 
   // _verbose_level set below
 
@@ -1228,7 +1232,16 @@
     if (!_final && _regions_done == 0)
       _start_vtime_sec = os::elapsedVTime();
 
-    if (hr->continuesHumongous()) return false;
+    if (hr->continuesHumongous()) {
+      HeapRegion* hum_start = hr->humongous_start_region();
+      // If the head region of the humongous region has been determined
+      // to be alive, then all the tail regions should be marked
+      // such as well.
+      if (_region_bm->at(hum_start->hrs_index())) {
+        _region_bm->par_at_put(hr->hrs_index(), 1);
+      }
+      return false;
+    }
 
     HeapWord* nextTop = hr->next_top_at_mark_start();
     HeapWord* start   = hr->top_at_conc_mark_count();
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -107,7 +107,7 @@
       if (PrintGC) {
         gclog_or_tty->date_stamp(PrintGCDateStamps);
         gclog_or_tty->stamp(PrintGCTimeStamps);
-        tty->print_cr("[GC concurrent-mark-start]");
+        gclog_or_tty->print_cr("[GC concurrent-mark-start]");
       }
 
       if (!g1_policy->in_young_gc_mode()) {
@@ -320,8 +320,6 @@
   set_in_progress();
   clear_started();
   if (TraceConcurrentMark) gclog_or_tty->print_cr("CM-starting");
-
-  return;
 }
 
 // Note: this method, although exported by the ConcurrentMarkSweepThread,
--- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -78,8 +78,8 @@
 
 void DirtyCardQueueSet::initialize(Monitor* cbl_mon, Mutex* fl_lock,
                                    int max_completed_queue,
-                                   Mutex* lock) {
-  PtrQueueSet::initialize(cbl_mon, fl_lock, max_completed_queue);
+                                   Mutex* lock, PtrQueueSet* fl_owner) {
+  PtrQueueSet::initialize(cbl_mon, fl_lock, max_completed_queue, fl_owner);
   set_buffer_size(DCQBarrierQueueBufferSize);
   set_process_completed_threshold(DCQBarrierProcessCompletedThreshold);
 
--- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -88,7 +88,7 @@
 
   void initialize(Monitor* cbl_mon, Mutex* fl_lock,
                   int max_completed_queue = 0,
-                  Mutex* lock = NULL);
+                  Mutex* lock = NULL, PtrQueueSet* fl_owner = NULL);
 
   // The number of parallel ids that can be claimed to allow collector or
   // mutator threads to do card-processing work.
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,21 +42,6 @@
 
 // Local to this file.
 
-// Finds the first HeapRegion.
-// No longer used, but might be handy someday.
-
-class FindFirstRegionClosure: public HeapRegionClosure {
-  HeapRegion* _a_region;
-public:
-  FindFirstRegionClosure() : _a_region(NULL) {}
-  bool doHeapRegion(HeapRegion* r) {
-    _a_region = r;
-    return true;
-  }
-  HeapRegion* result() { return _a_region; }
-};
-
-
 class RefineCardTableEntryClosure: public CardTableEntryClosure {
   SuspendibleThreadSet* _sts;
   G1RemSet* _g1rs;
@@ -136,6 +121,14 @@
   int calls() { return _calls; }
 };
 
+class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
+public:
+  bool do_card_ptr(jbyte* card_ptr, int worker_i) {
+    *card_ptr = CardTableModRefBS::dirty_card_val();
+    return true;
+  }
+};
+
 YoungList::YoungList(G1CollectedHeap* g1h)
   : _g1h(g1h), _head(NULL),
     _scan_only_head(NULL), _scan_only_tail(NULL), _curr_scan_only(NULL),
@@ -778,6 +771,12 @@
   }
 }
 
+void G1CollectedHeap::abandon_gc_alloc_regions() {
+  // first, make sure that the GC alloc region list is empty (it should!)
+  assert(_gc_alloc_region_list == NULL, "invariant");
+  release_gc_alloc_regions(true /* totally */);
+}
+
 class PostMCRemSetClearClosure: public HeapRegionClosure {
   ModRefBarrierSet* _mr_bs;
 public:
@@ -812,6 +811,40 @@
   }
 };
 
+class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
+  G1CollectedHeap*   _g1h;
+  UpdateRSOopClosure _cl;
+  int                _worker_i;
+public:
+  RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
+    _cl(g1->g1_rem_set()->as_HRInto_G1RemSet(), worker_i),
+    _worker_i(worker_i),
+    _g1h(g1)
+  { }
+  bool doHeapRegion(HeapRegion* r) {
+    if (!r->continuesHumongous()) {
+      _cl.set_from(r);
+      r->oop_iterate(&_cl);
+    }
+    return false;
+  }
+};
+
+class ParRebuildRSTask: public AbstractGangTask {
+  G1CollectedHeap* _g1;
+public:
+  ParRebuildRSTask(G1CollectedHeap* g1)
+    : AbstractGangTask("ParRebuildRSTask"),
+      _g1(g1)
+  { }
+
+  void work(int i) {
+    RebuildRSOutOfRegionClosure rebuild_rs(_g1, i);
+    _g1->heap_region_par_iterate_chunked(&rebuild_rs, i,
+                                         HeapRegion::RebuildRSClaimValue);
+  }
+};
+
 void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs,
                                     size_t word_size) {
   ResourceMark rm;
@@ -872,6 +905,7 @@
 
     // Make sure we'll choose a new allocation region afterwards.
     abandon_cur_alloc_region();
+    abandon_gc_alloc_regions();
     assert(_cur_alloc_region == NULL, "Invariant.");
     g1_rem_set()->as_HRInto_G1RemSet()->cleanupHRRS();
     tear_down_region_lists();
@@ -912,30 +946,42 @@
     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
       HandleMark hm;  // Discard invalid handles created during verification
       gclog_or_tty->print(" VerifyAfterGC:");
+      prepare_for_verify();
       Universe::verify(false);
     }
     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 
     reset_gc_time_stamp();
     // Since everything potentially moved, we will clear all remembered
-    // sets, and clear all cards.  Later we will also cards in the used
-    // portion of the heap after the resizing (which could be a shrinking.)
-    // We will also reset the GC time stamps of the regions.
+    // sets, and clear all cards.  Later we will rebuild remebered
+    // sets. We will also reset the GC time stamps of the regions.
     PostMCRemSetClearClosure rs_clear(mr_bs());
     heap_region_iterate(&rs_clear);
 
     // Resize the heap if necessary.
     resize_if_necessary_after_full_collection(full ? 0 : word_size);
 
-    // Since everything potentially moved, we will clear all remembered
-    // sets, but also dirty all cards corresponding to used regions.
-    PostMCRemSetInvalidateClosure rs_invalidate(mr_bs());
-    heap_region_iterate(&rs_invalidate);
     if (_cg1r->use_cache()) {
       _cg1r->clear_and_record_card_counts();
       _cg1r->clear_hot_cache();
     }
 
+    // Rebuild remembered sets of all regions.
+    if (ParallelGCThreads > 0) {
+      ParRebuildRSTask rebuild_rs_task(this);
+      assert(check_heap_region_claim_values(
+             HeapRegion::InitialClaimValue), "sanity check");
+      set_par_threads(workers()->total_workers());
+      workers()->run_task(&rebuild_rs_task);
+      set_par_threads(0);
+      assert(check_heap_region_claim_values(
+             HeapRegion::RebuildRSClaimValue), "sanity check");
+      reset_heap_region_claim_values();
+    } else {
+      RebuildRSOutOfRegionClosure rebuild_rs(this);
+      heap_region_iterate(&rebuild_rs);
+    }
+
     if (PrintGC) {
       print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
     }
@@ -961,7 +1007,8 @@
     // dirtied, so this should abandon those logs, and set "do_traversal"
     // to true.
     concurrent_g1_refine()->set_pya_restart();
-
+    assert(!G1DeferredRSUpdate
+           || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
     assert(regions_accounted_for(), "Region leakage!");
   }
 
@@ -1145,13 +1192,12 @@
                                                    bool par) {
   assert(!hr->continuesHumongous(), "should have filtered these out");
   size_t res = 0;
-  if (!hr->popular() && hr->used() > 0 && hr->garbage_bytes() == hr->used()) {
-    if (!hr->is_young()) {
-      if (G1PolicyVerbose > 0)
-        gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
-                               " during cleanup", hr, hr->used());
-      free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
-    }
+  if (hr->used() > 0 && hr->garbage_bytes() == hr->used() &&
+      !hr->is_young()) {
+    if (G1PolicyVerbose > 0)
+      gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
+                                                                               " during cleanup", hr, hr->used());
+    free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
   }
 }
 
@@ -1252,7 +1298,7 @@
 }
 
 void G1CollectedHeap::shrink(size_t shrink_bytes) {
-  release_gc_alloc_regions();
+  release_gc_alloc_regions(true /* totally */);
   tear_down_region_lists();  // We will rebuild them in a moment.
   shrink_helper(shrink_bytes);
   rebuild_region_lists();
@@ -1280,10 +1326,6 @@
   _refine_cte_cl(NULL),
   _free_region_list(NULL), _free_region_list_size(0),
   _free_regions(0),
-  _popular_object_boundary(NULL),
-  _cur_pop_hr_index(0),
-  _popular_regions_to_be_evacuated(NULL),
-  _pop_obj_rc_at_copy(),
   _full_collection(false),
   _unclean_region_list(),
   _unclean_regions_coming(false),
@@ -1291,8 +1333,7 @@
   _gc_time_stamp(0),
   _surviving_young_words(NULL),
   _in_cset_fast_test(NULL),
-  _in_cset_fast_test_base(NULL)
-{
+  _in_cset_fast_test_base(NULL) {
   _g1h = this; // To catch bugs.
   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
     vm_exit_during_initialization("Failed necessary allocation.");
@@ -1317,9 +1358,19 @@
   }
 
   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
-    _gc_alloc_regions[ap]       = NULL;
-    _gc_alloc_region_counts[ap] = 0;
-  }
+    _gc_alloc_regions[ap]          = NULL;
+    _gc_alloc_region_counts[ap]    = 0;
+    _retained_gc_alloc_regions[ap] = NULL;
+    // by default, we do not retain a GC alloc region for each ap;
+    // we'll override this, when appropriate, below
+    _retain_gc_alloc_region[ap]    = false;
+  }
+
+  // We will try to remember the last half-full tenured region we
+  // allocated to at the end of a collection so that we can re-use it
+  // during the next collection.
+  _retain_gc_alloc_region[GCAllocForTenured]  = true;
+
   guarantee(_task_queues != NULL, "task_queues allocation failure.");
 }
 
@@ -1351,9 +1402,34 @@
   // Reserve the maximum.
   PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
   // Includes the perm-gen.
+
+  const size_t total_reserved = max_byte_size + pgs->max_size();
+  char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
+
   ReservedSpace heap_rs(max_byte_size + pgs->max_size(),
                         HeapRegion::GrainBytes,
-                        false /*ism*/);
+                        false /*ism*/, addr);
+
+  if (UseCompressedOops) {
+    if (addr != NULL && !heap_rs.is_reserved()) {
+      // Failed to reserve at specified address - the requested memory
+      // region is taken already, for example, by 'java' launcher.
+      // Try again to reserver heap higher.
+      addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
+      ReservedSpace heap_rs0(total_reserved, HeapRegion::GrainBytes,
+                             false /*ism*/, addr);
+      if (addr != NULL && !heap_rs0.is_reserved()) {
+        // Failed to reserve at specified address again - give up.
+        addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
+        assert(addr == NULL, "");
+        ReservedSpace heap_rs1(total_reserved, HeapRegion::GrainBytes,
+                               false /*ism*/, addr);
+        heap_rs = heap_rs1;
+      } else {
+        heap_rs = heap_rs0;
+      }
+    }
+  }
 
   if (!heap_rs.is_reserved()) {
     vm_exit_during_initialization("Could not reserve enough space for object heap");
@@ -1424,26 +1500,11 @@
     _czft = new ConcurrentZFThread();
   }
 
-
-
-  // Allocate the popular regions; take them off free lists.
-  size_t pop_byte_size = G1NumPopularRegions * HeapRegion::GrainBytes;
-  expand(pop_byte_size);
-  _popular_object_boundary =
-    _g1_reserved.start() + (G1NumPopularRegions * HeapRegion::GrainWords);
-  for (int i = 0; i < G1NumPopularRegions; i++) {
-    HeapRegion* hr = newAllocRegion(HeapRegion::GrainWords);
-    //    assert(hr != NULL && hr->bottom() < _popular_object_boundary,
-    //     "Should be enough, and all should be below boundary.");
-    hr->set_popular(true);
-  }
-  assert(_cur_pop_hr_index == 0, "Start allocating at the first region.");
-
   // Initialize the from_card cache structure of HeapRegionRemSet.
   HeapRegionRemSet::init_heap(max_regions());
 
-  // Now expand into the rest of the initial heap size.
-  expand(init_byte_size - pop_byte_size);
+  // Now expand into the initial heap size.
+  expand(init_byte_size);
 
   // Perform any initialization actions delegated to the policy.
   g1_policy()->init();
@@ -1466,6 +1527,13 @@
                                                   G1DirtyCardQueueMax,
                                                   Shared_DirtyCardQ_lock);
   }
+  if (G1DeferredRSUpdate) {
+    dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
+                                      DirtyCardQ_FL_lock,
+                                      0,
+                                      Shared_DirtyCardQ_lock,
+                                      &JavaThread::dirty_card_queue_set());
+  }
   // In case we're keeping closure specialization stats, initialize those
   // counts and that mechanism.
   SpecializationStats::clear();
@@ -1551,8 +1619,7 @@
 class SumUsedRegionsClosure: public HeapRegionClosure {
   size_t _num;
 public:
-  // _num is set to 1 to account for the popular region
-  SumUsedRegionsClosure() : _num(G1NumPopularRegions) {}
+  SumUsedRegionsClosure() : _num(0) {}
   bool doHeapRegion(HeapRegion* r) {
     if (r->continuesHumongous() || r->used() > 0 || r->is_gc_alloc_region()) {
       _num += 1;
@@ -1655,14 +1722,20 @@
   }
 };
 
-void G1CollectedHeap::oop_iterate(OopClosure* cl) {
+void G1CollectedHeap::oop_iterate(OopClosure* cl, bool do_perm) {
   IterateOopClosureRegionClosure blk(_g1_committed, cl);
   _hrs->iterate(&blk);
+  if (do_perm) {
+    perm_gen()->oop_iterate(cl);
+  }
 }
 
-void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
+void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm) {
   IterateOopClosureRegionClosure blk(mr, cl);
   _hrs->iterate(&blk);
+  if (do_perm) {
+    perm_gen()->oop_iterate(cl);
+  }
 }
 
 // Iterates an ObjectClosure over all objects within a HeapRegion.
@@ -1679,9 +1752,12 @@
   }
 };
 
-void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
+void G1CollectedHeap::object_iterate(ObjectClosure* cl, bool do_perm) {
   IterateObjectClosureRegionClosure blk(cl);
   _hrs->iterate(&blk);
+  if (do_perm) {
+    perm_gen()->object_iterate(cl);
+  }
 }
 
 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
@@ -2058,15 +2134,7 @@
   bool doHeapRegion(HeapRegion* r) {
     guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue,
               "Should be unclaimed at verify points.");
-    if (r->isHumongous()) {
-      if (r->startsHumongous()) {
-        // Verify the single H object.
-        oop(r->bottom())->verify();
-        size_t word_sz = oop(r->bottom())->size();
-        guarantee(r->top() == r->bottom() + word_sz,
-                  "Only one object in a humongous region");
-      }
-    } else {
+    if (!r->continuesHumongous()) {
       VerifyObjsInRegionClosure not_dead_yet_cl(r);
       r->verify(_allow_dirty);
       r->object_iterate(&not_dead_yet_cl);
@@ -2118,6 +2186,7 @@
     _g1h(g1h), _allow_dirty(allow_dirty) { }
 
   void work(int worker_i) {
+    HandleMark hm;
     VerifyRegionClosure blk(_allow_dirty, true);
     _g1h->heap_region_par_iterate_chunked(&blk, worker_i,
                                           HeapRegion::ParVerifyClaimValue);
@@ -2222,9 +2291,6 @@
   if (SummarizeG1ZFStats) {
     ConcurrentZFThread::print_summary_info();
   }
-  if (G1SummarizePopularity) {
-    print_popularity_summary_info();
-  }
   g1_policy()->print_yg_surv_rate_info();
 
   GCOverheadReporter::printGCOverhead();
@@ -2316,10 +2382,9 @@
 void
 G1CollectedHeap::checkConcurrentMark() {
     VerifyMarkedObjsClosure verifycl(this);
-    doConcurrentMark();
     //    MutexLockerEx x(getMarkBitMapLock(),
     //              Mutex::_no_safepoint_check_flag);
-    object_iterate(&verifycl);
+    object_iterate(&verifycl, false);
 }
 
 void G1CollectedHeap::do_sync_mark() {
@@ -2400,30 +2465,19 @@
 // </NEW PREDICTION>
 
 void
-G1CollectedHeap::do_collection_pause_at_safepoint(HeapRegion* popular_region) {
+G1CollectedHeap::do_collection_pause_at_safepoint() {
   char verbose_str[128];
   sprintf(verbose_str, "GC pause ");
-  if (popular_region != NULL)
-    strcat(verbose_str, "(popular)");
-  else if (g1_policy()->in_young_gc_mode()) {
+  if (g1_policy()->in_young_gc_mode()) {
     if (g1_policy()->full_young_gcs())
       strcat(verbose_str, "(young)");
     else
       strcat(verbose_str, "(partial)");
   }
-  bool reset_should_initiate_conc_mark = false;
-  if (popular_region != NULL && g1_policy()->should_initiate_conc_mark()) {
-    // we currently do not allow an initial mark phase to be piggy-backed
-    // on a popular pause
-    reset_should_initiate_conc_mark = true;
-    g1_policy()->unset_should_initiate_conc_mark();
-  }
   if (g1_policy()->should_initiate_conc_mark())
     strcat(verbose_str, " (initial-mark)");
 
-  GCCauseSetter x(this, (popular_region == NULL ?
-                         GCCause::_g1_inc_collection_pause :
-                         GCCause::_g1_pop_region_collection_pause));
+  GCCauseSetter x(this, GCCause::_g1_inc_collection_pause);
 
   // if PrintGCDetails is on, we'll print long statistics information
   // in the collector policy code, so let's not print this as the output
@@ -2493,7 +2547,7 @@
 
     guarantee(_in_cset_fast_test == NULL, "invariant");
     guarantee(_in_cset_fast_test_base == NULL, "invariant");
-    _in_cset_fast_test_length = n_regions();
+    _in_cset_fast_test_length = max_regions();
     _in_cset_fast_test_base =
                              NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length);
     memset(_in_cset_fast_test_base, false,
@@ -2513,8 +2567,8 @@
     }
     save_marks();
 
-    // We must do this before any possible evacuation that should propogate
-    // marks, including evacuation of popular objects in a popular pause.
+    // We must do this before any possible evacuation that should propagate
+    // marks.
     if (mark_in_progress()) {
       double start_time_sec = os::elapsedTime();
 
@@ -2531,29 +2585,15 @@
 
     assert(regions_accounted_for(), "Region leakage.");
 
-    bool abandoned = false;
-
     if (mark_in_progress())
       concurrent_mark()->newCSet();
 
     // Now choose the CS.
-    if (popular_region == NULL) {
-      g1_policy()->choose_collection_set();
-    } else {
-      // We may be evacuating a single region (for popularity).
-      g1_policy()->record_popular_pause_preamble_start();
-      popularity_pause_preamble(popular_region);
-      g1_policy()->record_popular_pause_preamble_end();
-      abandoned = (g1_policy()->collection_set() == NULL);
-      // Now we allow more regions to be added (we have to collect
-      // all popular regions).
-      if (!abandoned) {
-        g1_policy()->choose_collection_set(popular_region);
-      }
-    }
+    g1_policy()->choose_collection_set();
+
     // We may abandon a pause if we find no region that will fit in the MMU
     // pause.
-    abandoned = (g1_policy()->collection_set() == NULL);
+    bool abandoned = (g1_policy()->collection_set() == NULL);
 
     // Nothing to do if we were unable to choose a collection set.
     if (!abandoned) {
@@ -2578,13 +2618,7 @@
       _in_cset_fast_test = NULL;
       _in_cset_fast_test_base = NULL;
 
-      if (popular_region != NULL) {
-        // We have to wait until now, because we don't want the region to
-        // be rescheduled for pop-evac during RS update.
-        popular_region->set_popular_pending(false);
-      }
-
-      release_gc_alloc_regions();
+      release_gc_alloc_regions(false /* totally */);
 
       cleanup_surviving_young_words();
 
@@ -2626,18 +2660,17 @@
 #endif // SCAN_ONLY_VERBOSE
 
     double end_time_sec = os::elapsedTime();
-    if (!evacuation_failed()) {
-      g1_policy()->record_pause_time((end_time_sec - start_time_sec)*1000.0);
-    }
+    double pause_time_ms = (end_time_sec - start_time_sec) * MILLIUNITS;
+    g1_policy()->record_pause_time_ms(pause_time_ms);
     GCOverheadReporter::recordSTWEnd(end_time_sec);
-    g1_policy()->record_collection_pause_end(popular_region != NULL,
-                                             abandoned);
+    g1_policy()->record_collection_pause_end(abandoned);
 
     assert(regions_accounted_for(), "Region leakage.");
 
     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
       HandleMark hm;  // Discard invalid handles created during verification
       gclog_or_tty->print(" VerifyAfterGC:");
+      prepare_for_verify();
       Universe::verify(false);
     }
 
@@ -2664,9 +2697,6 @@
 
   assert(verify_region_lists(), "Bad region lists.");
 
-  if (reset_should_initiate_conc_mark)
-    g1_policy()->set_should_initiate_conc_mark();
-
   if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
     gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
     print_tracing_info();
@@ -2676,6 +2706,10 @@
 
 void G1CollectedHeap::set_gc_alloc_region(int purpose, HeapRegion* r) {
   assert(purpose >= 0 && purpose < GCAllocPurposeCount, "invalid purpose");
+  // make sure we don't call set_gc_alloc_region() multiple times on
+  // the same region
+  assert(r == NULL || !r->is_gc_alloc_region(),
+         "shouldn't already be a GC alloc region");
   HeapWord* original_top = NULL;
   if (r != NULL)
     original_top = r->top();
@@ -2765,6 +2799,12 @@
   while (_gc_alloc_region_list != NULL) {
     HeapRegion* r = _gc_alloc_region_list;
     assert(r->is_gc_alloc_region(), "Invariant.");
+    // We need HeapRegion::oops_on_card_seq_iterate_careful() to work on
+    // newly allocated data in order to be able to apply deferred updates
+    // before the GC is done for verification purposes (i.e to allow
+    // G1HRRSFlushLogBuffersOnVerify). It's safe thing to do after the
+    // collection.
+    r->ContiguousSpace::set_saved_mark();
     _gc_alloc_region_list = r->next_gc_alloc_region();
     r->set_next_gc_alloc_region(NULL);
     r->set_is_gc_alloc_region(false);
@@ -2792,23 +2832,55 @@
 }
 
 void G1CollectedHeap::get_gc_alloc_regions() {
+  // First, let's check that the GC alloc region list is empty (it should)
+  assert(_gc_alloc_region_list == NULL, "invariant");
+
   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
+    assert(_gc_alloc_regions[ap] == NULL, "invariant");
+
     // Create new GC alloc regions.
-    HeapRegion* alloc_region = _gc_alloc_regions[ap];
-    // Clear this alloc region, so that in case it turns out to be
-    // unacceptable, we end up with no allocation region, rather than a bad
-    // one.
-    _gc_alloc_regions[ap] = NULL;
-    if (alloc_region == NULL || alloc_region->in_collection_set()) {
-      // Can't re-use old one.  Allocate a new one.
+    HeapRegion* alloc_region = _retained_gc_alloc_regions[ap];
+    _retained_gc_alloc_regions[ap] = NULL;
+
+    if (alloc_region != NULL) {
+      assert(_retain_gc_alloc_region[ap], "only way to retain a GC region");
+
+      // let's make sure that the GC alloc region is not tagged as such
+      // outside a GC operation
+      assert(!alloc_region->is_gc_alloc_region(), "sanity");
+
+      if (alloc_region->in_collection_set() ||
+          alloc_region->top() == alloc_region->end() ||
+          alloc_region->top() == alloc_region->bottom()) {
+        // we will discard the current GC alloc region if it's in the
+        // collection set (it can happen!), if it's already full (no
+        // point in using it), or if it's empty (this means that it
+        // was emptied during a cleanup and it should be on the free
+        // list now).
+
+        alloc_region = NULL;
+      }
+    }
+
+    if (alloc_region == NULL) {
+      // we will get a new GC alloc region
       alloc_region = newAllocRegionWithExpansion(ap, 0);
     }
+
     if (alloc_region != NULL) {
+      assert(_gc_alloc_regions[ap] == NULL, "pre-condition");
       set_gc_alloc_region(ap, alloc_region);
     }
+
+    assert(_gc_alloc_regions[ap] == NULL ||
+           _gc_alloc_regions[ap]->is_gc_alloc_region(),
+           "the GC alloc region should be tagged as such");
+    assert(_gc_alloc_regions[ap] == NULL ||
+           _gc_alloc_regions[ap] == _gc_alloc_region_list,
+           "the GC alloc region should be the same as the GC alloc list head");
   }
   // Set alternative regions for allocation purposes that have reached
-  // thier limit.
+  // their limit.
   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
     GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(ap);
     if (_gc_alloc_regions[ap] == NULL && alt_purpose != ap) {
@@ -2818,28 +2890,56 @@
   assert(check_gc_alloc_regions(), "alloc regions messed up");
 }
 
-void G1CollectedHeap::release_gc_alloc_regions() {
+void G1CollectedHeap::release_gc_alloc_regions(bool totally) {
   // We keep a separate list of all regions that have been alloc regions in
-  // the current collection pause.  Forget that now.
+  // the current collection pause. Forget that now. This method will
+  // untag the GC alloc regions and tear down the GC alloc region
+  // list. It's desirable that no regions are tagged as GC alloc
+  // outside GCs.
   forget_alloc_region_list();
 
   // The current alloc regions contain objs that have survived
   // collection. Make them no longer GC alloc regions.
   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
     HeapRegion* r = _gc_alloc_regions[ap];
-    if (r != NULL && r->is_empty()) {
-      {
+    _retained_gc_alloc_regions[ap] = NULL;
+
+    if (r != NULL) {
+      // we retain nothing on _gc_alloc_regions between GCs
+      set_gc_alloc_region(ap, NULL);
+      _gc_alloc_region_counts[ap] = 0;
+
+      if (r->is_empty()) {
+        // we didn't actually allocate anything in it; let's just put
+        // it on the free list
         MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
         r->set_zero_fill_complete();
         put_free_region_on_list_locked(r);
+      } else if (_retain_gc_alloc_region[ap] && !totally) {
+        // retain it so that we can use it at the beginning of the next GC
+        _retained_gc_alloc_regions[ap] = r;
       }
     }
-    // set_gc_alloc_region will also NULLify all aliases to the region
-    set_gc_alloc_region(ap, NULL);
-    _gc_alloc_region_counts[ap] = 0;
   }
 }
 
+#ifndef PRODUCT
+// Useful for debugging
+
+void G1CollectedHeap::print_gc_alloc_regions() {
+  gclog_or_tty->print_cr("GC alloc regions");
+  for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
+    HeapRegion* r = _gc_alloc_regions[ap];
+    if (r == NULL) {
+      gclog_or_tty->print_cr("  %2d : "PTR_FORMAT, ap, NULL);
+    } else {
+      gclog_or_tty->print_cr("  %2d : "PTR_FORMAT" "SIZE_FORMAT,
+                             ap, r->bottom(), r->used());
+    }
+  }
+}
+#endif // PRODUCT
+
 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
   _drain_in_progress = false;
   set_evac_failure_closure(cl);
@@ -2919,27 +3019,51 @@
   }
 };
 
-class RecreateRSetEntriesClosure: public OopClosure {
+class UpdateRSetImmediate : public OopsInHeapRegionClosure {
 private:
   G1CollectedHeap* _g1;
   G1RemSet* _g1_rem_set;
-  HeapRegion* _from;
 public:
-  RecreateRSetEntriesClosure(G1CollectedHeap* g1, HeapRegion* from) :
-    _g1(g1), _g1_rem_set(g1->g1_rem_set()), _from(from)
-  {}
+  UpdateRSetImmediate(G1CollectedHeap* g1) :
+    _g1(g1), _g1_rem_set(g1->g1_rem_set()) {}
 
   void do_oop(narrowOop* p) {
     guarantee(false, "NYI");
   }
   void do_oop(oop* p) {
     assert(_from->is_in_reserved(p), "paranoia");
-    if (*p != NULL) {
-      _g1_rem_set->write_ref(_from, p);
+    if (*p != NULL && !_from->is_survivor()) {
+      _g1_rem_set->par_write_ref(_from, p, 0);
     }
   }
 };
 
+class UpdateRSetDeferred : public OopsInHeapRegionClosure {
+private:
+  G1CollectedHeap* _g1;
+  DirtyCardQueue *_dcq;
+  CardTableModRefBS* _ct_bs;
+
+public:
+  UpdateRSetDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
+    _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) {}
+
+  void do_oop(narrowOop* p) {
+    guarantee(false, "NYI");
+  }
+  void do_oop(oop* p) {
+    assert(_from->is_in_reserved(p), "paranoia");
+    if (!_from->is_in_reserved(*p) && !_from->is_survivor()) {
+      size_t card_index = _ct_bs->index_for(p);
+      if (_ct_bs->mark_card_deferred(card_index)) {
+        _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
+      }
+    }
+  }
+};
+
+
+
 class RemoveSelfPointerClosure: public ObjectClosure {
 private:
   G1CollectedHeap* _g1;
@@ -2947,11 +3071,11 @@
   HeapRegion* _hr;
   size_t _prev_marked_bytes;
   size_t _next_marked_bytes;
+  OopsInHeapRegionClosure *_cl;
 public:
-  RemoveSelfPointerClosure(G1CollectedHeap* g1, HeapRegion* hr) :
-    _g1(g1), _cm(_g1->concurrent_mark()), _hr(hr),
-    _prev_marked_bytes(0), _next_marked_bytes(0)
-  {}
+  RemoveSelfPointerClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* cl) :
+    _g1(g1), _cm(_g1->concurrent_mark()),  _prev_marked_bytes(0),
+    _next_marked_bytes(0), _cl(cl) {}
 
   size_t prev_marked_bytes() { return _prev_marked_bytes; }
   size_t next_marked_bytes() { return _next_marked_bytes; }
@@ -2989,8 +3113,7 @@
       // that, if evacuation fails, we might have remembered set
       // entries missing given that we skipped cards on the
       // collection set. So, we'll recreate such entries now.
-      RecreateRSetEntriesClosure cl(_g1, _hr);
-      obj->oop_iterate(&cl);
+      obj->oop_iterate(_cl);
       assert(_cm->isPrevMarked(obj), "Should be marked!");
     } else {
       // The object has been either evacuated or is dead. Fill it with a
@@ -3003,14 +3126,23 @@
 };
 
 void G1CollectedHeap::remove_self_forwarding_pointers() {
+  UpdateRSetImmediate immediate_update(_g1h);
+  DirtyCardQueue dcq(&_g1h->dirty_card_queue_set());
+  UpdateRSetDeferred deferred_update(_g1h, &dcq);
+  OopsInHeapRegionClosure *cl;
+  if (G1DeferredRSUpdate) {
+    cl = &deferred_update;
+  } else {
+    cl = &immediate_update;
+  }
   HeapRegion* cur = g1_policy()->collection_set();
-
   while (cur != NULL) {
     assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
 
+    RemoveSelfPointerClosure rspc(_g1h, cl);
     if (cur->evacuation_failed()) {
-      RemoveSelfPointerClosure rspc(_g1h, cur);
       assert(cur->in_collection_set(), "bad CS");
+      cl->set_region(cur);
       cur->object_iterate(&rspc);
 
       // A number of manipulations to make the TAMS be the current top,
@@ -3519,6 +3651,9 @@
 protected:
   G1CollectedHeap* _g1h;
   RefToScanQueue*  _refs;
+  DirtyCardQueue   _dcq;
+  CardTableModRefBS* _ct_bs;
+  G1RemSet* _g1_rem;
 
   typedef GrowableArray<oop*> OverflowQueue;
   OverflowQueue* _overflowed_refs;
@@ -3560,10 +3695,34 @@
 
   void   add_to_undo_waste(size_t waste)         { _undo_waste += waste; }
 
+  DirtyCardQueue& dirty_card_queue()             { return _dcq;  }
+  CardTableModRefBS* ctbs()                      { return _ct_bs; }
+
+  void immediate_rs_update(HeapRegion* from, oop* p, int tid) {
+    if (!from->is_survivor()) {
+      _g1_rem->par_write_ref(from, p, tid);
+    }
+  }
+
+  void deferred_rs_update(HeapRegion* from, oop* p, int tid) {
+    // If the new value of the field points to the same region or
+    // is the to-space, we don't need to include it in the Rset updates.
+    if (!from->is_in_reserved(*p) && !from->is_survivor()) {
+      size_t card_index = ctbs()->index_for(p);
+      // If the card hasn't been added to the buffer, do it.
+      if (ctbs()->mark_card_deferred(card_index)) {
+        dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
+      }
+    }
+  }
+
 public:
   G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
     : _g1h(g1h),
       _refs(g1h->task_queue(queue_num)),
+      _dcq(&g1h->dirty_card_queue_set()),
+      _ct_bs((CardTableModRefBS*)_g1h->barrier_set()),
+      _g1_rem(g1h->g1_rem_set()),
       _hash_seed(17), _queue_num(queue_num),
       _term_attempts(0),
       _age_table(false),
@@ -3641,6 +3800,14 @@
   int refs_to_scan()                             { return refs()->size();                 }
   int overflowed_refs_to_scan()                  { return overflowed_refs()->length();    }
 
+  void update_rs(HeapRegion* from, oop* p, int tid) {
+    if (G1DeferredRSUpdate) {
+      deferred_rs_update(from, p, tid);
+    } else {
+      immediate_rs_update(from, p, tid);
+    }
+  }
+
   HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
 
     HeapWord* obj = NULL;
@@ -3809,7 +3976,6 @@
   }
 };
 
-
 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
   _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
   _par_scan_state(par_scan_state) { }
@@ -3835,7 +4001,7 @@
       assert(obj == *p, "the value of *p should not have changed");
       _par_scan_state->push_on_queue(p);
     } else {
-      _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
+      _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
     }
   }
 }
@@ -3973,13 +4139,13 @@
     }
     // When scanning the RS, we only care about objs in CS.
     if (barrier == G1BarrierRS) {
-      _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
+      _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
     }
   }
 
   // When scanning moved objs, must look at all oops.
   if (barrier == G1BarrierEvac && obj != NULL) {
-    _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
+    _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
   }
 
   if (do_gen_barrier && obj != NULL) {
@@ -4128,6 +4294,7 @@
     G1ParScanExtRootClosure         only_scan_root_cl(_g1h, &pss);
     G1ParScanPermClosure            only_scan_perm_cl(_g1h, &pss);
     G1ParScanHeapRSClosure          only_scan_heap_rs_cl(_g1h, &pss);
+
     G1ParScanAndMarkExtRootClosure  scan_mark_root_cl(_g1h, &pss);
     G1ParScanAndMarkPermClosure     scan_mark_perm_cl(_g1h, &pss);
     G1ParScanAndMarkHeapRSClosure   scan_mark_heap_rs_cl(_g1h, &pss);
@@ -4383,7 +4550,6 @@
   g1_rem_set()->prepare_for_oops_into_collection_set_do();
   concurrent_g1_refine()->set_use_cache(false);
   int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
-
   set_par_threads(n_workers);
   G1ParTask g1_par_task(this, n_workers, _task_queues);
 
@@ -4391,8 +4557,9 @@
 
   change_strong_roots_parity();  // In preparation for parallel strong roots.
   rem_set()->prepare_for_younger_refs_iterate(true);
+
+  assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
   double start_par = os::elapsedTime();
-
   if (ParallelGCThreads > 0) {
     // The individual threads will set their evac-failure closures.
     workers()->run_task(&g1_par_task);
@@ -4412,8 +4579,8 @@
     G1KeepAliveClosure keep_alive(this);
     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
   }
-
   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
+
   concurrent_g1_refine()->set_use_cache(true);
 
   finalize_for_evac_failure();
@@ -4424,7 +4591,6 @@
 
   if (evacuation_failed()) {
     remove_self_forwarding_pointers();
-
     if (PrintGCDetails) {
       gclog_or_tty->print(" (evacuation failed)");
     } else if (PrintGC) {
@@ -4432,6 +4598,14 @@
     }
   }
 
+  if (G1DeferredRSUpdate) {
+    RedirtyLoggedCardTableEntryFastClosure redirty;
+    dirty_card_queue_set().set_closure(&redirty);
+    dirty_card_queue_set().apply_closure_to_all_completed_buffers();
+    JavaThread::dirty_card_queue_set().merge_bufferlists(&dirty_card_queue_set());
+    assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
+  }
+
   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 }
 
@@ -4468,7 +4642,6 @@
                                   size_t& freed_regions,
                                   UncleanRegionList* list,
                                   bool par) {
-  assert(!hr->popular(), "should not free popular regions");
   pre_used += hr->used();
   if (hr->isHumongous()) {
     assert(hr->startsHumongous(),
@@ -4552,12 +4725,6 @@
 
 
 void G1CollectedHeap::do_collection_pause_if_appropriate(size_t word_size) {
-  // First do any popular regions.
-  HeapRegion* hr;
-  while ((hr = popular_region_to_evac()) != NULL) {
-    evac_popular_region(hr);
-  }
-  // Now do heuristic pauses.
   if (g1_policy()->should_do_collection_pause(word_size)) {
     do_collection_pause();
   }
@@ -4953,7 +5120,7 @@
 public:
   RegionCounter() : _n(0) {}
   bool doHeapRegion(HeapRegion* r) {
-    if (r->is_empty() && !r->popular()) {
+    if (r->is_empty()) {
       assert(!r->isHumongous(), "H regions should not be empty.");
       _n++;
     }
@@ -5097,14 +5264,8 @@
       r->set_zero_fill_allocated();
     } else {
       assert(r->is_empty(), "tautology");
-      if (r->popular()) {
-        if (r->zero_fill_state() != HeapRegion::Allocated) {
-          r->ensure_zero_filled_locked();
-          r->set_zero_fill_allocated();
-        }
-      } else {
-        _n++;
-        switch (r->zero_fill_state()) {
+      _n++;
+      switch (r->zero_fill_state()) {
         case HeapRegion::NotZeroFilled:
         case HeapRegion::ZeroFilling:
           _g1->put_region_on_unclean_list_locked(r);
@@ -5115,7 +5276,6 @@
         case HeapRegion::ZeroFilled:
           _g1->put_free_region_on_list_locked(r);
           break;
-        }
       }
     }
     return false;
@@ -5163,376 +5323,6 @@
   heap_region_iterate(&rs);
 }
 
-class CountObjClosure: public ObjectClosure {
-  size_t _n;
-public:
-  CountObjClosure() : _n(0) {}
-  void do_object(oop obj) { _n++; }
-  size_t n() { return _n; }
-};
-
-size_t G1CollectedHeap::pop_object_used_objs() {
-  size_t sum_objs = 0;
-  for (int i = 0; i < G1NumPopularRegions; i++) {
-    CountObjClosure cl;
-    _hrs->at(i)->object_iterate(&cl);
-    sum_objs += cl.n();
-  }
-  return sum_objs;
-}
-
-size_t G1CollectedHeap::pop_object_used_bytes() {
-  size_t sum_bytes = 0;
-  for (int i = 0; i < G1NumPopularRegions; i++) {
-    sum_bytes += _hrs->at(i)->used();
-  }
-  return sum_bytes;
-}
-
-
-static int nq = 0;
-
-HeapWord* G1CollectedHeap::allocate_popular_object(size_t word_size) {
-  while (_cur_pop_hr_index < G1NumPopularRegions) {
-    HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
-    HeapWord* res = cur_pop_region->allocate(word_size);
-    if (res != NULL) {
-      // We account for popular objs directly in the used summary:
-      _summary_bytes_used += (word_size * HeapWordSize);
-      return res;
-    }
-    // Otherwise, try the next region (first making sure that we remember
-    // the last "top" value as the "next_top_at_mark_start", so that
-    // objects made popular during markings aren't automatically considered
-    // live).
-    cur_pop_region->note_end_of_copying();
-    // Otherwise, try the next region.
-    _cur_pop_hr_index++;
-  }
-  // XXX: For now !!!
-  vm_exit_out_of_memory(word_size,
-                        "Not enough pop obj space (To Be Fixed)");
-  return NULL;
-}
-
-class HeapRegionList: public CHeapObj {
-  public:
-  HeapRegion* hr;
-  HeapRegionList* next;
-};
-
-void G1CollectedHeap::schedule_popular_region_evac(HeapRegion* r) {
-  // This might happen during parallel GC, so protect by this lock.
-  MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
-  // We don't schedule regions whose evacuations are already pending, or
-  // are already being evacuated.
-  if (!r->popular_pending() && !r->in_collection_set()) {
-    r->set_popular_pending(true);
-    if (G1TracePopularity) {
-      gclog_or_tty->print_cr("Scheduling region "PTR_FORMAT" "
-                             "["PTR_FORMAT", "PTR_FORMAT") for pop-object evacuation.",
-                             r, r->bottom(), r->end());
-    }
-    HeapRegionList* hrl = new HeapRegionList;
-    hrl->hr = r;
-    hrl->next = _popular_regions_to_be_evacuated;
-    _popular_regions_to_be_evacuated = hrl;
-  }
-}
-
-HeapRegion* G1CollectedHeap::popular_region_to_evac() {
-  MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
-  HeapRegion* res = NULL;
-  while (_popular_regions_to_be_evacuated != NULL && res == NULL) {
-    HeapRegionList* hrl = _popular_regions_to_be_evacuated;
-    _popular_regions_to_be_evacuated = hrl->next;
-    res = hrl->hr;
-    // The G1RSPopLimit may have increased, so recheck here...
-    if (res->rem_set()->occupied() < (size_t) G1RSPopLimit) {
-      // Hah: don't need to schedule.
-      if (G1TracePopularity) {
-        gclog_or_tty->print_cr("Unscheduling region "PTR_FORMAT" "
-                               "["PTR_FORMAT", "PTR_FORMAT") "
-                               "for pop-object evacuation (size %d < limit %d)",
-                               res, res->bottom(), res->end(),
-                               res->rem_set()->occupied(), G1RSPopLimit);
-      }
-      res->set_popular_pending(false);
-      res = NULL;
-    }
-    // We do not reset res->popular() here; if we did so, it would allow
-    // the region to be "rescheduled" for popularity evacuation.  Instead,
-    // this is done in the collection pause, with the world stopped.
-    // So the invariant is that the regions in the list have the popularity
-    // boolean set, but having the boolean set does not imply membership
-    // on the list (though there can at most one such pop-pending region
-    // not on the list at any time).
-    delete hrl;
-  }
-  return res;
-}
-
-void G1CollectedHeap::evac_popular_region(HeapRegion* hr) {
-  while (true) {
-    // Don't want to do a GC pause while cleanup is being completed!
-    wait_for_cleanup_complete();
-
-    // Read the GC count while holding the Heap_lock
-    int gc_count_before = SharedHeap::heap()->total_collections();
-    g1_policy()->record_stop_world_start();
-
-    {
-      MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
-      VM_G1PopRegionCollectionPause op(gc_count_before, hr);
-      VMThread::execute(&op);
-
-      // If the prolog succeeded, we didn't do a GC for this.
-      if (op.prologue_succeeded()) break;
-    }
-    // Otherwise we didn't.  We should recheck the size, though, since
-    // the limit may have increased...
-    if (hr->rem_set()->occupied() < (size_t) G1RSPopLimit) {
-      hr->set_popular_pending(false);
-      break;
-    }
-  }
-}
-
-void G1CollectedHeap::atomic_inc_obj_rc(oop obj) {
-  Atomic::inc(obj_rc_addr(obj));
-}
-
-class CountRCClosure: public OopsInHeapRegionClosure {
-  G1CollectedHeap* _g1h;
-  bool _parallel;
-public:
-  CountRCClosure(G1CollectedHeap* g1h) :
-    _g1h(g1h), _parallel(ParallelGCThreads > 0)
-  {}
-  void do_oop(narrowOop* p) {
-    guarantee(false, "NYI");
-  }
-  void do_oop(oop* p) {
-    oop obj = *p;
-    assert(obj != NULL, "Precondition.");
-    if (_parallel) {
-      // We go sticky at the limit to avoid excess contention.
-      // If we want to track the actual RC's further, we'll need to keep a
-      // per-thread hash table or something for the popular objects.
-      if (_g1h->obj_rc(obj) < G1ObjPopLimit) {
-        _g1h->atomic_inc_obj_rc(obj);
-      }
-    } else {
-      _g1h->inc_obj_rc(obj);
-    }
-  }
-};
-
-class EvacPopObjClosure: public ObjectClosure {
-  G1CollectedHeap* _g1h;
-  size_t _pop_objs;
-  size_t _max_rc;
-public:
-  EvacPopObjClosure(G1CollectedHeap* g1h) :
-    _g1h(g1h), _pop_objs(0), _max_rc(0) {}
-
-  void do_object(oop obj) {
-    size_t rc = _g1h->obj_rc(obj);
-    _max_rc = MAX2(rc, _max_rc);
-    if (rc >= (size_t) G1ObjPopLimit) {
-      _g1h->_pop_obj_rc_at_copy.add((double)rc);
-      size_t word_sz = obj->size();
-      HeapWord* new_pop_loc = _g1h->allocate_popular_object(word_sz);
-      oop new_pop_obj = (oop)new_pop_loc;
-      Copy::aligned_disjoint_words((HeapWord*)obj, new_pop_loc, word_sz);
-      obj->forward_to(new_pop_obj);
-      G1ScanAndBalanceClosure scan_and_balance(_g1h);
-      new_pop_obj->oop_iterate_backwards(&scan_and_balance);
-      // preserve "next" mark bit if marking is in progress.
-      if (_g1h->mark_in_progress() && !_g1h->is_obj_ill(obj)) {
-        _g1h->concurrent_mark()->markAndGrayObjectIfNecessary(new_pop_obj);
-      }
-
-      if (G1TracePopularity) {
-        gclog_or_tty->print_cr("Found obj " PTR_FORMAT " of word size " SIZE_FORMAT
-                               " pop (%d), move to " PTR_FORMAT,
-                               (void*) obj, word_sz,
-                               _g1h->obj_rc(obj), (void*) new_pop_obj);
-      }
-      _pop_objs++;
-    }
-  }
-  size_t pop_objs() { return _pop_objs; }
-  size_t max_rc() { return _max_rc; }
-};
-
-class G1ParCountRCTask : public AbstractGangTask {
-  G1CollectedHeap* _g1h;
-  BitMap _bm;
-
-  size_t getNCards() {
-    return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
-      / G1BlockOffsetSharedArray::N_bytes;
-  }
-  CountRCClosure _count_rc_closure;
-public:
-  G1ParCountRCTask(G1CollectedHeap* g1h) :
-    AbstractGangTask("G1 Par RC Count task"),
-    _g1h(g1h), _bm(getNCards()), _count_rc_closure(g1h)
-  {}
-
-  void work(int i) {
-    ResourceMark rm;
-    HandleMark   hm;
-    _g1h->g1_rem_set()->oops_into_collection_set_do(&_count_rc_closure, i);
-  }
-};
-
-void G1CollectedHeap::popularity_pause_preamble(HeapRegion* popular_region) {
-  // We're evacuating a single region (for popularity).
-  if (G1TracePopularity) {
-    gclog_or_tty->print_cr("Doing pop region pause for ["PTR_FORMAT", "PTR_FORMAT")",
-                           popular_region->bottom(), popular_region->end());
-  }
-  g1_policy()->set_single_region_collection_set(popular_region);
-  size_t max_rc;
-  if (!compute_reference_counts_and_evac_popular(popular_region,
-                                                 &max_rc)) {
-    // We didn't evacuate any popular objects.
-    // We increase the RS popularity limit, to prevent this from
-    // happening in the future.
-    if (G1RSPopLimit < (1 << 30)) {
-      G1RSPopLimit *= 2;
-    }
-    // For now, interesting enough for a message:
-#if 1
-    gclog_or_tty->print_cr("In pop region pause for ["PTR_FORMAT", "PTR_FORMAT"), "
-                           "failed to find a pop object (max = %d).",
-                           popular_region->bottom(), popular_region->end(),
-                           max_rc);
-    gclog_or_tty->print_cr("Increased G1RSPopLimit to %d.", G1RSPopLimit);
-#endif // 0
-    // Also, we reset the collection set to NULL, to make the rest of
-    // the collection do nothing.
-    assert(popular_region->next_in_collection_set() == NULL,
-           "should be single-region.");
-    popular_region->set_in_collection_set(false);
-    popular_region->set_popular_pending(false);
-    g1_policy()->clear_collection_set();
-  }
-}
-
-bool G1CollectedHeap::
-compute_reference_counts_and_evac_popular(HeapRegion* popular_region,
-                                          size_t* max_rc) {
-  HeapWord* rc_region_bot;
-  HeapWord* rc_region_end;
-
-  // Set up the reference count region.
-  HeapRegion* rc_region = newAllocRegion(HeapRegion::GrainWords);
-  if (rc_region != NULL) {
-    rc_region_bot = rc_region->bottom();
-    rc_region_end = rc_region->end();
-  } else {
-    rc_region_bot = NEW_C_HEAP_ARRAY(HeapWord, HeapRegion::GrainWords);
-    if (rc_region_bot == NULL) {
-      vm_exit_out_of_memory(HeapRegion::GrainWords,
-                            "No space for RC region.");
-    }
-    rc_region_end = rc_region_bot + HeapRegion::GrainWords;
-  }
-
-  if (G1TracePopularity)
-    gclog_or_tty->print_cr("RC region is ["PTR_FORMAT", "PTR_FORMAT")",
-                           rc_region_bot, rc_region_end);
-  if (rc_region_bot > popular_region->bottom()) {
-    _rc_region_above = true;
-    _rc_region_diff =
-      pointer_delta(rc_region_bot, popular_region->bottom(), 1);
-  } else {
-    assert(rc_region_bot < popular_region->bottom(), "Can't be equal.");
-    _rc_region_above = false;
-    _rc_region_diff =
-      pointer_delta(popular_region->bottom(), rc_region_bot, 1);
-  }
-  g1_policy()->record_pop_compute_rc_start();
-  // Count external references.
-  g1_rem_set()->prepare_for_oops_into_collection_set_do();
-  if (ParallelGCThreads > 0) {
-
-    set_par_threads(workers()->total_workers());
-    G1ParCountRCTask par_count_rc_task(this);
-    workers()->run_task(&par_count_rc_task);
-    set_par_threads(0);
-
-  } else {
-    CountRCClosure count_rc_closure(this);
-    g1_rem_set()->oops_into_collection_set_do(&count_rc_closure, 0);
-  }
-  g1_rem_set()->cleanup_after_oops_into_collection_set_do();
-  g1_policy()->record_pop_compute_rc_end();
-
-  // Now evacuate popular objects.
-  g1_policy()->record_pop_evac_start();
-  EvacPopObjClosure evac_pop_obj_cl(this);
-  popular_region->object_iterate(&evac_pop_obj_cl);
-  *max_rc = evac_pop_obj_cl.max_rc();
-
-  // Make sure the last "top" value of the current popular region is copied
-  // as the "next_top_at_mark_start", so that objects made popular during
-  // markings aren't automatically considered live.
-  HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
-  cur_pop_region->note_end_of_copying();
-
-  if (rc_region != NULL) {
-    free_region(rc_region);
-  } else {
-    FREE_C_HEAP_ARRAY(HeapWord, rc_region_bot);
-  }
-  g1_policy()->record_pop_evac_end();
-
-  return evac_pop_obj_cl.pop_objs() > 0;
-}
-
-class CountPopObjInfoClosure: public HeapRegionClosure {
-  size_t _objs;
-  size_t _bytes;
-
-  class CountObjClosure: public ObjectClosure {
-    int _n;
-  public:
-    CountObjClosure() : _n(0) {}
-    void do_object(oop obj) { _n++; }
-    size_t n() { return _n; }
-  };
-
-public:
-  CountPopObjInfoClosure() : _objs(0), _bytes(0) {}
-  bool doHeapRegion(HeapRegion* r) {
-    _bytes += r->used();
-    CountObjClosure blk;
-    r->object_iterate(&blk);
-    _objs += blk.n();
-    return false;
-  }
-  size_t objs() { return _objs; }
-  size_t bytes() { return _bytes; }
-};
-
-
-void G1CollectedHeap::print_popularity_summary_info() const {
-  CountPopObjInfoClosure blk;
-  for (int i = 0; i <= _cur_pop_hr_index; i++) {
-    blk.doHeapRegion(_hrs->at(i));
-  }
-  gclog_or_tty->print_cr("\nPopular objects: %d objs, %d bytes.",
-                         blk.objs(), blk.bytes());
-  gclog_or_tty->print_cr("   RC at copy = [avg = %5.2f, max = %5.2f, sd = %5.2f].",
-                _pop_obj_rc_at_copy.avg(),
-                _pop_obj_rc_at_copy.maximum(),
-                _pop_obj_rc_at_copy.sd());
-}
-
 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
   _refine_cte_cl->set_concurrent(concurrent);
 }
@@ -5606,7 +5396,6 @@
 }
 
 bool G1CollectedHeap::print_region_accounting_info() {
-  gclog_or_tty->print_cr("P regions: %d.", G1NumPopularRegions);
   gclog_or_tty->print_cr("Free regions: %d (count: %d count list %d) (clean: %d unclean: %d).",
                          free_regions(),
                          count_free_regions(), count_free_regions_list(),
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,6 @@
 
 class HeapRegion;
 class HeapRegionSeq;
-class HeapRegionList;
 class PermanentGenerationSpec;
 class GenerationSpec;
 class OopsInHeapRegionClosure;
@@ -143,7 +142,6 @@
   friend class VM_GenCollectForPermanentAllocation;
   friend class VM_G1CollectFull;
   friend class VM_G1IncCollectionPause;
-  friend class VM_G1PopRegionCollectionPause;
   friend class VMStructs;
 
   // Closures used in implementation.
@@ -172,7 +170,6 @@
     NumAPIs = HeapRegion::MaxAge
   };
 
-
   // The one and only G1CollectedHeap, so static functions can find it.
   static G1CollectedHeap* _g1h;
 
@@ -217,11 +214,20 @@
 
   // Postcondition: cur_alloc_region == NULL.
   void abandon_cur_alloc_region();
+  void abandon_gc_alloc_regions();
 
   // The to-space memory regions into which objects are being copied during
   // a GC.
   HeapRegion* _gc_alloc_regions[GCAllocPurposeCount];
   size_t _gc_alloc_region_counts[GCAllocPurposeCount];
+  // These are the regions, one per GCAllocPurpose, that are half-full
+  // at the end of a collection and that we want to reuse during the
+  // next collection.
+  HeapRegion* _retained_gc_alloc_regions[GCAllocPurposeCount];
+  // This specifies whether we will keep the last half-full region at
+  // the end of a collection so that it can be reused during the next
+  // collection (this is specified per GCAllocPurpose)
+  bool _retain_gc_alloc_region[GCAllocPurposeCount];
 
   // A list of the regions that have been set to be alloc regions in the
   // current collection.
@@ -245,10 +251,6 @@
   // than the current allocation region.
   size_t _summary_bytes_used;
 
-  // Summary information about popular objects; method to print it.
-  NumberSeq _pop_obj_rc_at_copy;
-  void print_popularity_summary_info() const;
-
   // This is used for a quick test on whether a reference points into
   // the collection set or not. Basically, we have an array, with one
   // byte per region, and that byte denotes whether the corresponding
@@ -439,10 +441,8 @@
   virtual void do_collection_pause();
 
   // The guts of the incremental collection pause, executed by the vm
-  // thread.  If "popular_region" is non-NULL, this pause should evacuate
-  // this single region whose remembered set has gotten large, moving
-  // any popular objects to one of the popular regions.
-  virtual void do_collection_pause_at_safepoint(HeapRegion* popular_region);
+  // thread.
+  virtual void do_collection_pause_at_safepoint();
 
   // Actually do the work of evacuating the collection set.
   virtual void evacuate_collection_set();
@@ -457,6 +457,10 @@
   // And it's mod ref barrier set, used to track updates for the above.
   ModRefBarrierSet* _mr_bs;
 
+  // A set of cards that cover the objects for which the Rsets should be updated
+  // concurrently after the collection.
+  DirtyCardQueueSet _dirty_card_queue_set;
+
   // The Heap Region Rem Set Iterator.
   HeapRegionRemSetIterator** _rem_set_iterator;
 
@@ -585,8 +589,21 @@
 
   // Ensure that the relevant gc_alloc regions are set.
   void get_gc_alloc_regions();
-  // We're done with GC alloc regions; release them, as appropriate.
-  void release_gc_alloc_regions();
+  // We're done with GC alloc regions. We are going to tear down the
+  // gc alloc list and remove the gc alloc tag from all the regions on
+  // that list. However, we will also retain the last (i.e., the one
+  // that is half-full) GC alloc region, per GCAllocPurpose, for
+  // possible reuse during the next collection, provided
+  // _retain_gc_alloc_region[] indicates that it should be the
+  // case. Said regions are kept in the _retained_gc_alloc_regions[]
+  // array. If the parameter totally is set, we will not retain any
+  // regions, irrespective of what _retain_gc_alloc_region[]
+  // indicates.
+  void release_gc_alloc_regions(bool totally);
+#ifndef PRODUCT
+  // Useful for debugging.
+  void print_gc_alloc_regions();
+#endif // !PRODUCT
 
   // ("Weak") Reference processing support
   ReferenceProcessor* _ref_processor;
@@ -600,72 +617,18 @@
 
   SubTasksDone* _process_strong_tasks;
 
-  // Allocate space to hold a popular object.  Result is guaranteed below
-  // "popular_object_boundary()".  Note: CURRENTLY halts the system if we
-  // run out of space to hold popular objects.
-  HeapWord* allocate_popular_object(size_t word_size);
-
-  // The boundary between popular and non-popular objects.
-  HeapWord* _popular_object_boundary;
-
-  HeapRegionList* _popular_regions_to_be_evacuated;
-
-  // Compute which objects in "single_region" are popular.  If any are,
-  // evacuate them to a popular region, leaving behind forwarding pointers,
-  // and select "popular_region" as the single collection set region.
-  // Otherwise, leave the collection set null.
-  void popularity_pause_preamble(HeapRegion* populer_region);
-
-  // Compute which objects in "single_region" are popular, and evacuate
-  // them to a popular region, leaving behind forwarding pointers.
-  // Returns "true" if at least one popular object is discovered and
-  // evacuated.  In any case, "*max_rc" is set to the maximum reference
-  // count of an object in the region.
-  bool compute_reference_counts_and_evac_popular(HeapRegion* populer_region,
-                                                 size_t* max_rc);
-  // Subroutines used in the above.
-  bool _rc_region_above;
-  size_t _rc_region_diff;
-  jint* obj_rc_addr(oop obj) {
-    uintptr_t obj_addr = (uintptr_t)obj;
-    if (_rc_region_above) {
-      jint* res = (jint*)(obj_addr + _rc_region_diff);
-      assert((uintptr_t)res > obj_addr, "RC region is above.");
-      return res;
-    } else {
-      jint* res = (jint*)(obj_addr - _rc_region_diff);
-      assert((uintptr_t)res < obj_addr, "RC region is below.");
-      return res;
-    }
-  }
-  jint obj_rc(oop obj) {
-    return *obj_rc_addr(obj);
-  }
-  void inc_obj_rc(oop obj) {
-    (*obj_rc_addr(obj))++;
-  }
-  void atomic_inc_obj_rc(oop obj);
-
-
-  // Number of popular objects and bytes (latter is cheaper!).
-  size_t pop_object_used_objs();
-  size_t pop_object_used_bytes();
-
-  // Index of the popular region in which allocation is currently being
-  // done.
-  int _cur_pop_hr_index;
-
   // List of regions which require zero filling.
   UncleanRegionList _unclean_region_list;
   bool _unclean_regions_coming;
 
-  bool check_age_cohort_well_formed_work(int a, HeapRegion* hr);
-
 public:
   void set_refine_cte_cl_concurrency(bool concurrent);
 
   RefToScanQueue *task_queue(int i);
 
+  // A set of cards where updates happened during the GC
+  DirtyCardQueueSet& dirty_card_queue_set() { return _dirty_card_queue_set; }
+
   // Create a G1CollectedHeap with the specified policy.
   // Must call the initialize method afterwards.
   // May not return if something goes wrong.
@@ -902,14 +865,25 @@
 
   // Iterate over all the ref-containing fields of all objects, calling
   // "cl.do_oop" on each.
-  virtual void oop_iterate(OopClosure* cl);
+  virtual void oop_iterate(OopClosure* cl) {
+    oop_iterate(cl, true);
+  }
+  void oop_iterate(OopClosure* cl, bool do_perm);
 
   // Same as above, restricted to a memory region.
-  virtual void oop_iterate(MemRegion mr, OopClosure* cl);
+  virtual void oop_iterate(MemRegion mr, OopClosure* cl) {
+    oop_iterate(mr, cl, true);
+  }
+  void oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm);
 
   // Iterate over all objects, calling "cl.do_object" on each.
-  virtual void object_iterate(ObjectClosure* cl);
-  virtual void safe_object_iterate(ObjectClosure* cl) { object_iterate(cl); }
+  virtual void object_iterate(ObjectClosure* cl) {
+    object_iterate(cl, true);
+  }
+  virtual void safe_object_iterate(ObjectClosure* cl) {
+    object_iterate(cl, true);
+  }
+  void object_iterate(ObjectClosure* cl, bool do_perm);
 
   // Iterate over all objects allocated since the last collection, calling
   // "cl.do_object" on each.  The heap must have been initialized properly
@@ -1038,21 +1012,6 @@
   // words.
   virtual size_t large_typearray_limit();
 
-  // All popular objects are guaranteed to have addresses below this
-  // boundary.
-  HeapWord* popular_object_boundary() {
-    return _popular_object_boundary;
-  }
-
-  // Declare the region as one that should be evacuated because its
-  // remembered set is too large.
-  void schedule_popular_region_evac(HeapRegion* r);
-  // If there is a popular region to evacuate it, remove it from the list
-  // and return it.
-  HeapRegion* popular_region_to_evac();
-  // Evacuate the given popular region.
-  void evac_popular_region(HeapRegion* r);
-
   // Returns "true" iff the given word_size is "very large".
   static bool isHumongous(size_t word_size) {
     return word_size >= VeryLargeInWords;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -91,10 +91,8 @@
 
   _all_mod_union_times_ms(new NumberSeq()),
 
-  _non_pop_summary(new NonPopSummary()),
-  _pop_summary(new PopSummary()),
-  _non_pop_abandoned_summary(new NonPopAbandonedSummary()),
-  _pop_abandoned_summary(new PopAbandonedSummary()),
+  _summary(new Summary()),
+  _abandoned_summary(new AbandonedSummary()),
 
   _cur_clear_ct_time_ms(0.0),
 
@@ -109,9 +107,6 @@
   _cur_aux_times_ms(new double[_aux_num]),
   _cur_aux_times_set(new bool[_aux_num]),
 
-  _pop_compute_rc_start(0.0),
-  _pop_evac_start(0.0),
-
   _concurrent_mark_init_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
@@ -224,16 +219,6 @@
 
   _par_last_termination_times_ms = new double[_parallel_gc_threads];
 
-  // we store the data from the first pass during popularity pauses
-  _pop_par_last_update_rs_start_times_ms = new double[_parallel_gc_threads];
-  _pop_par_last_update_rs_times_ms = new double[_parallel_gc_threads];
-  _pop_par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
-
-  _pop_par_last_scan_rs_start_times_ms = new double[_parallel_gc_threads];
-  _pop_par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
-
-  _pop_par_last_closure_app_times_ms = new double[_parallel_gc_threads];
-
   // start conservatively
   _expensive_region_limit_ms = 0.5 * (double) G1MaxPauseTimeMS;
 
@@ -1014,7 +999,7 @@
 
   _all_full_gc_times_ms->add(full_gc_time_ms);
 
-  update_recent_gc_times(end_sec, full_gc_time_sec);
+  update_recent_gc_times(end_sec, full_gc_time_ms);
 
   _g1->clear_full_collection();
 
@@ -1047,23 +1032,6 @@
   calculate_young_list_target_config();
  }
 
-void G1CollectorPolicy::record_pop_compute_rc_start() {
-  _pop_compute_rc_start = os::elapsedTime();
-}
-void G1CollectorPolicy::record_pop_compute_rc_end() {
-  double ms = (os::elapsedTime() - _pop_compute_rc_start)*1000.0;
-  _cur_popular_compute_rc_time_ms = ms;
-  _pop_compute_rc_start = 0.0;
-}
-void G1CollectorPolicy::record_pop_evac_start() {
-  _pop_evac_start = os::elapsedTime();
-}
-void G1CollectorPolicy::record_pop_evac_end() {
-  double ms = (os::elapsedTime() - _pop_evac_start)*1000.0;
-  _cur_popular_evac_time_ms = ms;
-  _pop_evac_start = 0.0;
-}
-
 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
   _bytes_in_to_space_before_gc += bytes;
 }
@@ -1087,6 +1055,7 @@
 
   assert(_g1->used_regions() == _g1->recalculate_used_regions(),
          "sanity");
+  assert(_g1->used() == _g1->recalculate_used(), "sanity");
 
   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
   _all_stop_world_times_ms->add(s_w_t_ms);
@@ -1119,13 +1088,6 @@
     _par_last_scan_new_refs_times_ms[i] = -666.0;
     _par_last_obj_copy_times_ms[i] = -666.0;
     _par_last_termination_times_ms[i] = -666.0;
-
-    _pop_par_last_update_rs_start_times_ms[i] = -666.0;
-    _pop_par_last_update_rs_times_ms[i] = -666.0;
-    _pop_par_last_update_rs_processed_buffers[i] = -666.0;
-    _pop_par_last_scan_rs_start_times_ms[i] = -666.0;
-    _pop_par_last_scan_rs_times_ms[i] = -666.0;
-    _pop_par_last_closure_app_times_ms[i] = -666.0;
   }
 #endif
 
@@ -1184,25 +1146,6 @@
   guarantee( false, "we should never reach here" );
 }
 
-void G1CollectorPolicy::record_popular_pause_preamble_start() {
-  _cur_popular_preamble_start_ms = os::elapsedTime() * 1000.0;
-}
-
-void G1CollectorPolicy::record_popular_pause_preamble_end() {
-  _cur_popular_preamble_time_ms =
-    (os::elapsedTime() * 1000.0) - _cur_popular_preamble_start_ms;
-
-  // copy the recorded statistics of the first pass to temporary arrays
-  for (int i = 0; i < _parallel_gc_threads; ++i) {
-    _pop_par_last_update_rs_start_times_ms[i] = _par_last_update_rs_start_times_ms[i];
-    _pop_par_last_update_rs_times_ms[i] = _par_last_update_rs_times_ms[i];
-    _pop_par_last_update_rs_processed_buffers[i] = _par_last_update_rs_processed_buffers[i];
-    _pop_par_last_scan_rs_start_times_ms[i] = _par_last_scan_rs_start_times_ms[i];
-    _pop_par_last_scan_rs_times_ms[i] = _par_last_scan_rs_times_ms[i];
-    _pop_par_last_closure_app_times_ms[i] = _par_last_obj_copy_times_ms[i];
-  }
-}
-
 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
   _mark_closure_time_ms = mark_closure_time_ms;
 }
@@ -1464,8 +1407,7 @@
 // Anything below that is considered to be zero
 #define MIN_TIMER_GRANULARITY 0.0000001
 
-void G1CollectorPolicy::record_collection_pause_end(bool popular,
-                                                    bool abandoned) {
+void G1CollectorPolicy::record_collection_pause_end(bool abandoned) {
   double end_time_sec = os::elapsedTime();
   double elapsed_ms = _last_pause_time_ms;
   bool parallel = ParallelGCThreads > 0;
@@ -1475,6 +1417,7 @@
   size_t cur_used_bytes = _g1->used();
   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
   bool last_pause_included_initial_mark = false;
+  bool update_stats = !abandoned && !_g1->evacuation_failed();
 
 #ifndef PRODUCT
   if (G1YoungSurvRateVerbose) {
@@ -1535,7 +1478,7 @@
 
   _n_pauses++;
 
-  if (!abandoned) {
+  if (update_stats) {
     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
     _recent_evac_times_ms->add(evac_ms);
@@ -1585,42 +1528,10 @@
   }
 
   PauseSummary* summary;
-  if (!abandoned && !popular)
-    summary = _non_pop_summary;
-  else if (!abandoned && popular)
-    summary = _pop_summary;
-  else if (abandoned && !popular)
-    summary = _non_pop_abandoned_summary;
-  else if (abandoned && popular)
-    summary = _pop_abandoned_summary;
-  else
-    guarantee(false, "should not get here!");
-
-  double pop_update_rs_time;
-  double pop_update_rs_processed_buffers;
-  double pop_scan_rs_time;
-  double pop_closure_app_time;
-  double pop_other_time;
-
-  if (popular) {
-    PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
-    guarantee(preamble_summary != NULL, "should not be null!");
-
-    pop_update_rs_time = avg_value(_pop_par_last_update_rs_times_ms);
-    pop_update_rs_processed_buffers =
-      sum_of_values(_pop_par_last_update_rs_processed_buffers);
-    pop_scan_rs_time = avg_value(_pop_par_last_scan_rs_times_ms);
-    pop_closure_app_time = avg_value(_pop_par_last_closure_app_times_ms);
-    pop_other_time = _cur_popular_preamble_time_ms -
-      (pop_update_rs_time + pop_scan_rs_time + pop_closure_app_time +
-       _cur_popular_evac_time_ms);
-
-    preamble_summary->record_pop_preamble_time_ms(_cur_popular_preamble_time_ms);
-    preamble_summary->record_pop_update_rs_time_ms(pop_update_rs_time);
-    preamble_summary->record_pop_scan_rs_time_ms(pop_scan_rs_time);
-    preamble_summary->record_pop_closure_app_time_ms(pop_closure_app_time);
-    preamble_summary->record_pop_evacuation_time_ms(_cur_popular_evac_time_ms);
-    preamble_summary->record_pop_other_time_ms(pop_other_time);
+  if (abandoned) {
+    summary = _abandoned_summary;
+  } else {
+    summary = _summary;
   }
 
   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
@@ -1635,8 +1546,10 @@
   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
   double termination_time = avg_value(_par_last_termination_times_ms);
 
-  double parallel_other_time;
-  if (!abandoned) {
+  double parallel_other_time = _cur_collection_par_time_ms -
+    (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
+     scan_only_time + scan_rs_time + obj_copy_time + termination_time);
+  if (update_stats) {
     MainBodySummary* body_summary = summary->main_body_summary();
     guarantee(body_summary != NULL, "should not be null!");
 
@@ -1654,9 +1567,6 @@
       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
       body_summary->record_termination_time_ms(termination_time);
-      parallel_other_time = _cur_collection_par_time_ms -
-        (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
-         scan_only_time + scan_rs_time + obj_copy_time + termination_time);
       body_summary->record_parallel_other_time_ms(parallel_other_time);
     }
     body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
@@ -1693,8 +1603,6 @@
   }
 
   double other_time_ms = elapsed_ms;
-  if (popular)
-    other_time_ms -= _cur_popular_preamble_time_ms;
 
   if (!abandoned) {
     if (_satb_drain_time_set)
@@ -1711,41 +1619,24 @@
 
   if (PrintGCDetails) {
     gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
-                           (popular && !abandoned) ? " (popular)" :
-                           (!popular && abandoned) ? " (abandoned)" :
-                           (popular && abandoned) ? " (popular/abandoned)" : "",
+                           abandoned ? " (abandoned)" : "",
                            (last_pause_included_initial_mark) ? " (initial-mark)" : "",
                            elapsed_ms / 1000.0);
 
     if (!abandoned) {
-      if (_satb_drain_time_set)
+      if (_satb_drain_time_set) {
         print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
-      if (_last_satb_drain_processed_buffers >= 0)
+      }
+      if (_last_satb_drain_processed_buffers >= 0) {
         print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
-    }
-    if (popular)
-      print_stats(1, "Popularity Preamble", _cur_popular_preamble_time_ms);
-    if (parallel) {
-      if (popular) {
-        print_par_stats(2, "Update RS (Start)", _pop_par_last_update_rs_start_times_ms, false);
-        print_par_stats(2, "Update RS", _pop_par_last_update_rs_times_ms);
+      }
+      if (parallel) {
+        print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
+        print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
+        print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
         if (G1RSBarrierUseQueue)
           print_par_buffers(3, "Processed Buffers",
-                            _pop_par_last_update_rs_processed_buffers, true);
-        print_par_stats(2, "Scan RS", _pop_par_last_scan_rs_times_ms);
-        print_par_stats(2, "Closure app", _pop_par_last_closure_app_times_ms);
-        print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
-        print_stats(2, "Other", pop_other_time);
-      }
-      if (!abandoned) {
-        print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
-        if (!popular) {
-          print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
-          print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
-          if (G1RSBarrierUseQueue)
-            print_par_buffers(3, "Processed Buffers",
-                              _par_last_update_rs_processed_buffers, true);
-        }
+                            _par_last_update_rs_processed_buffers, true);
         print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
         print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
         print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
@@ -1756,25 +1647,11 @@
         print_par_stats(2, "Termination", _par_last_termination_times_ms);
         print_stats(2, "Other", parallel_other_time);
         print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
-      }
-    } else {
-      if (popular) {
-        print_stats(2, "Update RS", pop_update_rs_time);
+      } else {
+        print_stats(1, "Update RS", update_rs_time);
         if (G1RSBarrierUseQueue)
-          print_stats(3, "Processed Buffers",
-                      (int)pop_update_rs_processed_buffers);
-        print_stats(2, "Scan RS", pop_scan_rs_time);
-        print_stats(2, "Closure App", pop_closure_app_time);
-        print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
-        print_stats(2, "Other", pop_other_time);
-      }
-      if (!abandoned) {
-        if (!popular) {
-          print_stats(1, "Update RS", update_rs_time);
-          if (G1RSBarrierUseQueue)
-            print_stats(2, "Processed Buffers",
-                        (int)update_rs_processed_buffers);
-        }
+          print_stats(2, "Processed Buffers",
+                      (int)update_rs_processed_buffers);
         print_stats(1, "Ext Root Scanning", ext_root_scan_time);
         print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
         print_stats(1, "Scan-Only Scanning", scan_only_time);
@@ -1801,8 +1678,10 @@
     gclog_or_tty->print_cr("]");
 
   _all_pause_times_ms->add(elapsed_ms);
-  summary->record_total_time_ms(elapsed_ms);
-  summary->record_other_time_ms(other_time_ms);
+  if (update_stats) {
+    summary->record_total_time_ms(elapsed_ms);
+    summary->record_other_time_ms(other_time_ms);
+  }
   for (int i = 0; i < _aux_num; ++i)
     if (_cur_aux_times_set[i])
       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
@@ -1852,7 +1731,7 @@
 
   // <NEW PREDICTION>
 
-  if (!popular && !abandoned) {
+  if (update_stats) {
     double pause_time_ms = elapsed_ms;
 
     size_t diff = 0;
@@ -2451,36 +2330,8 @@
 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
   bool parallel = ParallelGCThreads > 0;
   MainBodySummary*    body_summary = summary->main_body_summary();
-  PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
-
   if (summary->get_total_seq()->num() > 0) {
-    print_summary_sd(0,
-                     (preamble_summary == NULL) ? "Non-Popular Pauses" :
-                     "Popular Pauses",
-                     summary->get_total_seq());
-    if (preamble_summary != NULL) {
-      print_summary(1, "Popularity Preamble",
-                    preamble_summary->get_pop_preamble_seq());
-      print_summary(2, "Update RS", preamble_summary->get_pop_update_rs_seq());
-      print_summary(2, "Scan RS", preamble_summary->get_pop_scan_rs_seq());
-      print_summary(2, "Closure App",
-                    preamble_summary->get_pop_closure_app_seq());
-      print_summary(2, "Evacuation",
-                    preamble_summary->get_pop_evacuation_seq());
-      print_summary(2, "Other", preamble_summary->get_pop_other_seq());
-      {
-        NumberSeq* other_parts[] = {
-          preamble_summary->get_pop_update_rs_seq(),
-          preamble_summary->get_pop_scan_rs_seq(),
-          preamble_summary->get_pop_closure_app_seq(),
-          preamble_summary->get_pop_evacuation_seq()
-        };
-        NumberSeq calc_other_times_ms(preamble_summary->get_pop_preamble_seq(),
-                                      4, other_parts);
-        check_other_times(2, preamble_summary->get_pop_other_seq(),
-                          &calc_other_times_ms);
-      }
-    }
+    print_summary_sd(0, "Evacuation Pauses", summary->get_total_seq());
     if (body_summary != NULL) {
       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
       if (parallel) {
@@ -2534,19 +2385,15 @@
           // parallel
           NumberSeq* other_parts[] = {
             body_summary->get_satb_drain_seq(),
-            (preamble_summary == NULL) ? NULL :
-              preamble_summary->get_pop_preamble_seq(),
             body_summary->get_parallel_seq(),
             body_summary->get_clear_ct_seq()
           };
-          calc_other_times_ms = NumberSeq (summary->get_total_seq(),
-                                          4, other_parts);
+          calc_other_times_ms = NumberSeq(summary->get_total_seq(),
+                                          3, other_parts);
         } else {
           // serial
           NumberSeq* other_parts[] = {
             body_summary->get_satb_drain_seq(),
-            (preamble_summary == NULL) ? NULL :
-              preamble_summary->get_pop_preamble_seq(),
             body_summary->get_update_rs_seq(),
             body_summary->get_ext_root_scan_seq(),
             body_summary->get_mark_stack_scan_seq(),
@@ -2555,16 +2402,11 @@
             body_summary->get_obj_copy_seq()
           };
           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
-                                          8, other_parts);
+                                          7, other_parts);
         }
       } else {
         // abandoned
-        NumberSeq* other_parts[] = {
-          (preamble_summary == NULL) ? NULL :
-            preamble_summary->get_pop_preamble_seq()
-        };
-        calc_other_times_ms = NumberSeq(summary->get_total_seq(),
-                                        1, other_parts);
+        calc_other_times_ms = NumberSeq();
       }
       check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
     }
@@ -2576,18 +2418,12 @@
 }
 
 void
-G1CollectorPolicy::print_abandoned_summary(PauseSummary* non_pop_summary,
-                                           PauseSummary* pop_summary) const {
+G1CollectorPolicy::print_abandoned_summary(PauseSummary* summary) const {
   bool printed = false;
-  if (non_pop_summary->get_total_seq()->num() > 0) {
+  if (summary->get_total_seq()->num() > 0) {
     printed = true;
-    print_summary(non_pop_summary);
+    print_summary(summary);
   }
-  if (pop_summary->get_total_seq()->num() > 0) {
-    printed = true;
-    print_summary(pop_summary);
-  }
-
   if (!printed) {
     print_indent(0);
     gclog_or_tty->print_cr("none");
@@ -2605,15 +2441,11 @@
     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
     gclog_or_tty->print_cr("");
 
-    gclog_or_tty->print_cr("NON-POPULAR PAUSES");
-    print_summary(_non_pop_summary);
-
-    gclog_or_tty->print_cr("POPULAR PAUSES");
-    print_summary(_pop_summary);
+    gclog_or_tty->print_cr("EVACUATION PAUSES");
+    print_summary(_summary);
 
     gclog_or_tty->print_cr("ABANDONED PAUSES");
-    print_abandoned_summary(_non_pop_abandoned_summary,
-                            _pop_abandoned_summary);
+    print_abandoned_summary(_abandoned_summary);
 
     gclog_or_tty->print_cr("MISC");
     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
@@ -2699,14 +2531,6 @@
   _conc_refine_enabled++;
 }
 
-void G1CollectorPolicy::set_single_region_collection_set(HeapRegion* hr) {
-  assert(collection_set() == NULL, "Must be no current CS.");
-  _collection_set_size = 0;
-  _collection_set_bytes_used_before = 0;
-  add_to_collection_set(hr);
-  count_CS_bytes_used();
-}
-
 bool
 G1CollectorPolicy::should_add_next_region_to_young_list() {
   assert(in_young_gc_mode(), "should be in young GC mode");
@@ -2784,15 +2608,6 @@
   }
 }
 
-
-void
-G1CollectorPolicy_BestRegionsFirst::
-set_single_region_collection_set(HeapRegion* hr) {
-  G1CollectorPolicy::set_single_region_collection_set(hr);
-  _collectionSetChooser->removeRegion(hr);
-}
-
-
 bool
 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
                                                                word_size) {
@@ -3058,19 +2873,13 @@
 
 void
 G1CollectorPolicy_BestRegionsFirst::
-choose_collection_set(HeapRegion* pop_region) {
+choose_collection_set() {
   double non_young_start_time_sec;
   start_recording_regions();
 
-  if (pop_region != NULL) {
-    _target_pause_time_ms = (double) G1MaxPauseTimeMS;
-  } else {
-    guarantee(_target_pause_time_ms > -1.0,
-              "_target_pause_time_ms should have been set!");
-  }
-
-  // pop region is either null (and so is CS), or else it *is* the CS.
-  assert(_collection_set == pop_region, "Precondition");
+  guarantee(_target_pause_time_ms > -1.0,
+            "_target_pause_time_ms should have been set!");
+  assert(_collection_set == NULL, "Precondition");
 
   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
   double predicted_pause_time_ms = base_time_ms;
@@ -3097,15 +2906,13 @@
   size_t expansion_bytes =
     _g1->expansion_regions() * HeapRegion::GrainBytes;
 
-  if (pop_region == NULL) {
-    _collection_set_bytes_used_before = 0;
-    _collection_set_size = 0;
-  }
+  _collection_set_bytes_used_before = 0;
+  _collection_set_size = 0;
 
   // Adjust for expansion and slop.
   max_live_bytes = max_live_bytes + expansion_bytes;
 
-  assert(pop_region != NULL || _g1->regions_accounted_for(), "Region leakage!");
+  assert(_g1->regions_accounted_for(), "Region leakage!");
 
   HeapRegion* hr;
   if (in_young_gc_mode()) {
@@ -3132,14 +2939,9 @@
       double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
       time_remaining_ms -= predicted_time_ms;
       predicted_pause_time_ms += predicted_time_ms;
-      if (hr == pop_region) {
-        // The popular region was young.  Skip over it.
-        assert(hr->in_collection_set(), "It's the pop region.");
-      } else {
-        assert(!hr->in_collection_set(), "It's not the pop region.");
-        add_to_collection_set(hr);
-        record_cset_region(hr, true);
-      }
+      assert(!hr->in_collection_set(), "invariant");
+      add_to_collection_set(hr);
+      record_cset_region(hr, true);
       max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
       if (G1PolicyVerbose > 0) {
         gclog_or_tty->print_cr("  Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
@@ -3162,10 +2964,6 @@
       // don't bother adding more regions...
       goto choose_collection_set_end;
     }
-  } else if (pop_region != NULL) {
-    // We're not in young mode, and we chose a popular region; don't choose
-    // any more.
-    return;
   }
 
   if (!in_young_gc_mode() || !full_young_gcs()) {
@@ -3175,7 +2973,7 @@
     do {
       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
                                                       avg_prediction);
-      if (hr != NULL && !hr->popular()) {
+      if (hr != NULL) {
         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
         time_remaining_ms -= predicted_time_ms;
         predicted_pause_time_ms += predicted_time_ms;
@@ -3222,8 +3020,8 @@
 }
 
 void G1CollectorPolicy_BestRegionsFirst::
-record_collection_pause_end(bool popular, bool abandoned) {
-  G1CollectorPolicy::record_collection_pause_end(popular, abandoned);
+record_collection_pause_end(bool abandoned) {
+  G1CollectorPolicy::record_collection_pause_end(abandoned);
   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
 }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,6 @@
   }
 
 class MainBodySummary;
-class PopPreambleSummary;
 
 class PauseSummary: public CHeapObj {
   define_num_seq(total)
@@ -55,7 +54,6 @@
 
 public:
   virtual MainBodySummary*    main_body_summary()    { return NULL; }
-  virtual PopPreambleSummary* pop_preamble_summary() { return NULL; }
 };
 
 class MainBodySummary: public CHeapObj {
@@ -75,36 +73,13 @@
   define_num_seq(clear_ct)  // parallel only
 };
 
-class PopPreambleSummary: public CHeapObj {
-  define_num_seq(pop_preamble)
-    define_num_seq(pop_update_rs)
-    define_num_seq(pop_scan_rs)
-    define_num_seq(pop_closure_app)
-    define_num_seq(pop_evacuation)
-    define_num_seq(pop_other)
-};
-
-class NonPopSummary: public PauseSummary,
-                     public MainBodySummary {
+class Summary: public PauseSummary,
+               public MainBodySummary {
 public:
   virtual MainBodySummary*    main_body_summary()    { return this; }
 };
 
-class PopSummary: public PauseSummary,
-                  public MainBodySummary,
-                  public PopPreambleSummary {
-public:
-  virtual MainBodySummary*    main_body_summary()    { return this; }
-  virtual PopPreambleSummary* pop_preamble_summary() { return this; }
-};
-
-class NonPopAbandonedSummary: public PauseSummary {
-};
-
-class PopAbandonedSummary: public PauseSummary,
-                           public PopPreambleSummary {
-public:
-  virtual PopPreambleSummary* pop_preamble_summary() { return this; }
+class AbandonedSummary: public PauseSummary {
 };
 
 class G1CollectorPolicy: public CollectorPolicy {
@@ -146,10 +121,6 @@
   double _cur_satb_drain_time_ms;
   double _cur_clear_ct_time_ms;
   bool   _satb_drain_time_set;
-  double _cur_popular_preamble_start_ms;
-  double _cur_popular_preamble_time_ms;
-  double _cur_popular_compute_rc_time_ms;
-  double _cur_popular_evac_time_ms;
 
   double _cur_CH_strong_roots_end_sec;
   double _cur_CH_strong_roots_dur_ms;
@@ -173,10 +144,8 @@
   TruncatedSeq* _concurrent_mark_remark_times_ms;
   TruncatedSeq* _concurrent_mark_cleanup_times_ms;
 
-  NonPopSummary*           _non_pop_summary;
-  PopSummary*              _pop_summary;
-  NonPopAbandonedSummary*  _non_pop_abandoned_summary;
-  PopAbandonedSummary*     _pop_abandoned_summary;
+  Summary*           _summary;
+  AbandonedSummary*  _abandoned_summary;
 
   NumberSeq* _all_pause_times_ms;
   NumberSeq* _all_full_gc_times_ms;
@@ -210,18 +179,6 @@
   double* _par_last_obj_copy_times_ms;
   double* _par_last_termination_times_ms;
 
-  // there are two pases during popular pauses, so we need to store
-  // somewhere the results of the first pass
-  double* _pop_par_last_update_rs_start_times_ms;
-  double* _pop_par_last_update_rs_times_ms;
-  double* _pop_par_last_update_rs_processed_buffers;
-  double* _pop_par_last_scan_rs_start_times_ms;
-  double* _pop_par_last_scan_rs_times_ms;
-  double* _pop_par_last_closure_app_times_ms;
-
-  double _pop_compute_rc_start;
-  double _pop_evac_start;
-
   // indicates that we are in young GC mode
   bool _in_young_gc_mode;
 
@@ -634,8 +591,7 @@
                          NumberSeq* calc_other_times_ms) const;
 
   void print_summary (PauseSummary* stats) const;
-  void print_abandoned_summary(PauseSummary* non_pop_summary,
-                               PauseSummary* pop_summary) const;
+  void print_abandoned_summary(PauseSummary* summary) const;
 
   void print_summary (int level, const char* str, NumberSeq* seq) const;
   void print_summary_sd (int level, const char* str, NumberSeq* seq) const;
@@ -856,9 +812,6 @@
   virtual void record_collection_pause_start(double start_time_sec,
                                              size_t start_used);
 
-  virtual void record_popular_pause_preamble_start();
-  virtual void record_popular_pause_preamble_end();
-
   // Must currently be called while the world is stopped.
   virtual void record_concurrent_mark_init_start();
   virtual void record_concurrent_mark_init_end();
@@ -881,7 +834,7 @@
   virtual void record_collection_pause_end_CH_strong_roots();
   virtual void record_collection_pause_end_G1_strong_roots();
 
-  virtual void record_collection_pause_end(bool popular, bool abandoned);
+  virtual void record_collection_pause_end(bool abandoned);
 
   // Record the fact that a full collection occurred.
   virtual void record_full_collection_start();
@@ -966,7 +919,7 @@
     record_termination_time(0, ms);
   }
 
-  void record_pause_time(double ms) {
+  void record_pause_time_ms(double ms) {
     _last_pause_time_ms = ms;
   }
 
@@ -990,12 +943,6 @@
     _cur_aux_times_ms[i] += ms;
   }
 
-  void record_pop_compute_rc_start();
-  void record_pop_compute_rc_end();
-
-  void record_pop_evac_start();
-  void record_pop_evac_end();
-
   // Record the fact that "bytes" bytes allocated in a region.
   void record_before_bytes(size_t bytes);
   void record_after_bytes(size_t bytes);
@@ -1008,9 +955,7 @@
   // Choose a new collection set.  Marks the chosen regions as being
   // "in_collection_set", and links them together.  The head and number of
   // the collection set are available via access methods.
-  // If "pop_region" is non-NULL, it is a popular region that has already
-  // been added to the collection set.
-  virtual void choose_collection_set(HeapRegion* pop_region = NULL) = 0;
+  virtual void choose_collection_set() = 0;
 
   void clear_collection_set() { _collection_set = NULL; }
 
@@ -1018,9 +963,6 @@
   // current collection set.
   HeapRegion* collection_set() { return _collection_set; }
 
-  // Sets the collection set to the given single region.
-  virtual void set_single_region_collection_set(HeapRegion* hr);
-
   // The number of elements in the current collection set.
   size_t collection_set_size() { return _collection_set_size; }
 
@@ -1203,7 +1145,7 @@
   // If the estimated is less then desirable, resize if possible.
   void expand_if_possible(size_t numRegions);
 
-  virtual void choose_collection_set(HeapRegion* pop_region = NULL);
+  virtual void choose_collection_set();
   virtual void record_collection_pause_start(double start_time_sec,
                                              size_t start_used);
   virtual void record_concurrent_mark_cleanup_end(size_t freed_bytes,
@@ -1214,9 +1156,8 @@
   G1CollectorPolicy_BestRegionsFirst() {
     _collectionSetChooser = new CollectionSetChooser();
   }
-  void record_collection_pause_end(bool popular, bool abandoned);
+  void record_collection_pause_end(bool abandoned);
   bool should_do_collection_pause(size_t word_size);
-  virtual void set_single_region_collection_set(HeapRegion* hr);
   // This is not needed any more, after the CSet choosing code was
   // changed to use the pause prediction work. But let's leave the
   // hook in just in case.
--- a/hotspot/src/share/vm/gc_implementation/g1/g1MMUTracker.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1MMUTracker.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -157,7 +157,6 @@
 class G1PrepareCompactClosure: public HeapRegionClosure {
   ModRefBarrierSet* _mrbs;
   CompactPoint _cp;
-  bool _popular_only;
 
   void free_humongous_region(HeapRegion* hr) {
     HeapWord* bot = hr->bottom();
@@ -172,17 +171,11 @@
   }
 
 public:
-  G1PrepareCompactClosure(CompactibleSpace* cs, bool popular_only) :
+  G1PrepareCompactClosure(CompactibleSpace* cs) :
     _cp(NULL, cs, cs->initialize_threshold()),
-    _mrbs(G1CollectedHeap::heap()->mr_bs()),
-    _popular_only(popular_only)
+    _mrbs(G1CollectedHeap::heap()->mr_bs())
   {}
   bool doHeapRegion(HeapRegion* hr) {
-    if (_popular_only && !hr->popular())
-      return true; // terminate early
-    else if (!_popular_only && hr->popular())
-      return false; // skip this one.
-
     if (hr->isHumongous()) {
       if (hr->startsHumongous()) {
         oop obj = oop(hr->bottom());
@@ -203,20 +196,15 @@
     return false;
   }
 };
-// Stolen verbatim from g1CollectedHeap.cpp
+
+// Finds the first HeapRegion.
 class FindFirstRegionClosure: public HeapRegionClosure {
   HeapRegion* _a_region;
-  bool _find_popular;
 public:
-  FindFirstRegionClosure(bool find_popular) :
-    _a_region(NULL), _find_popular(find_popular) {}
+  FindFirstRegionClosure() : _a_region(NULL) {}
   bool doHeapRegion(HeapRegion* r) {
-    if (r->popular() == _find_popular) {
-      _a_region = r;
-      return true;
-    } else {
-      return false;
-    }
+    _a_region = r;
+    return true;
   }
   HeapRegion* result() { return _a_region; }
 };
@@ -242,30 +230,15 @@
   TraceTime tm("phase 2", PrintGC && Verbose, true, gclog_or_tty);
   GenMarkSweep::trace("2");
 
-  // First we compact the popular regions.
-  if (G1NumPopularRegions > 0) {
-    CompactibleSpace* sp = g1h->first_compactible_space();
-    FindFirstRegionClosure cl(true /*find_popular*/);
-    g1h->heap_region_iterate(&cl);
-    HeapRegion *r = cl.result();
-    assert(r->popular(), "should have found a popular region.");
-    assert(r == sp, "first popular heap region should "
-                    "== first compactible space");
-    G1PrepareCompactClosure blk(sp, true/*popular_only*/);
-    g1h->heap_region_iterate(&blk);
-  }
-
-  // Now we do the regular regions.
-  FindFirstRegionClosure cl(false /*find_popular*/);
+  FindFirstRegionClosure cl;
   g1h->heap_region_iterate(&cl);
   HeapRegion *r = cl.result();
-  assert(!r->popular(), "should have founda non-popular region.");
   CompactibleSpace* sp = r;
   if (r->isHumongous() && oop(r->bottom())->is_gc_marked()) {
     sp = r->next_compaction_space();
   }
 
-  G1PrepareCompactClosure blk(sp, false/*popular_only*/);
+  G1PrepareCompactClosure blk(sp);
   g1h->heap_region_iterate(&blk);
 
   CompactPoint perm_cp(pg, NULL, NULL);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -105,33 +105,6 @@
   _g1->heap_region_iterate(&rc);
 }
 
-class UpdateRSOopClosure: public OopClosure {
-  HeapRegion* _from;
-  HRInto_G1RemSet* _rs;
-  int _worker_i;
-public:
-  UpdateRSOopClosure(HRInto_G1RemSet* rs, int worker_i = 0) :
-    _from(NULL), _rs(rs), _worker_i(worker_i) {
-    guarantee(_rs != NULL, "Requires an HRIntoG1RemSet");
-  }
-
-  void set_from(HeapRegion* from) {
-    assert(from != NULL, "from region must be non-NULL");
-    _from = from;
-  }
-
-  virtual void do_oop(narrowOop* p) {
-    guarantee(false, "NYI");
-  }
-  virtual void do_oop(oop* p) {
-    assert(_from != NULL, "from region must be non-NULL");
-    _rs->par_write_ref(_from, p, _worker_i);
-  }
-  // Override: this closure is idempotent.
-  //  bool idempotent() { return true; }
-  bool apply_to_weak_ref_discovered_field() { return true; }
-};
-
 class UpdateRSOutOfRegionClosure: public HeapRegionClosure {
   G1CollectedHeap*    _g1h;
   ModRefBarrierSet*   _mr_bs;
@@ -177,11 +150,19 @@
     _cards_scanned(NULL), _total_cards_scanned(0)
 {
   _seq_task = new SubTasksDone(NumSeqTasks);
-  _new_refs = NEW_C_HEAP_ARRAY(GrowableArray<oop*>*, ParallelGCThreads);
+  guarantee(n_workers() > 0, "There should be some workers");
+  _new_refs = NEW_C_HEAP_ARRAY(GrowableArray<oop*>*, n_workers());
+  for (uint i = 0; i < n_workers(); i++) {
+    _new_refs[i] = new (ResourceObj::C_HEAP) GrowableArray<oop*>(8192,true);
+  }
 }
 
 HRInto_G1RemSet::~HRInto_G1RemSet() {
   delete _seq_task;
+  for (uint i = 0; i < n_workers(); i++) {
+    delete _new_refs[i];
+  }
+  FREE_C_HEAP_ARRAY(GrowableArray<oop*>*, _new_refs);
 }
 
 void CountNonCleanMemRegionClosure::do_MemRegion(MemRegion mr) {
@@ -281,8 +262,9 @@
         if (!_ct_bs->is_card_claimed(card_index) &&
             !_ct_bs->is_card_dirty(card_index)) {
           assert(_ct_bs->is_card_clean(card_index) ||
-                 _ct_bs->is_card_claimed(card_index),
-                 "Card is either dirty, clean, or claimed");
+                 _ct_bs->is_card_claimed(card_index) ||
+                 _ct_bs->is_card_deferred(card_index),
+                 "Card is either clean, claimed or deferred");
           if (_ct_bs->claim_card(card_index))
             scanCard(card_index, card_region);
         }
@@ -338,14 +320,12 @@
 
   _g1p->record_scan_rs_start_time(worker_i, rs_time_start * 1000.0);
   _g1p->record_scan_rs_time(worker_i, scan_rs_time_sec * 1000.0);
-  if (ParallelGCThreads > 0) {
-    // In this case, we called scanNewRefsRS and recorded the corresponding
-    // time.
-    double scan_new_refs_time_ms = _g1p->get_scan_new_refs_time(worker_i);
-    if (scan_new_refs_time_ms > 0.0) {
-      closure_app_time_ms += scan_new_refs_time_ms;
-    }
+
+  double scan_new_refs_time_ms = _g1p->get_scan_new_refs_time(worker_i);
+  if (scan_new_refs_time_ms > 0.0) {
+    closure_app_time_ms += scan_new_refs_time_ms;
   }
+
   _g1p->record_obj_copy_time(worker_i, closure_app_time_ms);
 }
 
@@ -469,8 +449,8 @@
   double scan_new_refs_start_sec = os::elapsedTime();
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   CardTableModRefBS* ct_bs = (CardTableModRefBS*) (g1h->barrier_set());
-  while (_new_refs[worker_i]->is_nonempty()) {
-    oop* p = _new_refs[worker_i]->pop();
+  for (int i = 0; i < _new_refs[worker_i]->length(); i++) {
+    oop* p = _new_refs[worker_i]->at(i);
     oop obj = *p;
     // *p was in the collection set when p was pushed on "_new_refs", but
     // another thread may have processed this location from an RS, so it
@@ -480,10 +460,6 @@
       HeapRegion* r = g1h->heap_region_containing(p);
 
       DEBUG_ONLY(HeapRegion* to = g1h->heap_region_containing(obj));
-      assert(ParallelGCThreads > 1
-             || to->rem_set()->contains_reference(p),
-             "Invariant: pushed after being added."
-             "(Not reliable in parallel code.)");
       oc->set_region(r);
       // If "p" has already been processed concurrently, this is
       // idempotent.
@@ -526,20 +502,31 @@
   }
 
   if (ParallelGCThreads > 0) {
-    // This is a temporary change to serialize the update and scanning
-    // of remembered sets. There are some race conditions when this is
-    // done in parallel and they are causing failures. When we resolve
-    // said race conditions, we'll revert back to parallel remembered
-    // set updating and scanning. See CRs 6677707 and 6677708.
-    if (worker_i == 0) {
+    // The two flags below were introduced temporarily to serialize
+    // the updating and scanning of remembered sets. There are some
+    // race conditions when these two operations are done in parallel
+    // and they are causing failures. When we resolve said race
+    // conditions, we'll revert back to parallel remembered set
+    // updating and scanning. See CRs 6677707 and 6677708.
+    if (G1EnableParallelRSetUpdating || (worker_i == 0)) {
       updateRS(worker_i);
       scanNewRefsRS(oc, worker_i);
+    } else {
+      _g1p->record_update_rs_start_time(worker_i, os::elapsedTime());
+      _g1p->record_update_rs_processed_buffers(worker_i, 0.0);
+      _g1p->record_update_rs_time(worker_i, 0.0);
+      _g1p->record_scan_new_refs_time(worker_i, 0.0);
+    }
+    if (G1EnableParallelRSetScanning || (worker_i == 0)) {
       scanRS(oc, worker_i);
+    } else {
+      _g1p->record_scan_rs_start_time(worker_i, os::elapsedTime());
+      _g1p->record_scan_rs_time(worker_i, 0.0);
     }
   } else {
     assert(worker_i == 0, "invariant");
-
     updateRS(0);
+    scanNewRefsRS(oc, 0);
     scanRS(oc, 0);
   }
 }
@@ -559,11 +546,7 @@
   assert(!_par_traversal_in_progress, "Invariant between iterations.");
   if (ParallelGCThreads > 0) {
     set_par_traversal(true);
-    int n_workers = _g1->workers()->total_workers();
-    _seq_task->set_par_threads(n_workers);
-    for (uint i = 0; i < ParallelGCThreads; i++)
-      _new_refs[i] = new (ResourceObj::C_HEAP) GrowableArray<oop*>(8192,true);
-
+    _seq_task->set_par_threads((int)n_workers());
     if (cg1r->do_traversal()) {
       updateRS(0);
       // Have to do this again after updaters
@@ -587,6 +570,51 @@
   }
 };
 
+class UpdateRSetOopsIntoCSImmediate : public OopClosure {
+  G1CollectedHeap* _g1;
+public:
+  UpdateRSetOopsIntoCSImmediate(G1CollectedHeap* g1) : _g1(g1) { }
+  virtual void do_oop(narrowOop* p) {
+    guarantee(false, "NYI");
+  }
+  virtual void do_oop(oop* p) {
+    HeapRegion* to = _g1->heap_region_containing(*p);
+    if (to->in_collection_set()) {
+      to->rem_set()->add_reference(p, 0);
+    }
+  }
+};
+
+class UpdateRSetOopsIntoCSDeferred : public OopClosure {
+  G1CollectedHeap* _g1;
+  CardTableModRefBS* _ct_bs;
+  DirtyCardQueue* _dcq;
+public:
+  UpdateRSetOopsIntoCSDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
+    _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) { }
+  virtual void do_oop(narrowOop* p) {
+    guarantee(false, "NYI");
+  }
+  virtual void do_oop(oop* p) {
+    oop obj = *p;
+    if (_g1->obj_in_cs(obj)) {
+      size_t card_index = _ct_bs->index_for(p);
+      if (_ct_bs->mark_card_deferred(card_index)) {
+        _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
+      }
+    }
+  }
+};
+
+void HRInto_G1RemSet::new_refs_iterate(OopClosure* cl) {
+  for (size_t i = 0; i < n_workers(); i++) {
+    for (int j = 0; j < _new_refs[i]->length(); j++) {
+      oop* p = _new_refs[i]->at(j);
+      cl->do_oop(p);
+    }
+  }
+}
+
 void HRInto_G1RemSet::cleanup_after_oops_into_collection_set_do() {
   guarantee( _cards_scanned != NULL, "invariant" );
   _total_cards_scanned = 0;
@@ -609,11 +637,25 @@
     if (cg1r->do_traversal()) {
       cg1r->cg1rThread()->set_do_traversal(false);
     }
-    for (uint i = 0; i < ParallelGCThreads; i++) {
-      delete _new_refs[i];
-    }
     set_par_traversal(false);
   }
+
+  if (_g1->evacuation_failed()) {
+    // Restore remembered sets for the regions pointing into
+    // the collection set.
+    if (G1DeferredRSUpdate) {
+      DirtyCardQueue dcq(&_g1->dirty_card_queue_set());
+      UpdateRSetOopsIntoCSDeferred deferred_update(_g1, &dcq);
+      new_refs_iterate(&deferred_update);
+    } else {
+      UpdateRSetOopsIntoCSImmediate immediate_update(_g1);
+      new_refs_iterate(&immediate_update);
+    }
+  }
+  for (uint i = 0; i < n_workers(); i++) {
+    _new_refs[i]->clear();
+  }
+
   assert(!_par_traversal_in_progress, "Invariant between iterations.");
 }
 
@@ -980,9 +1022,8 @@
     gclog_or_tty->print_cr("    %d occupied cards represented.",
                            blk.occupied());
     gclog_or_tty->print_cr("    Max sz region = [" PTR_FORMAT ", " PTR_FORMAT " )"
-                           " %s, cap = " SIZE_FORMAT "K, occ = " SIZE_FORMAT "K.",
+                           ", cap = " SIZE_FORMAT "K, occ = " SIZE_FORMAT "K.",
                            blk.max_mem_sz_region()->bottom(), blk.max_mem_sz_region()->end(),
-                           (blk.max_mem_sz_region()->popular() ? "POP" : ""),
                            (blk.max_mem_sz_region()->rem_set()->mem_size() + K - 1)/K,
                            (blk.max_mem_sz_region()->rem_set()->occupied() + K - 1)/K);
     gclog_or_tty->print_cr("    Did %d coarsenings.",
@@ -991,7 +1032,9 @@
   }
 }
 void HRInto_G1RemSet::prepare_for_verify() {
-  if (G1HRRSFlushLogBuffersOnVerify && VerifyBeforeGC && !_g1->full_collection()) {
+  if (G1HRRSFlushLogBuffersOnVerify &&
+      (VerifyBeforeGC || VerifyAfterGC)
+      &&  !_g1->full_collection()) {
     cleanupHRRS();
     _g1->set_refine_cte_cl_concurrency(false);
     if (SafepointSynchronize::is_at_safepoint()) {
@@ -1002,5 +1045,7 @@
     _cg1r->set_use_cache(false);
     updateRS(0);
     _cg1r->set_use_cache(cg1r_use_cache);
+
+    assert(JavaThread::dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
   }
 }
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -155,6 +155,7 @@
   bool _par_traversal_in_progress;
   void set_par_traversal(bool b);
   GrowableArray<oop*>** _new_refs;
+  void new_refs_iterate(OopClosure* cl);
 
 public:
   // This is called to reset dual hash tables after the gc pause
@@ -214,3 +215,27 @@
   int n() { return _n; };
   HeapWord* start_first() { return _start_first; }
 };
+
+class UpdateRSOopClosure: public OopClosure {
+  HeapRegion* _from;
+  HRInto_G1RemSet* _rs;
+  int _worker_i;
+public:
+  UpdateRSOopClosure(HRInto_G1RemSet* rs, int worker_i = 0) :
+    _from(NULL), _rs(rs), _worker_i(worker_i) {
+    guarantee(_rs != NULL, "Requires an HRIntoG1RemSet");
+  }
+
+  void set_from(HeapRegion* from) {
+    assert(from != NULL, "from region must be non-NULL");
+    _from = from;
+  }
+
+  virtual void do_oop(narrowOop* p);
+  virtual void do_oop(oop* p);
+
+  // Override: this closure is idempotent.
+  //  bool idempotent() { return true; }
+  bool apply_to_weak_ref_discovered_field() { return true; }
+};
+
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -31,24 +31,7 @@
 }
 
 inline void HRInto_G1RemSet::write_ref_nv(HeapRegion* from, oop* p) {
-  oop obj = *p;
-  assert(from != NULL && from->is_in_reserved(p),
-         "p is not in a from");
-  HeapRegion* to = _g1->heap_region_containing(obj);
-  if (from != to && to != NULL) {
-    if (!to->popular() && !from->is_survivor()) {
-#if G1_REM_SET_LOGGING
-      gclog_or_tty->print_cr("Adding " PTR_FORMAT " (" PTR_FORMAT ") to RS"
-                             " for region [" PTR_FORMAT ", " PTR_FORMAT ")",
-                             p, obj,
-                             to->bottom(), to->end());
-#endif
-      assert(to->rem_set() != NULL, "Need per-region 'into' remsets.");
-      if (to->rem_set()->add_reference(p)) {
-        _g1->schedule_popular_region_evac(to);
-      }
-    }
-  }
+  par_write_ref(from, p, 0);
 }
 
 inline void HRInto_G1RemSet::write_ref(HeapRegion* from, oop* p) {
@@ -82,7 +65,18 @@
   HeapRegion* to = _g1->heap_region_containing(obj);
   // The test below could be optimized by applying a bit op to to and from.
   if (to != NULL && from != NULL && from != to) {
-    if (!to->popular() && !from->is_survivor()) {
+    // There is a tricky infinite loop if we keep pushing
+    // self forwarding pointers onto our _new_refs list.
+    // The _par_traversal_in_progress flag is true during the collection pause,
+    // false during the evacuation failure handing.
+    if (_par_traversal_in_progress &&
+        to->in_collection_set() && !self_forwarded(obj)) {
+      _new_refs[tid]->push(p);
+      // Deferred updates to the Cset are either discarded (in the normal case),
+      // or processed (if an evacuation failure occurs) at the end
+      // of the collection.
+      // See HRInto_G1RemSet::cleanup_after_oops_into_collection_set_do().
+    } else {
 #if G1_REM_SET_LOGGING
       gclog_or_tty->print_cr("Adding " PTR_FORMAT " (" PTR_FORMAT ") to RS"
                              " for region [" PTR_FORMAT ", " PTR_FORMAT ")",
@@ -90,15 +84,16 @@
                              to->bottom(), to->end());
 #endif
       assert(to->rem_set() != NULL, "Need per-region 'into' remsets.");
-      if (to->rem_set()->add_reference(p, tid)) {
-        _g1->schedule_popular_region_evac(to);
-      }
-    }
-    // There is a tricky infinite loop if we keep pushing
-    // self forwarding pointers onto our _new_refs list.
-    if (_par_traversal_in_progress &&
-        to->in_collection_set() && !self_forwarded(obj)) {
-      _new_refs[tid]->push(p);
+      to->rem_set()->add_reference(p, tid);
     }
   }
 }
+
+inline void UpdateRSOopClosure::do_oop(narrowOop* p) {
+  guarantee(false, "NYI");
+}
+
+inline void UpdateRSOopClosure::do_oop(oop* p) {
+  assert(_from != NULL, "from region must be non-NULL");
+  _rs->par_write_ref(_from, p, _worker_i);
+}
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -172,6 +172,9 @@
   develop(bool, G1RSBarrierUseQueue, true,                                  \
           "If true, use queueing RS barrier")                               \
                                                                             \
+  develop(bool, G1DeferredRSUpdate, true,                                   \
+          "If true, use deferred RS updates")                               \
+                                                                            \
   develop(bool, G1RSLogCheckCardTable, false,                               \
           "If true, verify that no dirty cards remain after RS log "        \
           "processing.")                                                    \
@@ -182,15 +185,9 @@
   product(intx, G1InefficientPausePct, 80,                                  \
           "Threshold of an 'inefficient' pauses (as % of cum efficiency.")  \
                                                                             \
-  product(intx, G1RSPopLimit, 32768,                                        \
-          "Limit that defines popularity.  Should go away! XXX")            \
-                                                                            \
   develop(bool, G1RSCountHisto, false,                                      \
           "If true, print a histogram of RS occupancies after each pause")  \
                                                                             \
-  product(intx, G1ObjPopLimit, 256,                                         \
-          "Limit that defines popularity for an object.")                   \
-                                                                            \
   product(bool, G1TraceFileOverwrite, false,                                \
           "Allow the trace file to be overwritten")                         \
                                                                             \
@@ -198,16 +195,6 @@
           "When > 0, print the occupancies of the <n> best and worst"       \
           "regions.")                                                       \
                                                                             \
-  develop(bool, G1TracePopularity, false,                                   \
-          "When true, provide detailed tracing of popularity.")             \
-                                                                            \
-  product(bool, G1SummarizePopularity, false,                               \
-          "When true, provide end-of-run-summarization of popularity.")     \
-                                                                            \
-  product(intx, G1NumPopularRegions, 1,                                     \
-          "Number of regions reserved to hold popular objects.  "           \
-          "Should go away later.")                                          \
-                                                                            \
   develop(bool, G1PrintParCleanupStats, false,                              \
           "When true, print extra stats about parallel cleanup.")           \
                                                                             \
@@ -292,6 +279,14 @@
                                                                             \
   product(uintx, G1FixedSurvivorSpaceSize, 0,                               \
           "If non-0 is the size of the G1 survivor space, "                 \
-          "otherwise SurvivorRatio is used to determine the size")
+          "otherwise SurvivorRatio is used to determine the size")          \
+                                                                            \
+  experimental(bool, G1EnableParallelRSetUpdating, false,                   \
+          "Enables the parallelization of remembered set updating "         \
+          "during evacuation pauses")                                       \
+                                                                            \
+  experimental(bool, G1EnableParallelRSetScanning, false,                   \
+          "Enables the parallelization of remembered set scanning "         \
+          "during evacuation pauses")
 
 G1_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_EXPERIMENTAL_FLAG, DECLARE_NOTPRODUCT_FLAG, DECLARE_MANAGEABLE_FLAG, DECLARE_PRODUCT_RW_FLAG)
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_specialized_oop_closures.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_specialized_oop_closures.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -104,7 +104,6 @@
         HeapRegion* to   = _g1h->heap_region_containing(*p);
         if (from != NULL && to != NULL &&
             from != to &&
-            !to->popular() &&
             !to->isHumongous()) {
           jbyte cv_obj = *_bs->byte_for_const(_containing_obj);
           jbyte cv_field = *_bs->byte_for_const(p);
@@ -285,8 +284,6 @@
   }
   zero_marked_bytes();
   set_sort_index(-1);
-  if ((uintptr_t)bottom() >= (uintptr_t)g1h->popular_object_boundary())
-    set_popular(false);
 
   _offsets.resize(HeapRegion::GrainWords);
   init_top_at_mark_start();
@@ -371,7 +368,6 @@
     _next_in_special_set(NULL), _orig_end(NULL),
     _claimed(InitialClaimValue), _evacuation_failed(false),
     _prev_marked_bytes(0), _next_marked_bytes(0), _sort_index(-1),
-    _popularity(NotPopular),
     _young_type(NotYoung), _next_young_region(NULL),
     _young_index_in_cset(-1), _surv_rate_group(NULL), _age_index(-1),
     _rem_set(NULL), _zfs(NotZeroFilled)
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -238,15 +238,6 @@
   // See "sort_index" method.  -1 means is not in the array.
   int _sort_index;
 
-  // Means it has (or at least had) a very large RS, and should not be
-  // considered for membership in a collection set.
-  enum PopularityState {
-    NotPopular,
-    PopularPending,
-    Popular
-  };
-  PopularityState _popularity;
-
   // <PREDICTION>
   double _gc_efficiency;
   // </PREDICTION>
@@ -318,7 +309,8 @@
     FinalCountClaimValue  = 1,
     NoteEndClaimValue     = 2,
     ScrubRemSetClaimValue = 3,
-    ParVerifyClaimValue   = 4
+    ParVerifyClaimValue   = 4,
+    RebuildRSClaimValue   = 5
   };
 
   // Concurrent refinement requires contiguous heap regions (in which TLABs
@@ -432,10 +424,6 @@
     _next_in_special_set = r;
   }
 
-  bool is_reserved() {
-    return popular();
-  }
-
   bool is_on_free_list() {
     return _is_on_free_list;
   }
@@ -608,23 +596,6 @@
     init_top_at_mark_start();
   }
 
-  bool popular() { return _popularity == Popular; }
-  void set_popular(bool b) {
-    if (b) {
-      _popularity = Popular;
-    } else {
-      _popularity = NotPopular;
-    }
-  }
-  bool popular_pending() { return _popularity == PopularPending; }
-  void set_popular_pending(bool b) {
-    if (b) {
-      _popularity = PopularPending;
-    } else {
-      _popularity = NotPopular;
-    }
-  }
-
   // <PREDICTION>
   void calc_gc_efficiency(void);
   double gc_efficiency() { return _gc_efficiency;}
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -508,7 +508,7 @@
   typedef PosParPRT* PosParPRTPtr;
   if (_max_fine_entries == 0) {
     assert(_mod_max_fine_entries_mask == 0, "Both or none.");
-    _max_fine_entries = (1 << G1LogRSRegionEntries);
+    _max_fine_entries = (size_t)(1 << G1LogRSRegionEntries);
     _mod_max_fine_entries_mask = _max_fine_entries - 1;
 #if SAMPLE_FOR_EVICTION
     assert(_fine_eviction_sample_size == 0
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -188,32 +188,6 @@
   // the _outgoing_region_map.
   void clear_outgoing_entries();
 
-#if MAYBE
-  // Audit the given card index.
-  void audit_card(size_t card_num, HeapRegion* hr, u2* rc_arr,
-                  HeapRegionRemSet* empty_cards, size_t* one_obj_cards);
-
-  // Assumes that "audit_stage1" has been called for "hr", to set up
-  // "shadow" and "new_rs" appropriately.  Identifies individual popular
-  // objects; returns "true" if any are found.
-  bool audit_find_pop(HeapRegion* hr, u2* rc_arr);
-
-  // Assumes that "audit_stage1" has been called for "hr", to set up
-  // "shadow" and "new_rs" appropriately.  Identifies individual popular
-  // objects, and determines the number of entries in "new_rs" if any such
-  // popular objects are ignored.  If this is sufficiently small, returns
-  // "false" to indicate that a constraint should not be introduced.
-  // Otherwise, returns "true" to indicate that we should go ahead with
-  // adding the constraint.
-  bool audit_stag(HeapRegion* hr, u2* rc_arr);
-
-
-  u2* alloc_rc_array();
-
-  SeqHeapRegionRemSet* audit_post(u2* rc_arr, size_t multi_obj_crds,
-                                  SeqHeapRegionRemSet* empty_cards);
-#endif
-
   enum ParIterState { Unclaimed, Claimed, Complete };
   ParIterState _iter_state;
 
@@ -261,16 +235,14 @@
 
   /* Used in the sequential case.  Returns "true" iff this addition causes
      the size limit to be reached. */
-  bool add_reference(oop* from) {
+  void add_reference(oop* from) {
     _other_regions.add_reference(from);
-    return false;
   }
 
   /* Used in the parallel case.  Returns "true" iff this addition causes
      the size limit to be reached. */
-  bool add_reference(oop* from, int tid) {
+  void add_reference(oop* from, int tid) {
     _other_regions.add_reference(from, tid);
-    return false;
   }
 
   // Records the fact that the current region contains an outgoing
@@ -338,20 +310,6 @@
   }
   void print() const;
 
-#if MAYBE
-  // We are about to introduce a constraint, requiring the collection time
-  // of the region owning this RS to be <= "hr", and forgetting pointers
-  // from the owning region to "hr."  Before doing so, examines this rem
-  // set for pointers to "hr", possibly identifying some popular objects.,
-  // and possibly finding some cards to no longer contain pointers to "hr",
-  //
-  // These steps may prevent the the constraint from being necessary; in
-  // which case returns a set of cards now thought to contain no pointers
-  // into HR.  In the normal (I assume) case, returns NULL, indicating that
-  // we should go ahead and add the constraint.
-  virtual SeqHeapRegionRemSet* audit(HeapRegion* hr) = 0;
-#endif
-
   // Called during a stop-world phase to perform any deferred cleanups.
   // The second version may be called by parallel threads after then finish
   // collection work.
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,7 +74,6 @@
     //       [first, cur)
     HeapRegion* curhr = _regions.at(cur);
     if (curhr->is_empty()
-        && !curhr->is_reserved()
         && (first == cur
             || (_regions.at(cur-1)->end() ==
                 curhr->bottom()))) {
@@ -121,35 +120,27 @@
   }
 }
 
-void HeapRegionSeq::print_empty_runs(bool reserved_are_empty) {
+void HeapRegionSeq::print_empty_runs() {
   int empty_run = 0;
   int n_empty = 0;
-  bool at_least_one_reserved = false;
   int empty_run_start;
   for (int i = 0; i < _regions.length(); i++) {
     HeapRegion* r = _regions.at(i);
     if (r->continuesHumongous()) continue;
-    if (r->is_empty() && (reserved_are_empty || !r->is_reserved())) {
+    if (r->is_empty()) {
       assert(!r->isHumongous(), "H regions should not be empty.");
       if (empty_run == 0) empty_run_start = i;
       empty_run++;
       n_empty++;
-      if (r->is_reserved()) {
-        at_least_one_reserved = true;
-      }
     } else {
       if (empty_run > 0) {
         gclog_or_tty->print("  %d:%d", empty_run_start, empty_run);
-        if (reserved_are_empty && at_least_one_reserved)
-          gclog_or_tty->print("(R)");
         empty_run = 0;
-        at_least_one_reserved = false;
       }
     }
   }
   if (empty_run > 0) {
     gclog_or_tty->print(" %d:%d", empty_run_start, empty_run);
-    if (reserved_are_empty && at_least_one_reserved) gclog_or_tty->print("(R)");
   }
   gclog_or_tty->print_cr(" [tot = %d]", n_empty);
 }
@@ -193,7 +184,6 @@
   int cur = first;
   while (cur >= 0 &&
          (_regions.at(cur)->is_empty()
-          && !_regions.at(cur)->is_reserved()
           && (first == cur
               || (_regions.at(cur+1)->bottom() ==
                   _regions.at(cur)->end())))) {
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -104,8 +104,7 @@
 
   void print();
 
-  // Prints out runs of empty regions.  If the arg is "true" reserved
-  // (popular regions are considered "empty".
-  void print_empty_runs(bool reserved_are_empty);
+  // Prints out runs of empty regions.
+  void print_empty_runs();
 
 };
--- a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -91,15 +91,17 @@
   _n_completed_buffers(0),
   _process_completed_threshold(0), _process_completed(false),
   _buf_free_list(NULL), _buf_free_list_sz(0)
-{}
+{
+  _fl_owner = this;
+}
 
 void** PtrQueueSet::allocate_buffer() {
   assert(_sz > 0, "Didn't set a buffer size.");
-  MutexLockerEx x(_fl_lock, Mutex::_no_safepoint_check_flag);
-  if (_buf_free_list != NULL) {
-    void** res = _buf_free_list;
-    _buf_free_list = (void**)_buf_free_list[0];
-    _buf_free_list_sz--;
+  MutexLockerEx x(_fl_owner->_fl_lock, Mutex::_no_safepoint_check_flag);
+  if (_fl_owner->_buf_free_list != NULL) {
+    void** res = _fl_owner->_buf_free_list;
+    _fl_owner->_buf_free_list = (void**)_fl_owner->_buf_free_list[0];
+    _fl_owner->_buf_free_list_sz--;
     // Just override the next pointer with NULL, just in case we scan this part
     // of the buffer.
     res[0] = NULL;
@@ -111,10 +113,10 @@
 
 void PtrQueueSet::deallocate_buffer(void** buf) {
   assert(_sz > 0, "Didn't set a buffer size.");
-  MutexLockerEx x(_fl_lock, Mutex::_no_safepoint_check_flag);
-  buf[0] = (void*)_buf_free_list;
-  _buf_free_list = buf;
-  _buf_free_list_sz++;
+  MutexLockerEx x(_fl_owner->_fl_lock, Mutex::_no_safepoint_check_flag);
+  buf[0] = (void*)_fl_owner->_buf_free_list;
+  _fl_owner->_buf_free_list = buf;
+  _fl_owner->_buf_free_list_sz++;
 }
 
 void PtrQueueSet::reduce_free_list() {
@@ -207,3 +209,58 @@
 void PtrQueueSet::set_process_completed_threshold(size_t sz) {
   _process_completed_threshold = sz;
 }
+
+// Merge lists of buffers. Notify waiting threads if the length of the list
+// exceeds threshold. The source queue is emptied as a result. The queues
+// must share the monitor.
+void PtrQueueSet::merge_bufferlists(PtrQueueSet *src) {
+  assert(_cbl_mon == src->_cbl_mon, "Should share the same lock");
+  MutexLockerEx x(_cbl_mon, Mutex::_no_safepoint_check_flag);
+  if (_completed_buffers_tail == NULL) {
+    assert(_completed_buffers_head == NULL, "Well-formedness");
+    _completed_buffers_head = src->_completed_buffers_head;
+    _completed_buffers_tail = src->_completed_buffers_tail;
+  } else {
+    assert(_completed_buffers_head != NULL, "Well formedness");
+    if (src->_completed_buffers_head != NULL) {
+      _completed_buffers_tail->next = src->_completed_buffers_head;
+      _completed_buffers_tail = src->_completed_buffers_tail;
+    }
+  }
+  _n_completed_buffers += src->_n_completed_buffers;
+
+  src->_n_completed_buffers = 0;
+  src->_completed_buffers_head = NULL;
+  src->_completed_buffers_tail = NULL;
+
+  assert(_completed_buffers_head == NULL && _completed_buffers_tail == NULL ||
+         _completed_buffers_head != NULL && _completed_buffers_tail != NULL,
+         "Sanity");
+
+  if (!_process_completed &&
+      _n_completed_buffers >= _process_completed_threshold) {
+    _process_completed = true;
+    if (_notify_when_complete)
+      _cbl_mon->notify_all();
+  }
+}
+
+// Merge free lists of the two queues. The free list of the source
+// queue is emptied as a result. The queues must share the same
+// mutex that guards free lists.
+void PtrQueueSet::merge_freelists(PtrQueueSet* src) {
+  assert(_fl_lock == src->_fl_lock, "Should share the same lock");
+  MutexLockerEx x(_fl_lock, Mutex::_no_safepoint_check_flag);
+  if (_buf_free_list != NULL) {
+    void **p = _buf_free_list;
+    while (*p != NULL) {
+      p = (void**)*p;
+    }
+    *p = src->_buf_free_list;
+  } else {
+    _buf_free_list = src->_buf_free_list;
+  }
+  _buf_free_list_sz += src->_buf_free_list_sz;
+  src->_buf_free_list = NULL;
+  src->_buf_free_list_sz = 0;
+}
--- a/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/ptrQueue.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -155,6 +155,9 @@
   Mutex* _fl_lock;
   void** _buf_free_list;
   size_t _buf_free_list_sz;
+  // Queue set can share a freelist. The _fl_owner variable
+  // specifies the owner. It is set to "this" by default.
+  PtrQueueSet* _fl_owner;
 
   // The size of all buffers in the set.
   size_t _sz;
@@ -188,10 +191,13 @@
   // Because of init-order concerns, we can't pass these as constructor
   // arguments.
   void initialize(Monitor* cbl_mon, Mutex* fl_lock,
-                  int max_completed_queue = 0) {
+                  int max_completed_queue = 0,
+                  PtrQueueSet *fl_owner = NULL) {
     _max_completed_queue = max_completed_queue;
     assert(cbl_mon != NULL && fl_lock != NULL, "Init order issue?");
-    _cbl_mon = cbl_mon; _fl_lock = fl_lock;
+    _cbl_mon = cbl_mon;
+    _fl_lock = fl_lock;
+    _fl_owner = (fl_owner != NULL) ? fl_owner : this;
   }
 
   // Return an empty oop array of size _sz (required to be non-zero).
@@ -228,4 +234,7 @@
   void reduce_free_list();
 
   size_t completed_buffers_num() { return _n_completed_buffers; }
+
+  void merge_bufferlists(PtrQueueSet* src);
+  void merge_freelists(PtrQueueSet* src);
 };
--- a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -504,6 +504,7 @@
   // Make sure that the current and next tables agree.  (Another mechanism
   // takes care of deleting now-unused tables.)
   _cur = _next;
+  set_expanded(false);
 }
 
 void SparsePRT::expand() {
--- a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -274,7 +274,7 @@
 
   // Clean up all tables on the expanded list.  Called single threaded.
   static void cleanup_all();
-  RSHashTable* next() const { return _next; }
+  RSHashTable* cur() const { return _cur; }
 
 
   void init_iterator(SparsePRTIter* sprt_iter);
@@ -300,7 +300,7 @@
   {}
 
   void init(const SparsePRT* sprt) {
-    RSHashTableIter::init(sprt->next());
+    RSHashTableIter::init(sprt->cur());
   }
   bool has_next(size_t& card_index) {
     return RSHashTableIter::has_next(card_index);
--- a/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -43,16 +43,9 @@
   JvmtiGCForAllocationMarker jgcm;
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   GCCauseSetter x(g1h, GCCause::_g1_inc_collection_pause);
-  g1h->do_collection_pause_at_safepoint(NULL);
+  g1h->do_collection_pause_at_safepoint();
 }
 
-void VM_G1PopRegionCollectionPause::doit() {
-  JvmtiGCForAllocationMarker jgcm;
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  g1h->do_collection_pause_at_safepoint(_pop_region);
-}
-
-
 void VM_CGC_Operation::doit() {
   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
--- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -77,20 +77,6 @@
   }
 };
 
-class VM_G1PopRegionCollectionPause: public VM_GC_Operation {
-  HeapRegion* _pop_region;
- public:
-  VM_G1PopRegionCollectionPause(int gc_count_before, HeapRegion* pop_region) :
-    VM_GC_Operation(gc_count_before),
-    _pop_region(pop_region)
-  {}
-  virtual VMOp_Type type() const { return VMOp_G1PopRegionCollectionPause; }
-  virtual void doit();
-  virtual const char* name() const {
-    return "garbage-first popular region collection pause";
-  }
-};
-
 // Concurrent GC stop-the-world operations such as initial and final mark;
 // consider sharing these with CMS's counterparts.
 class VM_CGC_Operation: public VM_Operation {
--- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parNew/parGCAllocBuffer.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parGCAllocBuffer.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parNew/parGCAllocBuffer.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parGCAllocBuffer.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -63,9 +63,8 @@
   // return NULL.
   HeapWord* allocate(size_t word_sz) {
     HeapWord* res = _top;
-    HeapWord* new_top = _top + word_sz;
-    if (new_top <= _end) {
-      _top = new_top;
+    if (pointer_delta(_end, _top) >= word_sz) {
+      _top = _top + word_sz;
       return res;
     } else {
       return NULL;
@@ -75,10 +74,9 @@
   // Undo the last allocation in the buffer, which is required to be of the
   // "obj" of the given "word_sz".
   void undo_allocation(HeapWord* obj, size_t word_sz) {
-    assert(_top - word_sz >= _bottom
-           && _top - word_sz == obj,
-           "Bad undo_allocation");
-    _top = _top - word_sz;
+    assert(pointer_delta(_top, _bottom) >= word_sz, "Bad undo");
+    assert(pointer_delta(_top, obj)     == word_sz, "Bad undo");
+    _top = obj;
   }
 
   // The total (word) size of the buffer, including both allocated and
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,10 +34,12 @@
                                        Generation* old_gen_,
                                        int thread_num_,
                                        ObjToScanQueueSet* work_queue_set_,
+                                       GrowableArray<oop>**  overflow_stack_set_,
                                        size_t desired_plab_sz_,
                                        ParallelTaskTerminator& term_) :
-  _to_space(to_space_), _old_gen(old_gen_), _thread_num(thread_num_),
+  _to_space(to_space_), _old_gen(old_gen_), _young_gen(gen_), _thread_num(thread_num_),
   _work_queue(work_queue_set_->queue(thread_num_)), _to_space_full(false),
+  _overflow_stack(overflow_stack_set_[thread_num_]),
   _ageTable(false), // false ==> not the global age table, no perf data.
   _to_space_alloc_buffer(desired_plab_sz_),
   _to_space_closure(gen_, this), _old_gen_closure(gen_, this),
@@ -81,7 +83,7 @@
   assert(old->is_objArray(), "must be obj array");
   assert(old->is_forwarded(), "must be forwarded");
   assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
-  assert(!_old_gen->is_in(old), "must be in young generation.");
+  assert(!old_gen()->is_in(old), "must be in young generation.");
 
   objArrayOop obj = objArrayOop(old->forwardee());
   // Process ParGCArrayScanChunk elements now
@@ -119,26 +121,68 @@
 
 void ParScanThreadState::trim_queues(int max_size) {
   ObjToScanQueue* queue = work_queue();
-  while (queue->size() > (juint)max_size) {
-    oop obj_to_scan;
-    if (queue->pop_local(obj_to_scan)) {
-      note_pop();
-
-      if ((HeapWord *)obj_to_scan < young_old_boundary()) {
-        if (obj_to_scan->is_objArray() &&
-            obj_to_scan->is_forwarded() &&
-            obj_to_scan->forwardee() != obj_to_scan) {
-          scan_partial_array_and_push_remainder(obj_to_scan);
+  do {
+    while (queue->size() > (juint)max_size) {
+      oop obj_to_scan;
+      if (queue->pop_local(obj_to_scan)) {
+        note_pop();
+        if ((HeapWord *)obj_to_scan < young_old_boundary()) {
+          if (obj_to_scan->is_objArray() &&
+              obj_to_scan->is_forwarded() &&
+              obj_to_scan->forwardee() != obj_to_scan) {
+            scan_partial_array_and_push_remainder(obj_to_scan);
+          } else {
+            // object is in to_space
+            obj_to_scan->oop_iterate(&_to_space_closure);
+          }
         } else {
-          // object is in to_space
-          obj_to_scan->oop_iterate(&_to_space_closure);
+          // object is in old generation
+          obj_to_scan->oop_iterate(&_old_gen_closure);
         }
-      } else {
-        // object is in old generation
-        obj_to_scan->oop_iterate(&_old_gen_closure);
       }
     }
+    // For the  case of compressed oops, we have a private, non-shared
+    // overflow stack, so we eagerly drain it so as to more evenly
+    // distribute load early. Note: this may be good to do in
+    // general rather than delay for the final stealing phase.
+    // If applicable, we'll transfer a set of objects over to our
+    // work queue, allowing them to be stolen and draining our
+    // private overflow stack.
+  } while (ParGCTrimOverflow && young_gen()->take_from_overflow_list(this));
+}
+
+bool ParScanThreadState::take_from_overflow_stack() {
+  assert(ParGCUseLocalOverflow, "Else should not call");
+  assert(young_gen()->overflow_list() == NULL, "Error");
+  ObjToScanQueue* queue = work_queue();
+  GrowableArray<oop>* of_stack = overflow_stack();
+  uint num_overflow_elems = of_stack->length();
+  uint num_take_elems     = MIN2(MIN2((queue->max_elems() - queue->size())/4,
+                                      (juint)ParGCDesiredObjsFromOverflowList),
+                                 num_overflow_elems);
+  // Transfer the most recent num_take_elems from the overflow
+  // stack to our work queue.
+  for (size_t i = 0; i != num_take_elems; i++) {
+    oop cur = of_stack->pop();
+    oop obj_to_push = cur->forwardee();
+    assert(Universe::heap()->is_in_reserved(cur), "Should be in heap");
+    assert(!old_gen()->is_in_reserved(cur), "Should be in young gen");
+    assert(Universe::heap()->is_in_reserved(obj_to_push), "Should be in heap");
+    if (should_be_partially_scanned(obj_to_push, cur)) {
+      assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
+      obj_to_push = cur;
+    }
+    bool ok = queue->push(obj_to_push);
+    assert(ok, "Should have succeeded");
   }
+  assert(young_gen()->overflow_list() == NULL, "Error");
+  return num_take_elems > 0;  // was something transferred?
+}
+
+void ParScanThreadState::push_on_overflow_stack(oop p) {
+  assert(ParGCUseLocalOverflow, "Else should not call");
+  overflow_stack()->push(p);
+  assert(young_gen()->overflow_list() == NULL, "Error");
 }
 
 HeapWord* ParScanThreadState::alloc_in_to_space_slow(size_t word_sz) {
@@ -213,6 +257,7 @@
                         ParNewGeneration&       gen,
                         Generation&             old_gen,
                         ObjToScanQueueSet&      queue_set,
+                        GrowableArray<oop>**    overflow_stacks_,
                         size_t                  desired_plab_sz,
                         ParallelTaskTerminator& term);
   inline ParScanThreadState& thread_sate(int i);
@@ -235,6 +280,7 @@
 ParScanThreadStateSet::ParScanThreadStateSet(
   int num_threads, Space& to_space, ParNewGeneration& gen,
   Generation& old_gen, ObjToScanQueueSet& queue_set,
+  GrowableArray<oop>** overflow_stack_set_,
   size_t desired_plab_sz, ParallelTaskTerminator& term)
   : ResourceArray(sizeof(ParScanThreadState), num_threads),
     _gen(gen), _next_gen(old_gen), _term(term),
@@ -245,7 +291,7 @@
   for (int i = 0; i < num_threads; ++i) {
     new ((ParScanThreadState*)_data + i)
         ParScanThreadState(&to_space, &gen, &old_gen, i, &queue_set,
-                           desired_plab_sz, term);
+                           overflow_stack_set_, desired_plab_sz, term);
   }
 }
 
@@ -425,8 +471,7 @@
   ResourceMark rm;
   HandleMark hm;
   // We would need multiple old-gen queues otherwise.
-  guarantee(gch->n_gens() == 2,
-     "Par young collection currently only works with one older gen.");
+  assert(gch->n_gens() == 2, "Par young collection currently only works with one older gen.");
 
   Generation* old_gen = gch->next_gen(_gen);
 
@@ -473,6 +518,17 @@
   for (uint i2 = 0; i2 < ParallelGCThreads; i2++)
     _task_queues->queue(i2)->initialize();
 
+  _overflow_stacks = NEW_C_HEAP_ARRAY(GrowableArray<oop>*, ParallelGCThreads);
+  guarantee(_overflow_stacks != NULL, "Overflow stack set allocation failure");
+  for (uint i = 0; i < ParallelGCThreads; i++) {
+    if (ParGCUseLocalOverflow) {
+      _overflow_stacks[i] = new (ResourceObj::C_HEAP) GrowableArray<oop>(512, true);
+      guarantee(_overflow_stacks[i] != NULL, "Overflow Stack allocation failure.");
+    } else {
+      _overflow_stacks[i] = NULL;
+    }
+  }
+
   if (UsePerfData) {
     EXCEPTION_MARK;
     ResourceMark rm;
@@ -738,7 +794,7 @@
   ParallelTaskTerminator _term(workers->total_workers(), task_queues());
   ParScanThreadStateSet thread_state_set(workers->total_workers(),
                                          *to(), *this, *_next_gen, *task_queues(),
-                                         desired_plab_sz(), _term);
+                                         _overflow_stacks, desired_plab_sz(), _term);
 
   ParNewGenTask tsk(this, _next_gen, reserved().end(), &thread_state_set);
   int n_workers = workers->total_workers();
@@ -1169,36 +1225,77 @@
 }
 #endif
 
+// In case we are using compressed oops, we need to be careful.
+// If the object being pushed is an object array, then its length
+// field keeps track of the "grey boundary" at which the next
+// incremental scan will be done (see ParGCArrayScanChunk).
+// When using compressed oops, this length field is kept in the
+// lower 32 bits of the erstwhile klass word and cannot be used
+// for the overflow chaining pointer (OCP below). As such the OCP
+// would itself need to be compressed into the top 32-bits in this
+// case. Unfortunately, see below, in the event that we have a
+// promotion failure, the node to be pushed on the list can be
+// outside of the Java heap, so the heap-based pointer compression
+// would not work (we would have potential aliasing between C-heap
+// and Java-heap pointers). For this reason, when using compressed
+// oops, we simply use a worker-thread-local, non-shared overflow
+// list in the form of a growable array, with a slightly different
+// overflow stack draining strategy. If/when we start using fat
+// stacks here, we can go back to using (fat) pointer chains
+// (although some performance comparisons would be useful since
+// single global lists have their own performance disadvantages
+// as we were made painfully aware not long ago, see 6786503).
 #define BUSY (oop(0x1aff1aff))
 void ParNewGeneration::push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state) {
-  // if the object has been forwarded to itself, then we cannot
-  // use the klass pointer for the linked list.  Instead we have
-  // to allocate an oopDesc in the C-Heap and use that for the linked list.
-  // XXX This is horribly inefficient when a promotion failure occurs
-  // and should be fixed. XXX FIX ME !!!
+  assert(is_in_reserved(from_space_obj), "Should be from this generation");
+  if (ParGCUseLocalOverflow) {
+    // In the case of compressed oops, we use a private, not-shared
+    // overflow stack.
+    par_scan_state->push_on_overflow_stack(from_space_obj);
+  } else {
+    assert(!UseCompressedOops, "Error");
+    // if the object has been forwarded to itself, then we cannot
+    // use the klass pointer for the linked list.  Instead we have
+    // to allocate an oopDesc in the C-Heap and use that for the linked list.
+    // XXX This is horribly inefficient when a promotion failure occurs
+    // and should be fixed. XXX FIX ME !!!
 #ifndef PRODUCT
-  Atomic::inc_ptr(&_num_par_pushes);
-  assert(_num_par_pushes > 0, "Tautology");
+    Atomic::inc_ptr(&_num_par_pushes);
+    assert(_num_par_pushes > 0, "Tautology");
 #endif
-  if (from_space_obj->forwardee() == from_space_obj) {
-    oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1);
-    listhead->forward_to(from_space_obj);
-    from_space_obj = listhead;
+    if (from_space_obj->forwardee() == from_space_obj) {
+      oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1);
+      listhead->forward_to(from_space_obj);
+      from_space_obj = listhead;
+    }
+    oop observed_overflow_list = _overflow_list;
+    oop cur_overflow_list;
+    do {
+      cur_overflow_list = observed_overflow_list;
+      if (cur_overflow_list != BUSY) {
+        from_space_obj->set_klass_to_list_ptr(cur_overflow_list);
+      } else {
+        from_space_obj->set_klass_to_list_ptr(NULL);
+      }
+      observed_overflow_list =
+        (oop)Atomic::cmpxchg_ptr(from_space_obj, &_overflow_list, cur_overflow_list);
+    } while (cur_overflow_list != observed_overflow_list);
   }
-  oop observed_overflow_list = _overflow_list;
-  oop cur_overflow_list;
-  do {
-    cur_overflow_list = observed_overflow_list;
-    if (cur_overflow_list != BUSY) {
-      from_space_obj->set_klass_to_list_ptr(cur_overflow_list);
-    } else {
-      from_space_obj->set_klass_to_list_ptr(NULL);
-    }
-    observed_overflow_list =
-      (oop)Atomic::cmpxchg_ptr(from_space_obj, &_overflow_list, cur_overflow_list);
-  } while (cur_overflow_list != observed_overflow_list);
 }
 
+bool ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {
+  bool res;
+
+  if (ParGCUseLocalOverflow) {
+    res = par_scan_state->take_from_overflow_stack();
+  } else {
+    assert(!UseCompressedOops, "Error");
+    res = take_from_overflow_list_work(par_scan_state);
+  }
+  return res;
+}
+
+
 // *NOTE*: The overflow list manipulation code here and
 // in CMSCollector:: are very similar in shape,
 // except that in the CMS case we thread the objects
@@ -1213,14 +1310,14 @@
 // similar changes might be needed.
 // See CMSCollector::par_take_from_overflow_list() for
 // more extensive documentation comments.
-bool
-ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {
+bool ParNewGeneration::take_from_overflow_list_work(ParScanThreadState* par_scan_state) {
   ObjToScanQueue* work_q = par_scan_state->work_queue();
-  assert(work_q->size() == 0, "Should first empty local work queue");
   // How many to take?
-  size_t objsFromOverflow = MIN2((size_t)work_q->max_elems()/4,
+  size_t objsFromOverflow = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
                                  (size_t)ParGCDesiredObjsFromOverflowList);
 
+  assert(par_scan_state->overflow_stack() == NULL, "Error");
+  assert(!UseCompressedOops, "Error");
   if (_overflow_list == NULL) return false;
 
   // Otherwise, there was something there; try claiming the list.
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,8 +33,8 @@
 // but they must be here to allow ParScanClosure::do_oop_work to be defined
 // in genOopClosures.inline.hpp.
 
-typedef OopTaskQueue    ObjToScanQueue;
-typedef OopTaskQueueSet ObjToScanQueueSet;
+typedef OopTaskQueue       ObjToScanQueue;
+typedef OopTaskQueueSet    ObjToScanQueueSet;
 
 // Enable this to get push/pop/steal stats.
 const int PAR_STATS_ENABLED = 0;
@@ -55,6 +55,7 @@
   friend class ParScanThreadStateSet;
  private:
   ObjToScanQueue *_work_queue;
+  GrowableArray<oop>* _overflow_stack;
 
   ParGCAllocBuffer _to_space_alloc_buffer;
 
@@ -79,6 +80,9 @@
   Space* _to_space;
   Space* to_space() { return _to_space; }
 
+  ParNewGeneration* _young_gen;
+  ParNewGeneration* young_gen() const { return _young_gen; }
+
   Generation* _old_gen;
   Generation* old_gen() { return _old_gen; }
 
@@ -112,7 +116,9 @@
 
   ParScanThreadState(Space* to_space_, ParNewGeneration* gen_,
                      Generation* old_gen_, int thread_num_,
-                     ObjToScanQueueSet* work_queue_set_, size_t desired_plab_sz_,
+                     ObjToScanQueueSet* work_queue_set_,
+                     GrowableArray<oop>** overflow_stack_set_,
+                     size_t desired_plab_sz_,
                      ParallelTaskTerminator& term_);
 
  public:
@@ -134,6 +140,11 @@
   // Decrease queue size below "max_size".
   void trim_queues(int max_size);
 
+  // Private overflow stack usage
+  GrowableArray<oop>* overflow_stack() { return _overflow_stack; }
+  bool take_from_overflow_stack();
+  void push_on_overflow_stack(oop p);
+
   // Is new_obj a candidate for scan_partial_array_and_push_remainder method.
   inline bool should_be_partially_scanned(oop new_obj, oop old_obj) const;
 
@@ -287,9 +298,12 @@
         char pad[64 - sizeof(ObjToScanQueue)];  // prevent false sharing
   };
 
-  // The per-thread work queues, available here for stealing.
+  // The per-worker-thread work queues
   ObjToScanQueueSet* _task_queues;
 
+  // Per-worker-thread local overflow stacks
+  GrowableArray<oop>** _overflow_stacks;
+
   // Desired size of survivor space plab's
   PLABStats _plab_stats;
 
@@ -378,13 +392,17 @@
   NOT_PRODUCT(int _overflow_counter;)
   NOT_PRODUCT(bool should_simulate_overflow();)
 
+  // Accessor for overflow list
+  oop overflow_list() { return _overflow_list; }
+
   // Push the given (from-space) object on the global overflow list.
   void push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state);
 
   // If the global overflow list is non-empty, move some tasks from it
-  // onto "work_q" (which must be empty).  No more than 1/4 of the
-  // max_elems of "work_q" are moved.
+  // onto "work_q" (which need not be empty).  No more than 1/4 of the
+  // available space on "work_q" is used.
   bool take_from_overflow_list(ParScanThreadState* par_scan_state);
+  bool take_from_overflow_list_work(ParScanThreadState* par_scan_state);
 
   // The task queues to be used by parallel GC threads.
   ObjToScanQueueSet* task_queues() {
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -78,7 +78,7 @@
   }
 
   // Card marks are not precise. The current system can leave us with
-  // a mismash of precise marks and begining of object marks. This means
+  // a mismash of precise marks and beginning of object marks. This means
   // we test for missing precise marks first. If any are found, we don't
   // fail unless the object head is also unmarked.
   virtual void do_object(oop obj) {
@@ -258,7 +258,7 @@
     if (!start_array->object_starts_in_range(slice_start, slice_end)) {
       continue;
     }
-    // Update our begining addr
+    // Update our beginning addr
     HeapWord* first_object = start_array->object_start(slice_start);
     debug_only(oop* first_object_within_slice = (oop*) first_object;)
     if (first_object < slice_start) {
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -127,7 +127,7 @@
   // Optimized for finding the first object that crosses into
   // a given block. The blocks contain the offset of the last
   // object in that block. Scroll backwards by one, and the first
-  // object hit should be at the begining of the block
+  // object hit should be at the beginning of the block
   HeapWord* object_start(HeapWord* addr) const {
     assert(_covered_region.contains(addr), "Must be in covered region");
     jbyte* block = block_for_addr(addr);
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,12 +104,38 @@
                   og_min_size, og_max_size,
                   yg_min_size, yg_max_size);
 
+  const size_t total_reserved = pg_max_size + og_max_size + yg_max_size;
+  char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
+
   // The main part of the heap (old gen + young gen) can often use a larger page
   // size than is needed or wanted for the perm gen.  Use the "compound
   // alignment" ReservedSpace ctor to avoid having to use the same page size for
   // all gens.
+
   ReservedHeapSpace heap_rs(pg_max_size, pg_align, og_max_size + yg_max_size,
-                            og_align);
+                            og_align, addr);
+
+  if (UseCompressedOops) {
+    if (addr != NULL && !heap_rs.is_reserved()) {
+      // Failed to reserve at specified address - the requested memory
+      // region is taken already, for example, by 'java' launcher.
+      // Try again to reserver heap higher.
+      addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
+      ReservedHeapSpace heap_rs0(pg_max_size, pg_align, og_max_size + yg_max_size,
+                                 og_align, addr);
+      if (addr != NULL && !heap_rs0.is_reserved()) {
+        // Failed to reserve at specified address again - give up.
+        addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
+        assert(addr == NULL, "");
+        ReservedHeapSpace heap_rs1(pg_max_size, pg_align, og_max_size + yg_max_size,
+                                   og_align, addr);
+        heap_rs = heap_rs1;
+      } else {
+        heap_rs = heap_rs0;
+      }
+    }
+  }
+
   os::trace_page_sizes("ps perm", pg_min_size, pg_max_size, pg_page_sz,
                        heap_rs.base(), pg_max_size);
   os::trace_page_sizes("ps main", og_min_size + yg_min_size,
@@ -799,6 +825,7 @@
   if (young_gen()->is_in_reserved(addr)) {
     assert(young_gen()->is_in(addr),
            "addr should be in allocated part of young gen");
+    if (Debugging)  return NULL;  // called from find() in debug.cpp
     Unimplemented();
   } else if (old_gen()->is_in_reserved(addr)) {
     assert(old_gen()->is_in(addr),
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/prefetchQueue.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/prefetchQueue.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -26,7 +26,7 @@
 // PrefetchQueue is a FIFO queue of variable length (currently 8).
 //
 // We need to examine the performance penalty of variable lengths.
-// We may also want to split this into cpu dependant bits.
+// We may also want to split this into cpu dependent bits.
 //
 
 const int PREFETCH_QUEUE_SIZE  = 8;
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -125,6 +125,8 @@
     perm_gen->verify_object_start_array();
   }
 
+  heap->pre_full_gc_dump();
+
   // Filled in below to track the state of the young gen after the collection.
   bool eden_empty;
   bool survivors_empty;
@@ -363,6 +365,8 @@
     Universe::print_heap_after_gc();
   }
 
+  heap->post_full_gc_dump();
+
 #ifdef TRACESPINNING
   ParallelTaskTerminator::print_termination_counts();
 #endif
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -508,6 +508,7 @@
   assert(destination <= target_end, "sanity");
   assert(destination + _region_data[src_region].data_size() > target_end,
     "region should not fit into target space");
+  assert(is_region_aligned(target_end), "sanity");
 
   size_t split_region = src_region;
   HeapWord* split_destination = destination;
@@ -538,14 +539,12 @@
     //         max(top, max(new_top, clear_top))
     //
     // where clear_top is a new field in SpaceInfo.  Would have to set clear_top
-    // to destination + partial_obj_size, where both have the values passed to
-    // this routine.
+    // to target_end.
     const RegionData* const sr = region(split_region);
     const size_t beg_idx =
       addr_to_region_idx(region_align_up(sr->destination() +
                                          sr->partial_obj_size()));
-    const size_t end_idx =
-      addr_to_region_idx(region_align_up(destination + partial_obj_size));
+    const size_t end_idx = addr_to_region_idx(target_end);
 
     if (TraceParallelOldGCSummaryPhase) {
         gclog_or_tty->print_cr("split:  clearing source_region field in ["
@@ -1982,6 +1981,8 @@
     heap->record_gen_tops_before_GC();
   }
 
+  heap->pre_full_gc_dump();
+
   _print_phases = PrintGCDetails && PrintParallelOldGCPhaseTimes;
 
   // Make sure data structures are sane, make the heap parsable, and do other
@@ -2204,6 +2205,8 @@
     gc_task_manager()->print_task_time_stamps();
   }
 
+  heap->post_full_gc_dump();
+
 #ifdef TRACESPINNING
   ParallelTaskTerminator::print_termination_counts();
 #endif
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  *
  */
 
-/* Copyright 1992 Sun Microsystems, Inc. and Stanford University.
+/* Copyright 1992-2009 Sun Microsystems, Inc. and Stanford University.
    See the LICENSE file for license information. */
 
 # include "incls/_precompiled.incl"
--- a/hotspot/src/share/vm/gc_implementation/shared/ageTable.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/ageTable.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  *
  */
 
-/* Copyright 1992 Sun Microsystems, Inc. and Stanford University.
+/* Copyright 1992-2009 Sun Microsystems, Inc. and Stanford University.
    See the LICENSE file for license information. */
 
 // Age table for adaptive feedback-mediated tenuring (scavenging)
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 
 /*
- * Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,7 +74,7 @@
   for (int i = 0; i < lgrp_spaces()->length(); i++) {
     LGRPSpace *ls = lgrp_spaces()->at(i);
     MutableSpace *s = ls->space();
-    if (s->top() < top()) { // For all spaces preceeding the one containing top()
+    if (s->top() < top()) { // For all spaces preceding the one containing top()
       if (s->free_in_words() > 0) {
         size_t area_touched_words = pointer_delta(s->end(), s->top());
         CollectedHeap::fill_with_object(s->top(), area_touched_words);
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -121,7 +121,7 @@
     // make the heap parsable (no need to retire TLABs)
     ch->ensure_parsability(false);
   }
-  HeapInspection::heap_inspection(_out);
+  HeapInspection::heap_inspection(_out, _need_prologue /* need_prologue */);
 }
 
 
--- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -112,13 +112,16 @@
  private:
   outputStream* _out;
   bool _full_gc;
+  bool _need_prologue;
  public:
-  VM_GC_HeapInspection(outputStream* out, bool request_full_gc) :
+  VM_GC_HeapInspection(outputStream* out, bool request_full_gc,
+                       bool need_prologue) :
     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
                     0 /* total full collections, dummy, ignored */,
                     request_full_gc) {
     _out = out;
     _full_gc = request_full_gc;
+    _need_prologue = need_prologue;
   }
 
   ~VM_GC_HeapInspection() {}
--- a/hotspot/src/share/vm/gc_interface/collectedHeap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_interface/collectedHeap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -294,3 +294,29 @@
     ThreadLocalAllocBuffer::resize_all_tlabs();
   }
 }
+
+void CollectedHeap::pre_full_gc_dump() {
+  if (HeapDumpBeforeFullGC) {
+    TraceTime tt("Heap Dump: ", PrintGCDetails, false, gclog_or_tty);
+    // We are doing a "major" collection and a heap dump before
+    // major collection has been requested.
+    HeapDumper::dump_heap();
+  }
+  if (PrintClassHistogramBeforeFullGC) {
+    TraceTime tt("Class Histogram: ", PrintGCDetails, true, gclog_or_tty);
+    VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */, false /* ! prologue */);
+    inspector.doit();
+  }
+}
+
+void CollectedHeap::post_full_gc_dump() {
+  if (HeapDumpAfterFullGC) {
+    TraceTime tt("Heap Dump", PrintGCDetails, false, gclog_or_tty);
+    HeapDumper::dump_heap();
+  }
+  if (PrintClassHistogramAfterFullGC) {
+    TraceTime tt("Class Histogram", PrintGCDetails, true, gclog_or_tty);
+    VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */, false /* ! prologue */);
+    inspector.doit();
+  }
+}
--- a/hotspot/src/share/vm/gc_interface/collectedHeap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_interface/collectedHeap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -514,6 +514,10 @@
   // Perform any cleanup actions necessary before allowing a verification.
   virtual void prepare_for_verify() = 0;
 
+  // Generate any dumps preceding or following a full gc
+  void pre_full_gc_dump();
+  void post_full_gc_dump();
+
   virtual void print() const = 0;
   virtual void print_on(outputStream* st) const = 0;
 
--- a/hotspot/src/share/vm/gc_interface/collectedHeap.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_interface/collectedHeap.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/gc_interface/gcCause.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/gc_interface/gcCause.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -60,7 +60,7 @@
     _old_generation_too_full_to_scavenge,
     _adaptive_size_policy,
 
-    _g1_inc_collection_pause, _g1_pop_region_collection_pause,
+    _g1_inc_collection_pause,
 
     _last_ditch_collection,
     _last_gc_cause
--- a/hotspot/src/share/vm/includeDB_compiler2	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/includeDB_compiler2	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/includeDB_core	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/includeDB_core	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -176,7 +176,7 @@
 arguments.cpp                           oop.inline.hpp
 arguments.cpp                           os_<os_family>.inline.hpp
 arguments.cpp                           universe.inline.hpp
-arguments.cpp                           vm_version_<arch_model>.hpp
+arguments.cpp                           vm_version_<arch>.hpp
 
 arguments.hpp                           java.hpp
 arguments.hpp                           perfData.hpp
@@ -241,7 +241,7 @@
 assembler.hpp                           register_<arch>.hpp
 assembler.hpp                           relocInfo.hpp
 assembler.hpp                           top.hpp
-assembler.hpp                           vm_version_<arch_model>.hpp
+assembler.hpp                           vm_version_<arch>.hpp
 
 assembler.inline.hpp                    assembler.hpp
 assembler.inline.hpp                    codeBuffer.hpp
@@ -280,7 +280,7 @@
 
 atomic_<os_arch>.inline.hpp             atomic.hpp
 atomic_<os_arch>.inline.hpp             os.hpp
-atomic_<os_arch>.inline.hpp             vm_version_<arch_model>.hpp
+atomic_<os_arch>.inline.hpp             vm_version_<arch>.hpp
 
 // attachListener is jck optional, put cpp deps in includeDB_features
 
@@ -474,6 +474,7 @@
 cardTableModRefBS.cpp                   mutexLocker.hpp
 cardTableModRefBS.cpp                   sharedHeap.hpp
 cardTableModRefBS.cpp                   space.hpp
+cardTableModRefBS.cpp                   space.inline.hpp
 cardTableModRefBS.cpp                   universe.hpp
 cardTableModRefBS.cpp                   virtualspace.hpp
 
@@ -2094,6 +2095,7 @@
 interp_masm_<arch_model>.cpp            interpreterRuntime.hpp
 interp_masm_<arch_model>.cpp            interpreter.hpp
 interp_masm_<arch_model>.cpp            jvmtiExport.hpp
+interp_masm_<arch_model>.cpp            jvmtiRedefineClassesTrace.hpp
 interp_masm_<arch_model>.cpp            jvmtiThreadState.hpp
 interp_masm_<arch_model>.cpp            markOop.hpp
 interp_masm_<arch_model>.cpp            methodDataOop.hpp
@@ -2176,7 +2178,7 @@
 interpreterRuntime.cpp                  threadCritical.hpp
 interpreterRuntime.cpp                  universe.inline.hpp
 interpreterRuntime.cpp                  vmSymbols.hpp
-interpreterRuntime.cpp                  vm_version_<arch_model>.hpp
+interpreterRuntime.cpp                  vm_version_<arch>.hpp
 
 interpreterRuntime.hpp                  bytecode.hpp
 interpreterRuntime.hpp                  frame.inline.hpp
@@ -2279,7 +2281,7 @@
 java.cpp                                universe.hpp
 java.cpp                                vmError.hpp
 java.cpp                                vm_operations.hpp
-java.cpp                                vm_version_<arch_model>.hpp
+java.cpp                                vm_version_<arch>.hpp
 java.cpp                                vtune.hpp
 
 java.hpp                                os.hpp
@@ -3152,6 +3154,8 @@
 oopsHierarchy.cpp                       thread_<os_family>.inline.hpp
 
 orderAccess.cpp                         orderAccess.hpp
+orderAccess.cpp                         stubRoutines.hpp
+orderAccess.cpp                         thread.hpp
 
 orderAccess.hpp                         allocation.hpp
 orderAccess.hpp                         os.hpp
@@ -3485,7 +3489,7 @@
 register_<arch>.cpp                     register_<arch>.hpp
 
 register_<arch>.hpp                     register.hpp
-register_<arch>.hpp                     vm_version_<arch_model>.hpp
+register_<arch>.hpp                     vm_version_<arch>.hpp
 
 registerMap.hpp                         globalDefinitions.hpp
 registerMap.hpp                         register_<arch>.hpp
@@ -3670,6 +3674,7 @@
 sharedRuntime.cpp                       interpreter.hpp
 sharedRuntime.cpp                       javaCalls.hpp
 sharedRuntime.cpp                       jvmtiExport.hpp
+sharedRuntime.cpp                       jvmtiRedefineClassesTrace.hpp
 sharedRuntime.cpp                       nativeInst_<arch>.hpp
 sharedRuntime.cpp                       nativeLookup.hpp
 sharedRuntime.cpp                       oop.inline.hpp
@@ -3699,6 +3704,7 @@
 sharedRuntime_<arch_model>.cpp          debugInfoRec.hpp
 sharedRuntime_<arch_model>.cpp          icBuffer.hpp
 sharedRuntime_<arch_model>.cpp          interpreter.hpp
+sharedRuntime_<arch_model>.cpp          jvmtiRedefineClassesTrace.hpp
 sharedRuntime_<arch_model>.cpp          sharedRuntime.hpp
 sharedRuntime_<arch_model>.cpp          vframeArray.hpp
 sharedRuntime_<arch_model>.cpp          vmreg_<arch>.inline.hpp
@@ -3835,7 +3841,7 @@
 statSampler.cpp                         statSampler.hpp
 statSampler.cpp                         systemDictionary.hpp
 statSampler.cpp                         vmSymbols.hpp
-statSampler.cpp                         vm_version_<arch_model>.hpp
+statSampler.cpp                         vm_version_<arch>.hpp
 
 statSampler.hpp                         perfData.hpp
 statSampler.hpp                         task.hpp
@@ -4579,22 +4585,23 @@
 vm_version.cpp                          arguments.hpp
 vm_version.cpp                          oop.inline.hpp
 vm_version.cpp                          universe.hpp
-vm_version.cpp                          vm_version_<arch_model>.hpp
+vm_version.cpp                          vm_version_<arch>.hpp
 
 vm_version.hpp                          allocation.hpp
 vm_version.hpp                          ostream.hpp
 
-vm_version_<arch_model>.cpp             assembler_<arch>.inline.hpp
-vm_version_<arch_model>.cpp             java.hpp
-vm_version_<arch_model>.cpp             os_<os_family>.inline.hpp
-vm_version_<arch_model>.cpp             resourceArea.hpp
-vm_version_<arch_model>.cpp             stubCodeGenerator.hpp
-vm_version_<arch_model>.cpp             vm_version_<arch_model>.hpp
-
-vm_version_<arch_model>.hpp             globals_extension.hpp
-vm_version_<arch_model>.hpp             vm_version.hpp
-
-vm_version_<os_arch>.cpp                vm_version_<arch_model>.hpp
+vm_version_<arch>.cpp                   assembler_<arch>.inline.hpp
+vm_version_<arch>.cpp                   java.hpp
+vm_version_<arch>.cpp                   os_<os_family>.inline.hpp
+vm_version_<arch>.cpp                   resourceArea.hpp
+vm_version_<arch>.cpp                   stubCodeGenerator.hpp
+vm_version_<arch>.cpp                   vm_version_<arch>.hpp
+
+vm_version_<arch>.hpp                   globals_extension.hpp
+vm_version_<arch>.hpp                   vm_version.hpp
+
+vm_version_<os_arch>.cpp                os.hpp
+vm_version_<os_arch>.cpp                vm_version_<arch>.hpp
 
 vmreg.cpp                               assembler.hpp
 vmreg.cpp                               vmreg.hpp
--- a/hotspot/src/share/vm/includeDB_features	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/includeDB_features	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/includeDB_gc	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/includeDB_gc	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright 2001-2005 Sun Microsystems, Inc.  All Rights Reserved.
+// Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,12 @@
 
 collectedHeap.cpp                       collectedHeap.hpp
 collectedHeap.cpp                       collectedHeap.inline.hpp
+collectedHeap.cpp                       heapDumper.hpp
 collectedHeap.cpp                       init.hpp
 collectedHeap.cpp                       oop.inline.hpp
 collectedHeap.cpp                       systemDictionary.hpp
 collectedHeap.cpp                       thread_<os_family>.inline.hpp
+collectedHeap.cpp                       vmGCOperations.hpp
 
 collectedHeap.hpp                       allocation.hpp
 collectedHeap.hpp                       barrierSet.hpp
--- a/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the abstract interpreter and the abstract interpreter generator.
 
 // Organization of the interpreter(s). There exists two different interpreters in hotpot
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2642,7 +2642,7 @@
         // two interpreted frames). We need to save the current arguments in C heap so that
         // the deoptimized frame when it restarts can copy the arguments to its expression
         // stack and re-execute the call. We also have to notify deoptimization that this
-        // has occured and to pick the preerved args copy them to the deoptimized frame's
+        // has occurred and to pick the preserved args copy them to the deoptimized frame's
         // java expression stack. Yuck.
         //
         THREAD->popframe_preserve_args(in_ByteSize(METHOD->size_of_parameters() * wordSize),
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file holds platform-independant bodies of inline functions for the C++ based interpreter
+// This file holds platform-independent bodies of inline functions for the C++ based interpreter
 
 #ifdef CC_INTERP
 
--- a/hotspot/src/share/vm/interpreter/cppInterpreter.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/cppInterpreter.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -24,7 +24,7 @@
 
 #ifdef CC_INTERP
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the c++ interpreter
 
 class CppInterpreter: public AbstractInterpreter {
--- a/hotspot/src/share/vm/interpreter/cppInterpreterGenerator.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/cppInterpreterGenerator.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the template interpreter generator.
 
 #ifdef CC_INTERP
--- a/hotspot/src/share/vm/interpreter/interpreter.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/interpreter.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the interpreter and the interpreter generator.
 
 //------------------------------------------------------------------------------------------------------------------------
--- a/hotspot/src/share/vm/interpreter/interpreterGenerator.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/interpreterGenerator.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the interpreter generator.
 
 
--- a/hotspot/src/share/vm/interpreter/invocationCounter.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/invocationCounter.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -47,6 +47,8 @@
   // executed many more times before re-entering the VM.
   int old_count = count();
   int new_count = MIN2(old_count, (int) (CompileThreshold / 2));
+  // prevent from going to zero, to distinguish from never-executed methods
+  if (new_count == 0)  new_count = 1;
   if (old_count != new_count)  set(state(), new_count);
 }
 
--- a/hotspot/src/share/vm/interpreter/rewriter.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/rewriter.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/interpreter/templateInterpreter.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/templateInterpreter.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the template interpreter and the template interpreter generator.
 
 #ifndef CC_INTERP
--- a/hotspot/src/share/vm/interpreter/templateInterpreterGenerator.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/interpreter/templateInterpreterGenerator.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file contains the platform-independant parts
+// This file contains the platform-independent parts
 // of the template interpreter generator.
 
 #ifndef CC_INTERP
--- a/hotspot/src/share/vm/libadt/dict.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/libadt/dict.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -306,7 +306,7 @@
 // Convert string to hash key.  This algorithm implements a universal hash
 // function with the multipliers frozen (ok, so it's not universal).  The
 // multipliers (and allowable characters) are all odd, so the resultant sum
-// is odd - guarenteed not divisible by any power of two, so the hash tables
+// is odd - guaranteed not divisible by any power of two, so the hash tables
 // can be any power of two with good results.  Also, I choose multipliers
 // that have only 2 bits set (the low is always set to be odd) so
 // multiplication requires only shifts and adds.  Characters are required to
@@ -326,7 +326,7 @@
 }
 
 //------------------------------hashptr--------------------------------------
-// Slimey cheap hash function; no guarenteed performance.  Better than the
+// Slimey cheap hash function; no guaranteed performance.  Better than the
 // default for pointers, especially on MS-DOS machines.
 int hashptr(const void *key) {
 #ifdef __TURBOC__
@@ -336,7 +336,7 @@
 #endif
 }
 
-// Slimey cheap hash function; no guarenteed performance.
+// Slimey cheap hash function; no guaranteed performance.
 int hashkey(const void *key) {
   return (intptr_t)key;
 }
--- a/hotspot/src/share/vm/libadt/dict.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/libadt/dict.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -86,10 +86,10 @@
 
 // Hashing functions
 int hashstr(const void *s);        // Nice string hash
-// Slimey cheap hash function; no guarenteed performance.  Better than the
+// Slimey cheap hash function; no guaranteed performance.  Better than the
 // default for pointers, especially on MS-DOS machines.
 int hashptr(const void *key);
-// Slimey cheap hash function; no guarenteed performance.
+// Slimey cheap hash function; no guaranteed performance.
 int hashkey(const void *key);
 
 // Key comparators
--- a/hotspot/src/share/vm/libadt/port.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/libadt/port.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/blockOffsetTable.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/blockOffsetTable.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -235,7 +235,7 @@
   };
 
   static size_t power_to_cards_back(uint i) {
-    return 1 << (LogBase * i);
+    return (size_t)(1 << (LogBase * i));
   }
   static size_t power_to_words_back(uint i) {
     return power_to_cards_back(i) * N_words;
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -217,15 +217,28 @@
       (HeapWord*) align_size_up((uintptr_t)new_end, _page_size);
     assert(new_end_aligned >= (HeapWord*) new_end,
            "align up, but less");
+    // Check the other regions (excludes "ind") to ensure that
+    // the new_end_aligned does not intrude onto the committed
+    // space of another region.
     int ri = 0;
     for (ri = 0; ri < _cur_covered_regions; ri++) {
       if (ri != ind) {
         if (_committed[ri].contains(new_end_aligned)) {
-          assert((new_end_aligned >= _committed[ri].start()) &&
-                 (_committed[ri].start() > _committed[ind].start()),
+          // The prior check included in the assert
+          // (new_end_aligned >= _committed[ri].start())
+          // is redundant with the "contains" test.
+          // Any region containing the new end
+          // should start at or beyond the region found (ind)
+          // for the new end (committed regions are not expected to
+          // be proper subsets of other committed regions).
+          assert(_committed[ri].start() >= _committed[ind].start(),
                  "New end of committed region is inconsistent");
           new_end_aligned = _committed[ri].start();
-          assert(new_end_aligned > _committed[ind].start(),
+          // new_end_aligned can be equal to the start of its
+          // committed region (i.e., of "ind") if a second
+          // region following "ind" also start at the same location
+          // as "ind".
+          assert(new_end_aligned >= _committed[ind].start(),
             "New end of committed region is before start");
           debug_only(collided = true;)
           // Should only collide with 1 region
@@ -343,18 +356,62 @@
   inline_write_ref_field(field, newVal);
 }
 
+/*
+   Claimed and deferred bits are used together in G1 during the evacuation
+   pause. These bits can have the following state transitions:
+   1. The claimed bit can be put over any other card state. Except that
+      the "dirty -> dirty and claimed" transition is checked for in
+      G1 code and is not used.
+   2. Deferred bit can be set only if the previous state of the card
+      was either clean or claimed. mark_card_deferred() is wait-free.
+      We do not care if the operation is be successful because if
+      it does not it will only result in duplicate entry in the update
+      buffer because of the "cache-miss". So it's not worth spinning.
+ */
+
 
 bool CardTableModRefBS::claim_card(size_t card_index) {
   jbyte val = _byte_map[card_index];
-  if (val != claimed_card_val()) {
-    jbyte res = Atomic::cmpxchg((jbyte) claimed_card_val(), &_byte_map[card_index], val);
-    if (res == val)
+  assert(val != dirty_card_val(), "Shouldn't claim a dirty card");
+  while (val == clean_card_val() ||
+         (val & (clean_card_mask_val() | claimed_card_val())) != claimed_card_val()) {
+    jbyte new_val = val;
+    if (val == clean_card_val()) {
+      new_val = (jbyte)claimed_card_val();
+    } else {
+      new_val = val | (jbyte)claimed_card_val();
+    }
+    jbyte res = Atomic::cmpxchg(new_val, &_byte_map[card_index], val);
+    if (res == val) {
       return true;
-    else return false;
+    }
+    val = res;
   }
   return false;
 }
 
+bool CardTableModRefBS::mark_card_deferred(size_t card_index) {
+  jbyte val = _byte_map[card_index];
+  // It's already processed
+  if ((val & (clean_card_mask_val() | deferred_card_val())) == deferred_card_val()) {
+    return false;
+  }
+  // Cached bit can be installed either on a clean card or on a claimed card.
+  jbyte new_val = val;
+  if (val == clean_card_val()) {
+    new_val = (jbyte)deferred_card_val();
+  } else {
+    if (val & claimed_card_val()) {
+      new_val = val | (jbyte)deferred_card_val();
+    }
+  }
+  if (new_val != val) {
+    Atomic::cmpxchg(new_val, &_byte_map[card_index], val);
+  }
+  return true;
+}
+
+
 void CardTableModRefBS::non_clean_card_iterate(Space* sp,
                                                MemRegion mr,
                                                DirtyCardToOopClosure* dcto_cl,
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,11 +52,15 @@
 
   enum CardValues {
     clean_card                  = -1,
+    // The mask contains zeros in places for all other values.
+    clean_card_mask             = clean_card - 31,
+
     dirty_card                  =  0,
     precleaned_card             =  1,
-    claimed_card                =  3,
-    last_card                   =  4,
-    CT_MR_BS_last_reserved      = 10
+    claimed_card                =  2,
+    deferred_card               =  4,
+    last_card                   =  8,
+    CT_MR_BS_last_reserved      = 16
   };
 
   // dirty and precleaned are equivalent wrt younger_refs_iter.
@@ -254,9 +258,11 @@
   };
 
   static int clean_card_val()      { return clean_card; }
+  static int clean_card_mask_val() { return clean_card_mask; }
   static int dirty_card_val()      { return dirty_card; }
   static int claimed_card_val()    { return claimed_card; }
   static int precleaned_card_val() { return precleaned_card; }
+  static int deferred_card_val()   { return deferred_card; }
 
   // For RTTI simulation.
   bool is_a(BarrierSet::Name bsn) {
@@ -329,7 +335,8 @@
   }
 
   bool is_card_claimed(size_t card_index) {
-    return _byte_map[card_index] == claimed_card_val();
+    jbyte val = _byte_map[card_index];
+    return (val & (clean_card_mask_val() | claimed_card_val())) == claimed_card_val();
   }
 
   bool claim_card(size_t card_index);
@@ -338,6 +345,13 @@
     return _byte_map[card_index] == clean_card_val();
   }
 
+  bool is_card_deferred(size_t card_index) {
+    jbyte val = _byte_map[card_index];
+    return (val & (clean_card_mask_val() | deferred_card_val())) == deferred_card_val();
+  }
+
+  bool mark_card_deferred(size_t card_index);
+
   // Card marking array base (adjusted for heap low boundary)
   // This would be the 0th element of _byte_map, if the heap started at 0x0.
   // But since the heap starts at some higher address, this points to somewhere
@@ -434,6 +448,10 @@
     return byte_for(p) - _byte_map;
   }
 
+  const jbyte* byte_for_index(const size_t card_index) const {
+    return _byte_map + card_index;
+  }
+
   void verify();
   void verify_guard();
 
--- a/hotspot/src/share/vm/memory/filemap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/filemap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -35,14 +35,14 @@
 extern address JVM_FunctionAtStart();
 extern address JVM_FunctionAtEnd();
 
-// Complain and stop. All error conditions occuring during the writing of
+// Complain and stop. All error conditions occurring during the writing of
 // an archive file should stop the process.  Unrecoverable errors during
 // the reading of the archive file should stop the process.
 
 static void fail(const char *msg, va_list ap) {
   // This occurs very early during initialization: tty is not initialized.
   jio_fprintf(defaultStream::error_stream(),
-              "An error has occured while processing the"
+              "An error has occurred while processing the"
               " shared archive file.\n");
   jio_vfprintf(defaultStream::error_stream(), msg, ap);
   jio_fprintf(defaultStream::error_stream(), "\n");
--- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -218,6 +218,31 @@
     heap_address -= total_reserved;
   } else {
     heap_address = NULL;  // any address will do.
+    if (UseCompressedOops) {
+      heap_address = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
+      *_total_reserved = total_reserved;
+      *_n_covered_regions = n_covered_regions;
+      *heap_rs = ReservedHeapSpace(total_reserved, alignment,
+                                   UseLargePages, heap_address);
+
+      if (heap_address != NULL && !heap_rs->is_reserved()) {
+        // Failed to reserve at specified address - the requested memory
+        // region is taken already, for example, by 'java' launcher.
+        // Try again to reserver heap higher.
+        heap_address = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
+        *heap_rs = ReservedHeapSpace(total_reserved, alignment,
+                                     UseLargePages, heap_address);
+
+        if (heap_address != NULL && !heap_rs->is_reserved()) {
+          // Failed to reserve at specified address again - give up.
+          heap_address = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
+          assert(heap_address == NULL, "");
+          *heap_rs = ReservedHeapSpace(total_reserved, alignment,
+                                       UseLargePages, heap_address);
+        }
+      }
+      return heap_address;
+    }
   }
 
   *_total_reserved = total_reserved;
@@ -456,6 +481,9 @@
     int max_level_collected = starting_level;
     for (int i = starting_level; i <= max_level; i++) {
       if (_gens[i]->should_collect(full, size, is_tlab)) {
+        if (i == n_gens() - 1) {  // a major collection is to happen
+          pre_full_gc_dump();    // do any pre full gc dumps
+        }
         // Timer for individual generations. Last argument is false: no CR
         TraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, gclog_or_tty);
         TraceCollectorStats tcs(_gens[i]->counters());
@@ -573,6 +601,10 @@
     // a whole heap collection.
     complete = complete || (max_level_collected == n_gens() - 1);
 
+    if (complete) { // We did a "major" collection
+      post_full_gc_dump();   // do any post full gc dumps
+    }
+
     if (PrintGCDetails) {
       print_heap_change(gch_prev_used);
 
--- a/hotspot/src/share/vm/memory/genCollectedHeap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/genCollectedHeap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/generation.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/generation.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/generation.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/generation.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/heap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/heap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -112,7 +112,7 @@
 
   const size_t rs_align = page_size == (size_t) os::vm_page_size() ? 0 :
     MAX2(page_size, granularity);
-  ReservedSpace rs(r_size, rs_align, rs_align > 0);
+  ReservedCodeSpace rs(r_size, rs_align, rs_align > 0);
   os::trace_page_sizes("code heap", committed_size, reserved_size, page_size,
                        rs.base(), rs.size());
   if (!_memory.initialize(rs, c_size)) {
--- a/hotspot/src/share/vm/memory/heapInspection.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/heapInspection.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -233,7 +233,7 @@
   size_t missed_count() { return _missed_count; }
 };
 
-void HeapInspection::heap_inspection(outputStream* st) {
+void HeapInspection::heap_inspection(outputStream* st, bool need_prologue) {
   ResourceMark rm;
   HeapWord* ref;
 
@@ -244,7 +244,9 @@
     case CollectedHeap::GenCollectedHeap: {
       is_shared_heap = true;
       SharedHeap* sh = (SharedHeap*)heap;
-      sh->gc_prologue(false /* !full */); // get any necessary locks, etc.
+      if (need_prologue) {
+        sh->gc_prologue(false /* !full */); // get any necessary locks, etc.
+      }
       ref = sh->perm_gen()->used_region().start();
       break;
     }
@@ -290,7 +292,7 @@
   }
   st->flush();
 
-  if (is_shared_heap) {
+  if (need_prologue && is_shared_heap) {
     SharedHeap* sh = (SharedHeap*)heap;
     sh->gc_epilogue(false /* !full */); // release all acquired locks, etc.
   }
--- a/hotspot/src/share/vm/memory/heapInspection.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/heapInspection.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -127,6 +127,6 @@
 
 class HeapInspection : public AllStatic {
  public:
-  static void heap_inspection(outputStream* st) KERNEL_RETURN;
+  static void heap_inspection(outputStream* st, bool need_prologue) KERNEL_RETURN;
   static void find_instances_at_safepoint(klassOop k, GrowableArray<oop>* result) KERNEL_RETURN;
 };
--- a/hotspot/src/share/vm/memory/oopFactory.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/oopFactory.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/oopFactory.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/oopFactory.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/permGen.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/permGen.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/permGen.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/permGen.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -36,7 +36,7 @@
   friend class VMStructs;
  protected:
   size_t _capacity_expansion_limit;  // maximum expansion allowed without a
-                                     // full gc occuring
+                                     // full gc occurring
 
   HeapWord* mem_allocate_in_gen(size_t size, Generation* gen);
 
--- a/hotspot/src/share/vm/memory/referenceProcessor.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/referenceProcessor.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/sharedHeap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/space.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/space.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/space.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/space.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/tenuredGeneration.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/tenuredGeneration.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/threadLocalAllocBuffer.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/threadLocalAllocBuffer.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/universe.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/universe.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -99,7 +99,8 @@
 size_t          Universe::_heap_used_at_last_gc = 0;
 
 CollectedHeap*  Universe::_collectedHeap = NULL;
-address         Universe::_heap_base = NULL;
+
+NarrowOopStruct Universe::_narrow_oop = { NULL, 0, true };
 
 
 void Universe::basic_type_classes_do(void f(klassOop)) {
@@ -729,6 +730,53 @@
   return JNI_OK;
 }
 
+// Choose the heap base address and oop encoding mode
+// when compressed oops are used:
+// Unscaled  - Use 32-bits oops without encoding when
+//     NarrowOopHeapBaseMin + heap_size < 4Gb
+// ZeroBased - Use zero based compressed oops with encoding when
+//     NarrowOopHeapBaseMin + heap_size < 32Gb
+// HeapBased - Use compressed oops with heap base + encoding.
+
+// 4Gb
+static const uint64_t NarrowOopHeapMax = (uint64_t(max_juint) + 1);
+// 32Gb
+static const uint64_t OopEncodingHeapMax = NarrowOopHeapMax << LogMinObjAlignmentInBytes;
+
+char* Universe::preferred_heap_base(size_t heap_size, NARROW_OOP_MODE mode) {
+#ifdef _LP64
+  if (UseCompressedOops) {
+    assert(mode == UnscaledNarrowOop  ||
+           mode == ZeroBasedNarrowOop ||
+           mode == HeapBasedNarrowOop, "mode is invalid");
+
+    const size_t total_size = heap_size + HeapBaseMinAddress;
+    if (total_size <= OopEncodingHeapMax && (mode != HeapBasedNarrowOop)) {
+      if (total_size <= NarrowOopHeapMax && (mode == UnscaledNarrowOop) &&
+          (Universe::narrow_oop_shift() == 0)) {
+        // Use 32-bits oops without encoding and
+        // place heap's top on the 4Gb boundary
+        return (char*)(NarrowOopHeapMax - heap_size);
+      } else {
+        // Can't reserve with NarrowOopShift == 0
+        Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
+        if (mode == UnscaledNarrowOop ||
+            mode == ZeroBasedNarrowOop && total_size <= NarrowOopHeapMax) {
+          // Use zero based compressed oops with encoding and
+          // place heap's top on the 32Gb boundary in case
+          // total_size > 4Gb or failed to reserve below 4Gb.
+          return (char*)(OopEncodingHeapMax - heap_size);
+        }
+      }
+    } else {
+      // Can't reserve below 32Gb.
+      Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
+    }
+  }
+#endif
+  return NULL; // also return NULL (don't care) for 32-bit VM
+}
+
 jint Universe::initialize_heap() {
 
   if (UseParallelGC) {
@@ -773,6 +821,8 @@
   if (status != JNI_OK) {
     return status;
   }
+
+#ifdef _LP64
   if (UseCompressedOops) {
     // Subtract a page because something can get allocated at heap base.
     // This also makes implicit null checking work, because the
@@ -780,8 +830,49 @@
     // See needs_explicit_null_check.
     // Only set the heap base for compressed oops because it indicates
     // compressed oops for pstack code.
-    Universe::_heap_base = Universe::heap()->base() - os::vm_page_size();
+    if (PrintCompressedOopsMode) {
+      tty->cr();
+      tty->print("heap address: "PTR_FORMAT, Universe::heap()->base());
+    }
+    if ((uint64_t)Universe::heap()->reserved_region().end() > OopEncodingHeapMax) {
+      // Can't reserve heap below 32Gb.
+      Universe::set_narrow_oop_base(Universe::heap()->base() - os::vm_page_size());
+      Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
+      if (PrintCompressedOopsMode) {
+        tty->print(", Compressed Oops with base: "PTR_FORMAT, Universe::narrow_oop_base());
+      }
+    } else {
+      Universe::set_narrow_oop_base(0);
+      if (PrintCompressedOopsMode) {
+        tty->print(", zero based Compressed Oops");
+      }
+#ifdef _WIN64
+      if (!Universe::narrow_oop_use_implicit_null_checks()) {
+        // Don't need guard page for implicit checks in indexed addressing
+        // mode with zero based Compressed Oops.
+        Universe::set_narrow_oop_use_implicit_null_checks(true);
+      }
+#endif //  _WIN64
+      if((uint64_t)Universe::heap()->reserved_region().end() > NarrowOopHeapMax) {
+        // Can't reserve heap below 4Gb.
+        Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
+      } else {
+        assert(Universe::narrow_oop_shift() == 0, "use unscaled narrow oop");
+        if (PrintCompressedOopsMode) {
+          tty->print(", 32-bits Oops");
+        }
+      }
+    }
+    if (PrintCompressedOopsMode) {
+      tty->cr();
+      tty->cr();
+    }
   }
+  assert(Universe::narrow_oop_base() == (Universe::heap()->base() - os::vm_page_size()) ||
+         Universe::narrow_oop_base() == NULL, "invalid value");
+  assert(Universe::narrow_oop_shift() == LogMinObjAlignmentInBytes ||
+         Universe::narrow_oop_shift() == 0, "invalid value");
+#endif
 
   // We will never reach the CATCH below since Exceptions::_throw will cause
   // the VM to exit if an exception is thrown during initialization
--- a/hotspot/src/share/vm/memory/universe.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/memory/universe.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -90,6 +90,19 @@
   methodOop get_methodOop();
 };
 
+// For UseCompressedOops.
+struct NarrowOopStruct {
+  // Base address for oop-within-java-object materialization.
+  // NULL if using wide oops or zero based narrow oops.
+  address _base;
+  // Number of shift bits for encoding/decoding narrow oops.
+  // 0 if using wide oops or zero based unscaled narrow oops,
+  // LogMinObjAlignmentInBytes otherwise.
+  int     _shift;
+  // Generate code with implicit null checks for narrow oops.
+  bool    _use_implicit_null_checks;
+};
+
 
 class Universe: AllStatic {
   // Ugh.  Universe is much too friendly.
@@ -181,9 +194,9 @@
 
   // The particular choice of collected heap.
   static CollectedHeap* _collectedHeap;
-  // Base address for oop-within-java-object materialization.
-  // NULL if using wide oops.  Doubles as heap oop null value.
-  static address        _heap_base;
+
+  // For UseCompressedOops.
+  static struct NarrowOopStruct _narrow_oop;
 
   // array of dummy objects used with +FullGCAlot
   debug_only(static objArrayOop _fullgc_alot_dummy_array;)
@@ -328,8 +341,25 @@
   static CollectedHeap* heap() { return _collectedHeap; }
 
   // For UseCompressedOops
-  static address heap_base()       { return _heap_base; }
-  static address* heap_base_addr() { return &_heap_base; }
+  static address* narrow_oop_base_addr()              { return &_narrow_oop._base; }
+  static address  narrow_oop_base()                   { return  _narrow_oop._base; }
+  static int      narrow_oop_shift()                  { return  _narrow_oop._shift; }
+  static void     set_narrow_oop_base(address base)   { _narrow_oop._base  = base; }
+  static void     set_narrow_oop_shift(int shift)     { _narrow_oop._shift = shift; }
+  static bool     narrow_oop_use_implicit_null_checks()             { return  _narrow_oop._use_implicit_null_checks; }
+  static void     set_narrow_oop_use_implicit_null_checks(bool use) { _narrow_oop._use_implicit_null_checks = use; }
+  // Narrow Oop encoding mode:
+  // 0 - Use 32-bits oops without encoding when
+  //     NarrowOopHeapBaseMin + heap_size < 4Gb
+  // 1 - Use zero based compressed oops with encoding when
+  //     NarrowOopHeapBaseMin + heap_size < 32Gb
+  // 2 - Use compressed oops with heap base + encoding.
+  enum NARROW_OOP_MODE {
+    UnscaledNarrowOop  = 0,
+    ZeroBasedNarrowOop = 1,
+    HeapBasedNarrowOop = 2
+  };
+  static char* preferred_heap_base(size_t heap_size, NARROW_OOP_MODE mode);
 
   // Historic gc information
   static size_t get_heap_capacity_at_last_gc()         { return _heap_capacity_at_last_gc; }
--- a/hotspot/src/share/vm/oops/arrayOop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/arrayOop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constMethodKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constMethodKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constMethodKlass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constMethodKlass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constMethodOop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constMethodOop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constantPoolKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constantPoolKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constantPoolKlass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constantPoolKlass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constantPoolOop.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constantPoolOop.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/constantPoolOop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/constantPoolOop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/cpCacheKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/cpCacheKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/cpCacheKlass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/cpCacheKlass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/cpCacheOop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/cpCacheOop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/generateOopMap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/generateOopMap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -2003,7 +2003,7 @@
 //  ============ Main Entry Point ===========
 //
 GenerateOopMap::GenerateOopMap(methodHandle method) {
-  // We have to initialize all variables here, that can be queried direcly
+  // We have to initialize all variables here, that can be queried directly
   _method = method;
   _max_locals=0;
   _init_vars = NULL;
--- a/hotspot/src/share/vm/oops/generateOopMap.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/generateOopMap.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -292,7 +292,7 @@
   int          _max_stack;                  // Cached value of max. stack depth
   int          _max_monitors;               // Cached value of max. monitor stack depth
   int          _has_exceptions;             // True, if exceptions exist for method
-  bool         _got_error;                  // True, if an error occured during interpretation.
+  bool         _got_error;                  // True, if an error occurred during interpretation.
   Handle       _exception;                  // Exception if got_error is true.
   bool         _did_rewriting;              // was bytecodes rewritten
   bool         _did_relocation;             // was relocation neccessary
@@ -422,7 +422,7 @@
   void  add_to_ref_init_set                 (int localNo);
 
   // Conflicts rewrite logic
-  bool      _conflict;                      // True, if a conflict occured during interpretation
+  bool      _conflict;                      // True, if a conflict occurred during interpretation
   int       _nof_refval_conflicts;          // No. of conflicts that require rewrites
   int *     _new_var_map;
 
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1813,6 +1813,8 @@
                                           oop class_loader2, symbolOop class_name2) {
   if (class_loader1 != class_loader2) {
     return false;
+  } else if (class_name1 == class_name2) {
+    return true;                // skip painful bytewise comparison
   } else {
     ResourceMark rm;
 
@@ -1859,6 +1861,75 @@
   }
 }
 
+// Returns true iff super_method can be overridden by a method in targetclassname
+// See JSL 3rd edition 8.4.6.1
+// Assumes name-signature match
+// "this" is instanceKlass of super_method which must exist
+// note that the instanceKlass of the method in the targetclassname has not always been created yet
+bool instanceKlass::is_override(methodHandle super_method, Handle targetclassloader, symbolHandle targetclassname, TRAPS) {
+   // Private methods can not be overridden
+   if (super_method->is_private()) {
+     return false;
+   }
+   // If super method is accessible, then override
+   if ((super_method->is_protected()) ||
+       (super_method->is_public())) {
+     return true;
+   }
+   // Package-private methods are not inherited outside of package
+   assert(super_method->is_package_private(), "must be package private");
+   return(is_same_class_package(targetclassloader(), targetclassname()));
+}
+
+/* defined for now in jvm.cpp, for historical reasons *--
+klassOop instanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
+                                                     symbolOop& simple_name_result, TRAPS) {
+  ...
+}
+*/
+
+// tell if two classes have the same enclosing class (at package level)
+bool instanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
+                                                klassOop class2_oop, TRAPS) {
+  if (class2_oop == class1->as_klassOop())          return true;
+  if (!Klass::cast(class2_oop)->oop_is_instance())  return false;
+  instanceKlassHandle class2(THREAD, class2_oop);
+
+  // must be in same package before we try anything else
+  if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
+    return false;
+
+  // As long as there is an outer1.getEnclosingClass,
+  // shift the search outward.
+  instanceKlassHandle outer1 = class1;
+  for (;;) {
+    // As we walk along, look for equalities between outer1 and class2.
+    // Eventually, the walks will terminate as outer1 stops
+    // at the top-level class around the original class.
+    symbolOop ignore_name;
+    klassOop next = outer1->compute_enclosing_class(ignore_name, CHECK_false);
+    if (next == NULL)  break;
+    if (next == class2())  return true;
+    outer1 = instanceKlassHandle(THREAD, next);
+  }
+
+  // Now do the same for class2.
+  instanceKlassHandle outer2 = class2;
+  for (;;) {
+    symbolOop ignore_name;
+    klassOop next = outer2->compute_enclosing_class(ignore_name, CHECK_false);
+    if (next == NULL)  break;
+    // Might as well check the new outer against all available values.
+    if (next == class1())  return true;
+    if (next == outer1())  return true;
+    outer2 = instanceKlassHandle(THREAD, next);
+  }
+
+  // If by this point we have not found an equality between the
+  // two classes, we know they are in separate package members.
+  return false;
+}
+
 
 jint instanceKlass::compute_modifier_flags(TRAPS) const {
   klassOop k = as_klassOop();
@@ -1917,7 +1988,7 @@
                        / itableOffsetEntry::size();
 
   for (int cnt = 0 ; ; cnt ++, ioe ++) {
-    // If the interface isn't implemented by the reciever class,
+    // If the interface isn't implemented by the receiver class,
     // the VM should throw IncompatibleClassChangeError.
     if (cnt >= nof_interfaces) {
       THROW_OOP_0(vmSymbols::java_lang_IncompatibleClassChangeError());
@@ -1996,9 +2067,11 @@
 
 // Printing
 
+#define BULLET  " - "
+
 void FieldPrinter::do_field(fieldDescriptor* fd) {
-   if (fd->is_static() == (_obj == NULL)) {
-     _st->print("   - ");
+  _st->print(BULLET);
+   if (fd->is_static() || (_obj == NULL)) {
      fd->print_on(_st);
      _st->cr();
    } else {
@@ -2019,7 +2092,7 @@
         value->is_typeArray() &&
         offset          <= (juint) value->length() &&
         offset + length <= (juint) value->length()) {
-      st->print("string: ");
+      st->print(BULLET"string: ");
       Handle h_obj(obj);
       java_lang_String::print(h_obj, st);
       st->cr();
@@ -2027,23 +2100,26 @@
     }
   }
 
-  st->print_cr("fields:");
+  st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
   FieldPrinter print_nonstatic_field(st, obj);
   do_nonstatic_fields(&print_nonstatic_field);
 
   if (as_klassOop() == SystemDictionary::class_klass()) {
+    st->print(BULLET"signature: ");
+    java_lang_Class::print_signature(obj, st);
+    st->cr();
     klassOop mirrored_klass = java_lang_Class::as_klassOop(obj);
-    st->print("   - fake entry for mirror: ");
+    st->print(BULLET"fake entry for mirror: ");
     mirrored_klass->print_value_on(st);
     st->cr();
-    st->print("   - fake entry resolved_constructor: ");
+    st->print(BULLET"fake entry resolved_constructor: ");
     methodOop ctor = java_lang_Class::resolved_constructor(obj);
     ctor->print_value_on(st);
     klassOop array_klass = java_lang_Class::array_klass(obj);
-    st->print("   - fake entry for array: ");
+    st->cr();
+    st->print(BULLET"fake entry for array: ");
     array_klass->print_value_on(st);
     st->cr();
-    st->cr();
   }
 }
 
@@ -2051,6 +2127,28 @@
   st->print("a ");
   name()->print_value_on(st);
   obj->print_address_on(st);
+  if (as_klassOop() == SystemDictionary::string_klass()
+      && java_lang_String::value(obj) != NULL) {
+    ResourceMark rm;
+    int len = java_lang_String::length(obj);
+    int plen = (len < 24 ? len : 12);
+    char* str = java_lang_String::as_utf8_string(obj, 0, plen);
+    st->print(" = \"%s\"", str);
+    if (len > plen)
+      st->print("...[%d]", len);
+  } else if (as_klassOop() == SystemDictionary::class_klass()) {
+    klassOop k = java_lang_Class::as_klassOop(obj);
+    st->print(" = ");
+    if (k != NULL) {
+      k->print_value_on(st);
+    } else {
+      const char* tname = type2name(java_lang_Class::primitive_type(obj));
+      st->print("%s", tname ? tname : "type?");
+    }
+  } else if (java_lang_boxing_object::is_instance(obj)) {
+    st->print(" = ");
+    java_lang_boxing_object::print(obj, st);
+  }
 }
 
 #endif // ndef PRODUCT
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -303,11 +303,30 @@
     inner_class_next_offset = 4
   };
 
+  // method override check
+  bool is_override(methodHandle super_method, Handle targetclassloader, symbolHandle targetclassname, TRAPS);
+
   // package
   bool is_same_class_package(klassOop class2);
   bool is_same_class_package(oop classloader2, symbolOop classname2);
   static bool is_same_class_package(oop class_loader1, symbolOop class_name1, oop class_loader2, symbolOop class_name2);
 
+  // find an enclosing class (defined where original code was, in jvm.cpp!)
+  klassOop compute_enclosing_class(symbolOop& simple_name_result, TRAPS) {
+    instanceKlassHandle self(THREAD, this->as_klassOop());
+    return compute_enclosing_class_impl(self, simple_name_result, THREAD);
+  }
+  static klassOop compute_enclosing_class_impl(instanceKlassHandle self,
+                                               symbolOop& simple_name_result, TRAPS);
+
+  // tell if two classes have the same enclosing class (at package level)
+  bool is_same_package_member(klassOop class2, TRAPS) {
+    instanceKlassHandle self(THREAD, this->as_klassOop());
+    return is_same_package_member_impl(self, class2, THREAD);
+  }
+  static bool is_same_package_member_impl(instanceKlassHandle self,
+                                          klassOop class2, TRAPS);
+
   // initialization state
   bool is_loaded() const                   { return _init_state >= loaded; }
   bool is_linked() const                   { return _init_state >= linked; }
--- a/hotspot/src/share/vm/oops/instanceKlassKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlassKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -487,6 +487,8 @@
 
 // Printing
 
+#define BULLET  " - "
+
 static const char* state_names[] = {
   "unparseable_by_gc", "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
 };
@@ -497,13 +499,13 @@
   instanceKlass* ik = instanceKlass::cast(klassOop(obj));
   klassKlass::oop_print_on(obj, st);
 
-  st->print(" - instance size:     %d", ik->size_helper());                        st->cr();
-  st->print(" - klass size:        %d", ik->object_size());                        st->cr();
-  st->print(" - access:            "); ik->access_flags().print_on(st);            st->cr();
-  st->print(" - state:             "); st->print_cr(state_names[ik->_init_state]);
-  st->print(" - name:              "); ik->name()->print_value_on(st);             st->cr();
-  st->print(" - super:             "); ik->super()->print_value_on(st);            st->cr();
-  st->print(" - sub:               ");
+  st->print(BULLET"instance size:     %d", ik->size_helper());                        st->cr();
+  st->print(BULLET"klass size:        %d", ik->object_size());                        st->cr();
+  st->print(BULLET"access:            "); ik->access_flags().print_on(st);            st->cr();
+  st->print(BULLET"state:             "); st->print_cr(state_names[ik->_init_state]);
+  st->print(BULLET"name:              "); ik->name()->print_value_on(st);             st->cr();
+  st->print(BULLET"super:             "); ik->super()->print_value_on(st);            st->cr();
+  st->print(BULLET"sub:               ");
   Klass* sub = ik->subklass();
   int n;
   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
@@ -516,12 +518,12 @@
   st->cr();
 
   if (ik->is_interface()) {
-    st->print_cr(" - nof implementors:  %d", ik->nof_implementors());
+    st->print_cr(BULLET"nof implementors:  %d", ik->nof_implementors());
     int print_impl = 0;
     for (int i = 0; i < instanceKlass::implementors_limit; i++) {
       if (ik->implementor(i) != NULL) {
         if (++print_impl == 1)
-          st->print_cr(" - implementor:    ");
+          st->print_cr(BULLET"implementor:    ");
         st->print("   ");
         ik->implementor(i)->print_value_on(st);
       }
@@ -529,34 +531,33 @@
     if (print_impl > 0)  st->cr();
   }
 
-  st->print(" - arrays:            "); ik->array_klasses()->print_value_on(st);     st->cr();
-  st->print(" - methods:           "); ik->methods()->print_value_on(st);           st->cr();
+  st->print(BULLET"arrays:            "); ik->array_klasses()->print_value_on(st);     st->cr();
+  st->print(BULLET"methods:           "); ik->methods()->print_value_on(st);           st->cr();
   if (Verbose) {
     objArrayOop methods = ik->methods();
     for(int i = 0; i < methods->length(); i++) {
       tty->print("%d : ", i); methods->obj_at(i)->print_value(); tty->cr();
     }
   }
-  st->print(" - method ordering:   "); ik->method_ordering()->print_value_on(st);       st->cr();
-  st->print(" - local interfaces:  "); ik->local_interfaces()->print_value_on(st);      st->cr();
-  st->print(" - trans. interfaces: "); ik->transitive_interfaces()->print_value_on(st); st->cr();
-  st->print(" - constants:         "); ik->constants()->print_value_on(st);         st->cr();
-  st->print(" - class loader:      "); ik->class_loader()->print_value_on(st);      st->cr();
-  st->print(" - protection domain: "); ik->protection_domain()->print_value_on(st); st->cr();
-  st->print(" - host class: ");        ik->host_klass()->print_value_on(st);        st->cr();
-  st->print(" - signers:           "); ik->signers()->print_value_on(st);           st->cr();
+  st->print(BULLET"method ordering:   "); ik->method_ordering()->print_value_on(st);       st->cr();
+  st->print(BULLET"local interfaces:  "); ik->local_interfaces()->print_value_on(st);      st->cr();
+  st->print(BULLET"trans. interfaces: "); ik->transitive_interfaces()->print_value_on(st); st->cr();
+  st->print(BULLET"constants:         "); ik->constants()->print_value_on(st);         st->cr();
+  st->print(BULLET"class loader:      "); ik->class_loader()->print_value_on(st);      st->cr();
+  st->print(BULLET"protection domain: "); ik->protection_domain()->print_value_on(st); st->cr();
+  st->print(BULLET"host class:        "); ik->host_klass()->print_value_on(st);        st->cr();
+  st->print(BULLET"signers:           "); ik->signers()->print_value_on(st);           st->cr();
   if (ik->source_file_name() != NULL) {
-    st->print(" - source file:       ");
+    st->print(BULLET"source file:       ");
     ik->source_file_name()->print_value_on(st);
     st->cr();
   }
   if (ik->source_debug_extension() != NULL) {
-    st->print(" - source debug extension:       ");
+    st->print(BULLET"source debug extension:       ");
     ik->source_debug_extension()->print_value_on(st);
     st->cr();
   }
 
-  st->print_cr(" - previous version:       ");
   {
     ResourceMark rm;
     // PreviousVersionInfo objects returned via PreviousVersionWalker
@@ -564,38 +565,43 @@
     // GrowableArray _after_ the PreviousVersionWalker destructor
     // has destroyed the handles.
     {
+      bool have_pv = false;
       PreviousVersionWalker pvw(ik);
       for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
            pv_info != NULL; pv_info = pvw.next_previous_version()) {
+        if (!have_pv)
+          st->print(BULLET"previous version:  ");
+        have_pv = true;
         pv_info->prev_constant_pool_handle()()->print_value_on(st);
       }
-      st->cr();
+      if (have_pv)  st->cr();
     } // pvw is cleaned up
   } // rm is cleaned up
 
   if (ik->generic_signature() != NULL) {
-    st->print(" - generic signature:            ");
+    st->print(BULLET"generic signature: ");
     ik->generic_signature()->print_value_on(st);
+    st->cr();
   }
-  st->print(" - inner classes:     "); ik->inner_classes()->print_value_on(st);     st->cr();
-  st->print(" - java mirror:       "); ik->java_mirror()->print_value_on(st);       st->cr();
-  st->print(" - vtable length      %d  (start addr: " INTPTR_FORMAT ")", ik->vtable_length(), ik->start_of_vtable());  st->cr();
-  st->print(" - itable length      %d (start addr: " INTPTR_FORMAT ")", ik->itable_length(), ik->start_of_itable()); st->cr();
-  st->print_cr(" - static fields:");
+  st->print(BULLET"inner classes:     "); ik->inner_classes()->print_value_on(st);     st->cr();
+  st->print(BULLET"java mirror:       "); ik->java_mirror()->print_value_on(st);       st->cr();
+  st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", ik->vtable_length(), ik->start_of_vtable());  st->cr();
+  st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", ik->itable_length(), ik->start_of_itable()); st->cr();
+  st->print_cr(BULLET"---- static fields (%d words):", ik->static_field_size());
   FieldPrinter print_static_field(st);
   ik->do_local_static_fields(&print_static_field);
-  st->print_cr(" - non-static fields:");
-  FieldPrinter print_nonstatic_field(st, obj);
+  st->print_cr(BULLET"---- non-static fields (%d words):", ik->nonstatic_field_size());
+  FieldPrinter print_nonstatic_field(st);
   ik->do_nonstatic_fields(&print_nonstatic_field);
 
-  st->print(" - static oop maps:     ");
+  st->print(BULLET"static oop maps:     ");
   if (ik->static_oop_field_size() > 0) {
     int first_offset = ik->offset_of_static_fields();
     st->print("%d-%d", first_offset, first_offset + ik->static_oop_field_size() - 1);
   }
   st->cr();
 
-  st->print(" - non-static oop maps: ");
+  st->print(BULLET"non-static oop maps: ");
   OopMapBlock* map     = ik->start_of_nonstatic_oop_maps();
   OopMapBlock* end_map = map + ik->nonstatic_oop_map_size();
   while (map < end_map) {
--- a/hotspot/src/share/vm/oops/klass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/klass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -71,7 +71,7 @@
   return r;                   // Return the 1 concrete class
 }
 
-// Find LCA in class heirarchy
+// Find LCA in class hierarchy
 Klass *Klass::LCA( Klass *k2 ) {
   Klass *k1 = this;
   while( 1 ) {
--- a/hotspot/src/share/vm/oops/klass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/klass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -471,7 +471,7 @@
   }
   bool search_secondary_supers(klassOop k) const;
 
-  // Find LCA in class heirarchy
+  // Find LCA in class hierarchy
   Klass *LCA( Klass *k );
 
   // Check whether reflection/jni/jvm code is allowed to instantiate this class;
--- a/hotspot/src/share/vm/oops/klassVtable.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/klassVtable.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,9 +45,10 @@
                                                        klassOop super,
                                                        objArrayOop methods,
                                                        AccessFlags class_flags,
-                                                       oop classloader,
-                                                       symbolOop classname,
-                                                       objArrayOop local_interfaces
+                                                       Handle classloader,
+                                                       symbolHandle classname,
+                                                       objArrayOop local_interfaces,
+                                                       TRAPS
                                                        ) {
 
   No_Safepoint_Verifier nsv;
@@ -64,9 +65,9 @@
   int len = methods->length();
   for (int i = 0; i < len; i++) {
     assert(methods->obj_at(i)->is_method(), "must be a methodOop");
-    methodOop m = methodOop(methods->obj_at(i));
+    methodHandle mh(THREAD, methodOop(methods->obj_at(i)));
 
-    if (needs_new_vtable_entry(m, super, classloader, classname, class_flags)) {
+    if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
       vtable_length += vtableEntry::size(); // we need a new entry
     }
   }
@@ -117,6 +118,7 @@
     superVtable->copy_vtable_to(table());
 #ifndef PRODUCT
     if (PrintVtables && Verbose) {
+      ResourceMark rm;
       tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
     }
 #endif
@@ -159,13 +161,13 @@
     int len = methods()->length();
     int initialized = super_vtable_len;
 
-    // update_super_vtable can stop for gc - ensure using handles
+    // update_inherited_vtable can stop for gc - ensure using handles
     for (int i = 0; i < len; i++) {
       HandleMark hm(THREAD);
       assert(methods()->obj_at(i)->is_method(), "must be a methodOop");
       methodHandle mh(THREAD, (methodOop)methods()->obj_at(i));
 
-      bool needs_new_entry = update_super_vtable(ik(), mh, super_vtable_len, checkconstraints, CHECK);
+      bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, checkconstraints, CHECK);
 
       if (needs_new_entry) {
         put_method_at(mh(), initialized);
@@ -177,7 +179,7 @@
     // add miranda methods; it will also update the value of initialized
     fill_in_mirandas(initialized);
 
-    // In class hierachieswhere the accesibility is not increasing (i.e., going from private ->
+    // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
     // package_private -> publicprotected), the vtable might actually be smaller than our initial
     // calculation.
     assert(initialized <= _length, "vtable initialization failed");
@@ -188,26 +190,49 @@
   }
 }
 
-// Interates through the vtables to find the broadest access level. This
-// will always be monotomic for valid Java programs - but not neccesarily
-// for incompatible class files.
-klassVtable::AccessType klassVtable::vtable_accessibility_at(int i) {
-  // This vtable is not implementing the specific method
-  if (i >= length()) return acc_private;
+// Called for cases where a method does not override its superclass' vtable entry
+// For bytecodes not produced by javac together it is possible that a method does not override
+// the superclass's method, but might indirectly override a super-super class's vtable entry
+// If none found, return a null superk, else return the superk of the method this does override
+instanceKlass* klassVtable::find_transitive_override(instanceKlass* initialsuper, methodHandle target_method,
+                            int vtable_index, Handle target_loader, symbolHandle target_classname, Thread * THREAD) {
+  instanceKlass* superk = initialsuper;
+  while (superk != NULL && superk->super() != NULL) {
+    instanceKlass* supersuperklass = instanceKlass::cast(superk->super());
+    klassVtable* ssVtable = supersuperklass->vtable();
+    if (vtable_index < ssVtable->length()) {
+      methodOop super_method = ssVtable->method_at(vtable_index);
+#ifndef PRODUCT
+      symbolHandle name(THREAD,target_method()->name());
+      symbolHandle signature(THREAD,target_method()->signature());
+      assert(super_method->name() == name() && super_method->signature() == signature(), "vtable entry name/sig mismatch");
+#endif
+      if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) {
+#ifndef PRODUCT
+        if (PrintVtables && Verbose) {
+          ResourceMark rm(THREAD);
+          tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ",
+           supersuperklass->internal_name(),
+           _klass->internal_name(), (target_method() != NULL) ?
+           target_method()->name()->as_C_string() : "<NULL>", vtable_index);
+           super_method->access_flags().print_on(tty);
+           tty->print("overriders flags: ");
+           target_method->access_flags().print_on(tty);
+           tty->cr();
+        }
+#endif /*PRODUCT*/
+        break; // return found superk
+      }
+    } else  {
+      // super class has no vtable entry here, stop transitive search
+      superk = (instanceKlass*)NULL;
+      break;
+    }
+    // if no override found yet, continue to search up
+    superk = instanceKlass::cast(superk->super());
+  }
 
-  // Compute AccessType for current method. public or protected we are done.
-  methodOop m = method_at(i);
-  if (m->is_protected() || m->is_public()) return acc_publicprotected;
-
-  AccessType acc = m->is_package_private() ? acc_package_private : acc_private;
-
-  // Compute AccessType for method in super classes
-  klassOop super = klass()->super();
-  AccessType super_acc = (super != NULL) ? instanceKlass::cast(klass()->super())->vtable()->vtable_accessibility_at(i)
-                                         : acc_private;
-
-  // Merge
-  return (AccessType)MAX2((int)acc, (int)super_acc);
+  return superk;
 }
 
 
@@ -215,7 +240,8 @@
 // OR return true if a new vtable entry is required
 // Only called for instanceKlass's, i.e. not for arrays
 // If that changed, could not use _klass as handle for klass
-bool klassVtable::update_super_vtable(instanceKlass* klass, methodHandle target_method, int super_vtable_len, bool checkconstraints, TRAPS) {
+bool klassVtable::update_inherited_vtable(instanceKlass* klass, methodHandle target_method, int super_vtable_len,
+                  bool checkconstraints, TRAPS) {
   ResourceMark rm;
   bool allocate_new = true;
   assert(klass->oop_is_instance(), "must be instanceKlass");
@@ -242,58 +268,35 @@
   }
 
   // private methods always have a new entry in the vtable
+  // specification interpretation since classic has
+  // private methods not overriding
   if (target_method()->is_private()) {
     return allocate_new;
   }
 
   // search through the vtable and update overridden entries
   // Since check_signature_loaders acquires SystemDictionary_lock
-  // which can block for gc, once we are in this loop, use handles, not
-  // unhandled oops unless they are reinitialized for each loop
-  // handles for name, signature, klass, target_method
-  // not for match_method, holder
+  // which can block for gc, once we are in this loop, use handles
+  // For classfiles built with >= jdk7, we now look for transitive overrides
 
   symbolHandle name(THREAD,target_method()->name());
   symbolHandle signature(THREAD,target_method()->signature());
+  Handle target_loader(THREAD, _klass->class_loader());
+  symbolHandle target_classname(THREAD, _klass->name());
   for(int i = 0; i < super_vtable_len; i++) {
-    methodOop match_method = method_at(i);
+    methodOop super_method = method_at(i);
     // Check if method name matches
-    if (match_method->name() == name() && match_method->signature() == signature()) {
-
-      instanceKlass* holder = (THREAD, instanceKlass::cast(match_method->method_holder()));
-
-      // Check if the match_method is accessable from current class
-
-      bool same_package_init = false;
-      bool same_package_flag = false;
-      bool simple_match = match_method->is_public()  || match_method->is_protected();
-      if (!simple_match) {
-        same_package_init = true;
-        same_package_flag = holder->is_same_class_package(_klass->class_loader(), _klass->name());
+    if (super_method->name() == name() && super_method->signature() == signature()) {
 
-        simple_match = match_method->is_package_private() && same_package_flag;
-      }
-      // match_method is the superclass' method. Note we can't override
-      // and shouldn't access superclass' ACC_PRIVATE methods
-      // (although they have been copied into our vtable)
-      // A simple form of this statement is:
-      // if ( (match_method->is_public()  || match_method->is_protected()) ||
-      //    (match_method->is_package_private() && holder->is_same_class_package(klass->class_loader(), klass->name()))) {
-      //
-      // The complexity is introduced it avoid recomputing 'is_same_class_package' which is expensive.
-      if (simple_match) {
-        // Check if target_method and match_method has same level of accessibility. The accesibility of the
-        // match method is the "most-general" visibility of all entries at it's particular vtable index for
-        // all superclasses. This check must be done before we override the current entry in the vtable.
-        AccessType at = vtable_accessibility_at(i);
-        bool same_access = false;
+      // get super_klass for method_holder for the found method
+      instanceKlass* super_klass =  instanceKlass::cast(super_method->method_holder());
 
-        if (  (at == acc_publicprotected && (target_method()->is_public() || target_method()->is_protected())
-           || (at == acc_package_private && (target_method()->is_package_private() &&
-                                            (( same_package_init && same_package_flag) ||
-                                             (!same_package_init && holder->is_same_class_package(_klass->class_loader(), _klass->name()))))))) {
-           same_access = true;
-        }
+      if ((super_klass->is_override(super_method, target_loader, target_classname, THREAD)) ||
+      ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
+        && ((super_klass = find_transitive_override(super_klass, target_method, i, target_loader,
+             target_classname, THREAD)) != (instanceKlass*)NULL))) {
+        // overriding, so no new entry
+        allocate_new = false;
 
         if (checkconstraints) {
         // Override vtable entry if passes loader constraint check
@@ -302,15 +305,12 @@
         // have already made any needed loader constraints.
         // Since loader constraints are transitive, it is enough
         // to link to the first super, and we get all the others.
-          symbolHandle signature(THREAD, target_method()->signature());
-          Handle this_loader(THREAD, _klass->class_loader());
-          instanceKlassHandle super_klass(THREAD, _klass->super());
           Handle super_loader(THREAD, super_klass->class_loader());
 
-          if (this_loader() != super_loader()) {
+          if (target_loader() != super_loader()) {
             ResourceMark rm(THREAD);
             char* failed_type_name =
-              SystemDictionary::check_signature_loaders(signature, this_loader,
+              SystemDictionary::check_signature_loaders(signature, target_loader,
                                                         super_loader, true,
                                                         CHECK_(false));
             if (failed_type_name != NULL) {
@@ -320,7 +320,7 @@
                 "(instance of %s), have different Class objects for the type "
                 "%s used in the signature";
               char* sig = target_method()->name_and_sig_as_C_string();
-              const char* loader1 = SystemDictionary::loader_name(this_loader());
+              const char* loader1 = SystemDictionary::loader_name(target_loader());
               char* current = _klass->name()->as_C_string();
               const char* loader2 = SystemDictionary::loader_name(super_loader());
               size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
@@ -331,59 +331,46 @@
               THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
             }
           }
-        }
-        put_method_at(target_method(), i);
-
+       }
 
-        if (same_access) {
-          // target and match has same accessiblity - share entry
-          allocate_new = false;
-          target_method()->set_vtable_index(i);
+        put_method_at(target_method(), i);
+        target_method()->set_vtable_index(i);
 #ifndef PRODUCT
-          if (PrintVtables && Verbose) {
-            AccessType targetacc;
-            if (target_method()->is_protected() ||
-                 target_method()->is_public()) {
-               targetacc =  acc_publicprotected;
-            } else {
-              targetacc = target_method()->is_package_private() ? acc_package_private : acc_private;
-            }
-            tty->print_cr("overriding with %s::%s index %d, original flags: %x overriders flags: %x",
-             _klass->internal_name(), (target_method() != NULL) ?
-             target_method()->name()->as_C_string() : "<NULL>", i,
-             at, targetacc);
-          }
+        if (PrintVtables && Verbose) {
+          tty->print("overriding with %s::%s index %d, original flags: ",
+           _klass->internal_name(), (target_method() != NULL) ?
+           target_method()->name()->as_C_string() : "<NULL>", i);
+           super_method->access_flags().print_on(tty);
+           tty->print("overriders flags: ");
+           target_method->access_flags().print_on(tty);
+           tty->cr();
+        }
 #endif /*PRODUCT*/
-        } else {
+      } else {
+        // allocate_new = true; default. We might override one entry,
+        // but not override another. Once we override one, not need new
 #ifndef PRODUCT
-          if (PrintVtables && Verbose) {
-            AccessType targetacc;
-            if (target_method()->is_protected() ||
-                 target_method()->is_public()) {
-               targetacc =  acc_publicprotected;
-            } else {
-              targetacc = target_method()->is_package_private() ? acc_package_private : acc_private;
-            }
-            tty->print_cr("override %s %s::%s at index %d, original flags: %x overriders flags: %x",
-            allocate_new ? "+ new" : "only",
-            _klass->internal_name(), (target_method() != NULL) ?
-            target_method()->name()->as_C_string() : "<NULL>", i,
-            at, targetacc);
-           }
+        if (PrintVtables && Verbose) {
+          tty->print("NOT overriding with %s::%s index %d, original flags: ",
+           _klass->internal_name(), (target_method() != NULL) ?
+           target_method()->name()->as_C_string() : "<NULL>", i);
+           super_method->access_flags().print_on(tty);
+           tty->print("overriders flags: ");
+           target_method->access_flags().print_on(tty);
+           tty->cr();
+        }
 #endif /*PRODUCT*/
-        }
       }
     }
   }
   return allocate_new;
 }
 
-
-
 void klassVtable::put_method_at(methodOop m, int index) {
   assert(m->is_oop_or_null(), "Not an oop or null");
 #ifndef PRODUCT
   if (PrintVtables && Verbose) {
+    ResourceMark rm;
     tty->print_cr("adding %s::%s at index %d", _klass->internal_name(),
       (m != NULL) ? m->name()->as_C_string() : "<NULL>", index);
   }
@@ -397,19 +384,23 @@
 // by "classloader" and "classname".
 // NOTE: The logic used here is very similar to the one used for computing
 // the vtables indices for a method. We cannot directly use that function because,
-// when the Universe is boostrapping, a super's vtable might not be initialized.
-bool klassVtable::needs_new_vtable_entry(methodOop target_method,
+// we allocate the instanceKlass at load time, and that requires that the
+// superclass has been loaded.
+// However, the vtable entries are filled in at link time, and therefore
+// the superclass' vtable may not yet have been filled in.
+bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
                                          klassOop super,
-                                         oop classloader,
-                                         symbolOop classname,
-                                         AccessFlags class_flags) {
-  if ((class_flags.is_final() || target_method->is_final()) ||
+                                         Handle classloader,
+                                         symbolHandle classname,
+                                         AccessFlags class_flags,
+                                         TRAPS) {
+  if ((class_flags.is_final() || target_method()->is_final()) ||
       // a final method never needs a new entry; final methods can be statically
       // resolved and they have to be present in the vtable only if they override
       // a super's method, in which case they re-use its entry
-      (target_method->is_static()) ||
+      (target_method()->is_static()) ||
       // static methods don't need to be in vtable
-      (target_method->name() ==  vmSymbols::object_initializer_name())
+      (target_method()->name() ==  vmSymbols::object_initializer_name())
       // <init> is never called dynamically-bound
       ) {
     return false;
@@ -421,55 +412,58 @@
   }
 
   // private methods always have a new entry in the vtable
-  if (target_method->is_private()) {
+  // specification interpretation since classic has
+  // private methods not overriding
+  if (target_method()->is_private()) {
     return true;
   }
 
   // search through the super class hierarchy to see if we need
   // a new entry
-  symbolOop name = target_method->name();
-  symbolOop signature = target_method->signature();
+  ResourceMark rm;
+  symbolOop name = target_method()->name();
+  symbolOop signature = target_method()->signature();
   klassOop k = super;
-  methodOop match_method = NULL;
+  methodOop super_method = NULL;
   instanceKlass *holder = NULL;
+  methodOop recheck_method =  NULL;
   while (k != NULL) {
     // lookup through the hierarchy for a method with matching name and sign.
-    match_method = instanceKlass::cast(k)->lookup_method(name, signature);
-    if (match_method == NULL) {
+    super_method = instanceKlass::cast(k)->lookup_method(name, signature);
+    if (super_method == NULL) {
       break; // we still have to search for a matching miranda method
     }
     // get the class holding the matching method
-    holder = instanceKlass::cast(match_method->method_holder());
-
-    if (!match_method->is_static()) { // we want only instance method matches
-      if ((target_method->is_public() || target_method->is_protected()) &&
-          (match_method->is_public()  || match_method->is_protected())) {
-        // target and match are public/protected; we do not need a new entry
+    // make sure you use that class for is_override
+    instanceKlass* superk = instanceKlass::cast(super_method->method_holder());
+    // we want only instance method matches
+    // pretend private methods are not in the super vtable
+    // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
+    // ignore private, c.m pub does override a.m pub
+    // For classes that were not javac'd together, we also do transitive overriding around
+    // methods that have less accessibility
+    if ((!super_method->is_static()) &&
+       (!super_method->is_private())) {
+      if (superk->is_override(super_method, classloader, classname, THREAD)) {
         return false;
-      }
-
-      if (target_method->is_package_private() &&
-          match_method->is_package_private() &&
-          holder->is_same_class_package(classloader, classname)) {
-        // target and match are P private; we do not need a new entry
-        return false;
+      // else keep looking for transitive overrides
       }
     }
 
-    k = holder->super(); // haven't found a match yet; continue to look
+    // Start with lookup result and continue to search up
+    k = superk->super(); // haven't found an override match yet; continue to look
   }
 
   // if the target method is public or protected it may have a matching
   // miranda method in the super, whose entry it should re-use.
-  if (target_method->is_public() || target_method->is_protected()) {
-    instanceKlass *sk = instanceKlass::cast(super);
-    if (sk->has_miranda_methods()) {
-      if (sk->lookup_method_in_all_interfaces(name, signature) != NULL) {
-        return false;  // found a matching miranda; we do not need a new entry
-      }
+  // Actually, to handle cases that javac would not generate, we need
+  // this check for all access permissions.
+  instanceKlass *sk = instanceKlass::cast(super);
+  if (sk->has_miranda_methods()) {
+    if (sk->lookup_method_in_all_interfaces(name, signature) != NULL) {
+      return false;  // found a matching miranda; we do not need a new entry
     }
   }
-
   return true; // found no match; we need a new entry
 }
 
@@ -884,7 +878,7 @@
                                     _klass->name()->as_C_string());
 
 
-    // Interate through all interfaces
+    // Iterate through all interfaces
     int i;
     for(i = 0; i < num_interfaces; i++) {
       itableOffsetEntry* ioe = offset_entry(i);
@@ -992,6 +986,10 @@
     methodOop new_method = new_methods[j];
     itableMethodEntry* ime = method_entry(0);
 
+    // The itable can describe more than one interface and the same
+    // method signature can be specified by more than one interface.
+    // This means we have to do an exhaustive search to find all the
+    // old_method references.
     for (int i = 0; i < _size_method_table; i++) {
       if (ime->method() == old_method) {
         ime->initialize(new_method);
@@ -1150,6 +1148,27 @@
   return index;
 }
 
+
+// inverse to compute_itable_index
+methodOop klassItable::method_for_itable_index(klassOop intf, int itable_index) {
+  assert(instanceKlass::cast(intf)->is_interface(), "sanity check");
+  objArrayOop methods = instanceKlass::cast(intf)->methods();
+
+  int index = itable_index;
+  // Adjust for <clinit>, which is left out of table if first method
+  if (methods->length() > 0 && ((methodOop)methods->obj_at(0))->name() == vmSymbols::class_initializer_name()) {
+    index++;
+  }
+
+  if (itable_index < 0 || index >= methods->length())
+    return NULL;                // help caller defend against bad indexes
+
+  methodOop m = (methodOop)methods->obj_at(index);
+  assert(compute_itable_index(m) == itable_index, "correct inverse");
+
+  return m;
+}
+
 void klassVtable::verify(outputStream* st, bool forced) {
   // make sure table is initialized
   if (!Universe::is_fully_initialized()) return;
--- a/hotspot/src/share/vm/oops/klassVtable.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/klassVtable.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,8 +70,9 @@
   // conputes vtable length (in words) and the number of miranda methods
   static void compute_vtable_size_and_num_mirandas(int &vtable_length, int &num_miranda_methods,
                                                    klassOop super, objArrayOop methods,
-                                                   AccessFlags class_flags, oop classloader,
-                                                   symbolOop classname, objArrayOop local_interfaces);
+                                                   AccessFlags class_flags, Handle classloader,
+                                                   symbolHandle classname, objArrayOop local_interfaces,
+                                                   TRAPS);
 
   // RedefineClasses() API support:
   // If any entry of this vtable points to any of old_methods,
@@ -111,14 +112,16 @@
  protected:
   friend class vtableEntry;
  private:
+  enum { VTABLE_TRANSITIVE_OVERRIDE_VERSION = 51 } ;
   void copy_vtable_to(vtableEntry* start);
   int  initialize_from_super(KlassHandle super);
   int  index_of(methodOop m, int len) const; // same as index_of, but search only up to len
   void put_method_at(methodOop m, int index);
-  static bool needs_new_vtable_entry(methodOop m, klassOop super, oop classloader, symbolOop classname, AccessFlags access_flags);
-  AccessType vtable_accessibility_at(int i);
+  static bool needs_new_vtable_entry(methodHandle m, klassOop super, Handle classloader, symbolHandle classname, AccessFlags access_flags, TRAPS);
 
-  bool update_super_vtable(instanceKlass* klass, methodHandle target_method, int super_vtable_len, bool checkconstraints, TRAPS);
+  bool update_inherited_vtable(instanceKlass* klass, methodHandle target_method, int super_vtable_len, bool checkconstraints, TRAPS);
+ instanceKlass* find_transitive_override(instanceKlass* initialsuper, methodHandle target_method, int vtable_index,
+                                         Handle target_loader, symbolHandle target_classname, Thread* THREAD);
 
   // support for miranda methods
   bool is_miranda_entry_at(int i);
@@ -298,6 +301,8 @@
 
   // Resolving of method to index
   static int compute_itable_index(methodOop m);
+  // ...and back again:
+  static methodOop method_for_itable_index(klassOop klass, int itable_index);
 
   // Debugging/Statistics
   static void print_statistics() PRODUCT_RETURN;
--- a/hotspot/src/share/vm/oops/methodKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/methodKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -247,9 +247,14 @@
   st->print_cr(" - size of params:    %d",   m->size_of_parameters());
   st->print_cr(" - method size:       %d",   m->method_size());
   st->print_cr(" - vtable index:      %d",   m->_vtable_index);
+  st->print_cr(" - i2i entry:         " INTPTR_FORMAT, m->interpreter_entry());
+  st->print_cr(" - adapter:           " INTPTR_FORMAT, m->adapter());
+  st->print_cr(" - compiled entry     " INTPTR_FORMAT, m->from_compiled_entry());
   st->print_cr(" - code size:         %d",   m->code_size());
-  st->print_cr(" - code start:        " INTPTR_FORMAT, m->code_base());
-  st->print_cr(" - code end (excl):   " INTPTR_FORMAT, m->code_base() + m->code_size());
+  if (m->code_size() != 0) {
+    st->print_cr(" - code start:        " INTPTR_FORMAT, m->code_base());
+    st->print_cr(" - code end (excl):   " INTPTR_FORMAT, m->code_base() + m->code_size());
+  }
   if (m->method_data() != NULL) {
     st->print_cr(" - method data:       " INTPTR_FORMAT, (address)m->method_data());
   }
@@ -293,6 +298,10 @@
     m->code()->print_value_on(st);
     st->cr();
   }
+  if (m->is_native()) {
+    st->print_cr(" - native function:   " INTPTR_FORMAT, m->native_function());
+    st->print_cr(" - signature handler: " INTPTR_FORMAT, m->signature_handler());
+  }
 }
 
 
--- a/hotspot/src/share/vm/oops/methodOop.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/methodOop.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/methodOop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/methodOop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -296,7 +296,7 @@
   void set_compiled_invocation_count(int count)  { _compiled_invocation_count = count; }
 #endif // not PRODUCT
 
-  // Clear (non-shared space) pointers which could not be relevent
+  // Clear (non-shared space) pointers which could not be relevant
   // if this (shared) method were mapped into another JVM.
   void remove_unshareable_info();
 
--- a/hotspot/src/share/vm/oops/objArrayKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/objArrayKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -502,12 +502,25 @@
   }
 }
 
+static int max_objArray_print_length = 4;
 
 void objArrayKlass::oop_print_value_on(oop obj, outputStream* st) {
   assert(obj->is_objArray(), "must be objArray");
+  st->print("a ");
   element_klass()->print_value_on(st);
-  st->print("a [%d] ", objArrayOop(obj)->length());
-  as_klassOop()->klass()->print_value_on(st);
+  int len = objArrayOop(obj)->length();
+  st->print("[%d] ", len);
+  obj->print_address_on(st);
+  if (PrintOopAddress || PrintMiscellaneous && (WizardMode || Verbose)) {
+    st->print("{");
+    for (int i = 0; i < len; i++) {
+      if (i > max_objArray_print_length) {
+        st->print("..."); break;
+      }
+      st->print(" "INTPTR_FORMAT, (intptr_t)(void*)objArrayOop(obj)->obj_at(i));
+    }
+    st->print(" }");
+  }
 }
 
 #endif // PRODUCT
--- a/hotspot/src/share/vm/oops/oop.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/oop.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,11 +65,7 @@
 
 void oopDesc::print_address_on(outputStream* st) const {
   if (PrintOopAddress) {
-    st->print("{");
-    if (PrintOopAddress) {
-      st->print(INTPTR_FORMAT, this);
-    }
-    st->print("}");
+    st->print("{"INTPTR_FORMAT"}", this);
   }
 }
 
--- a/hotspot/src/share/vm/oops/oop.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/oop.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/oop.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/oop.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -148,10 +148,11 @@
 
 inline narrowOop oopDesc::encode_heap_oop_not_null(oop v) {
   assert(!is_null(v), "oop value can never be zero");
-  address heap_base = Universe::heap_base();
-  uint64_t pd = (uint64_t)(pointer_delta((void*)v, (void*)heap_base, 1));
+  address base = Universe::narrow_oop_base();
+  int    shift = Universe::narrow_oop_shift();
+  uint64_t  pd = (uint64_t)(pointer_delta((void*)v, (void*)base, 1));
   assert(OopEncodingHeapMax > pd, "change encoding max if new encoding");
-  uint64_t result = pd >> LogMinObjAlignmentInBytes;
+  uint64_t result = pd >> shift;
   assert((result & CONST64(0xffffffff00000000)) == 0, "narrow oop overflow");
   return (narrowOop)result;
 }
@@ -162,8 +163,9 @@
 
 inline oop oopDesc::decode_heap_oop_not_null(narrowOop v) {
   assert(!is_null(v), "narrow oop value can never be zero");
-  address heap_base = Universe::heap_base();
-  return (oop)(void*)((uintptr_t)heap_base + ((uintptr_t)v << LogMinObjAlignmentInBytes));
+  address base = Universe::narrow_oop_base();
+  int    shift = Universe::narrow_oop_shift();
+  return (oop)(void*)((uintptr_t)base + ((uintptr_t)v << shift));
 }
 
 inline oop oopDesc::decode_heap_oop(narrowOop v) {
--- a/hotspot/src/share/vm/oops/oopsHierarchy.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/oopsHierarchy.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/typeArrayKlass.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/typeArrayKlass.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/oops/typeArrayKlass.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/oops/typeArrayKlass.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/opto/addnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/addnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -756,7 +756,13 @@
       if ( eti == NULL ) {
         // there must be one pointer among the operands
         guarantee(tptr == NULL, "must be only one pointer operand");
-        tptr = et->isa_oopptr();
+        if (UseCompressedOops && Universe::narrow_oop_shift() == 0) {
+          // 32-bits narrow oop can be the base of address expressions
+          tptr = et->make_ptr()->isa_oopptr();
+        } else {
+          // only regular oops are expected here
+          tptr = et->isa_oopptr();
+        }
         guarantee(tptr != NULL, "non-int operand must be pointer");
         if (tptr->higher_equal(tp->add_offset(tptr->offset())))
           tp = tptr; // Set more precise type for bailout
--- a/hotspot/src/share/vm/opto/block.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/block.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -181,7 +181,7 @@
 }
 
 //------------------------------has_uncommon_code------------------------------
-// Return true if the block's code implies that it is not likely to be
+// Return true if the block's code implies that it is likely to be
 // executed infrequently.  Check to see if the block ends in a Halt or
 // a low probability call.
 bool Block::has_uncommon_code() const {
@@ -909,6 +909,10 @@
               !(n->jvms() != NULL && n->jvms()->is_monitor_use(k)) ) {
             assert( b->find_node(def) < j, "uses must follow definitions" );
           }
+          if( def->is_SafePointScalarObject() ) {
+            assert(_bbs[def->_idx] == b, "SafePointScalarObject Node should be at the same block as its SafePoint node");
+            assert(_bbs[def->_idx] == _bbs[def->in(0)->_idx], "SafePointScalarObject Node should be at the same block as its control edge");
+          }
         }
       }
     }
@@ -1307,7 +1311,7 @@
       }
     } else if (e->state() == CFGEdge::open) {
       // Append traces, even without a fall-thru connection.
-      // But leave root entry at the begining of the block list.
+      // But leave root entry at the beginning of the block list.
       if (targ_trace != trace(_cfg._broot)) {
         e->set_state(CFGEdge::connected);
         src_trace->append(targ_trace);
@@ -1430,7 +1434,7 @@
     }
 
     // Backbranch to the top of a trace
-    // Scroll foward through the trace from the targ_block. If we find
+    // Scroll forward through the trace from the targ_block. If we find
     // a loop head before another loop top, use the the loop head alignment.
     for (Block *b = targ_block; b != NULL; b = next(b)) {
       if (b->has_loop_alignment()) {
--- a/hotspot/src/share/vm/opto/block.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/block.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -347,6 +347,8 @@
   // Helper function to insert a node into a block
   void schedule_node_into_block( Node *n, Block *b );
 
+  void replace_block_proj_ctrl( Node *n );
+
   // Set the basic block for pinned Nodes
   void schedule_pinned_nodes( VectorSet &visited );
 
@@ -369,6 +371,7 @@
   Block *_broot;                // Basic block of root
   uint _rpo_ctr;
   CFGLoop* _root_loop;
+  float _outer_loop_freq;       // Outmost loop frequency
 
   // Per node latency estimation, valid only during GCM
   GrowableArray<uint> _node_latency;
@@ -535,6 +538,7 @@
   void compute_loop_depth(int depth);
   void compute_freq(); // compute frequency with loop assuming head freq 1.0f
   void scale_freq();   // scale frequency by loop trip count (including outer loops)
+  float outer_loop_freq() const; // frequency of outer loop
   bool in_loop_nest(Block* b);
   float trip_count() const { return 1.0f / _exit_prob; }
   virtual bool is_loop()  { return true; }
@@ -607,7 +611,7 @@
   Block * next(Block *b) const { return _next_list[b->_pre_order]; }
   void set_next(Block *b, Block *n) const { _next_list[b->_pre_order] = n; }
 
-  // Return the block that preceeds "b" in the trace.
+  // Return the block that precedes "b" in the trace.
   Block * prev(Block *b) const { return _prev_list[b->_pre_order]; }
   void set_prev(Block *b, Block *p) const { _prev_list[b->_pre_order] = p; }
 
--- a/hotspot/src/share/vm/opto/buildOopMap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/buildOopMap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -55,7 +55,7 @@
 // breadth-first approach but it was worse (showed O(n^2) in the
 // pick-next-block code).
 //
-// The relevent data is kept in a struct of arrays (it could just as well be
+// The relevant data is kept in a struct of arrays (it could just as well be
 // an array of structs, but the struct-of-arrays is generally a little more
 // efficient).  The arrays are indexed by register number (including
 // stack-slots as registers) and so is bounded by 200 to 300 elements in
--- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -232,6 +232,14 @@
     return "disallowed by CompilerOracle";
   }
 
+  if (UseStringCache) {
+    // Do not inline StringCache::profile() method used only at the beginning.
+    if (callee_method->name() == ciSymbol::profile_name() &&
+        callee_method->holder()->name() == ciSymbol::java_lang_StringCache()) {
+      return "profiling method";
+    }
+  }
+
   return NULL;
 }
 
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -391,7 +391,7 @@
   product(intx, EliminateAllocationArraySizeLimit, 64,                      \
           "Array size (number of elements) limit for scalar replacement")   \
                                                                             \
-  product(bool, UseOptoBiasInlining, true,                                 \
+  product(bool, UseOptoBiasInlining, true,                                  \
           "Generate biased locking code in C2 ideal graph")                 \
                                                                             \
   product(intx, ValueSearchLimit, 1000,                                     \
@@ -410,7 +410,7 @@
           "Miniumum %% of a successor (predecessor) for which block layout "\
           "a will allow a fork (join) in a single chain")                   \
                                                                             \
-  product(bool, BlockLayoutRotateLoops, false,                              \
+  product(bool, BlockLayoutRotateLoops, true,                               \
           "Allow back branches to be fall throughs in the block layour")    \
 
 C2_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_NOTPRODUCT_FLAG)
--- a/hotspot/src/share/vm/opto/callnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/callnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -975,6 +975,7 @@
 }
 
 bool SafePointScalarObjectNode::pinned() const { return true; }
+bool SafePointScalarObjectNode::depends_only_on_test() const { return false; }
 
 uint SafePointScalarObjectNode::ideal_reg() const {
   return 0; // No matching to machine instruction
--- a/hotspot/src/share/vm/opto/callnode.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/callnode.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -437,6 +437,10 @@
   // of the SafePoint node for which it was generated.
   virtual bool pinned() const; // { return true; }
 
+  // SafePointScalarObject depends on the SafePoint node
+  // for which it was generated.
+  virtual bool depends_only_on_test() const; // { return false; }
+
   virtual uint size_of() const { return sizeof(*this); }
 
   // Assumes that "this" is an argument to a safepoint node "s", and that
--- a/hotspot/src/share/vm/opto/cfgnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/cfgnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1350,7 +1350,7 @@
   }
 
   // Register the new node but do not transform it.  Cannot transform until the
-  // entire Region/Phi conglerate has been hacked as a single huge transform.
+  // entire Region/Phi conglomerate has been hacked as a single huge transform.
   igvn->register_new_node_with_optimizer( newn );
   // Now I can point to the new node.
   n->add_req(newn);
@@ -1381,7 +1381,7 @@
   Node *val = phi->in(i);       // Constant to split for
   uint hit = 0;                 // Number of times it occurs
 
-  for( ; i < phi->req(); i++ ){ // Count occurances of constant
+  for( ; i < phi->req(); i++ ){ // Count occurrences of constant
     Node *n = phi->in(i);
     if( !n ) return NULL;
     if( phase->type(n) == Type::TOP ) return NULL;
@@ -1423,7 +1423,7 @@
 
 //=============================================================================
 //------------------------------simple_data_loop_check-------------------------
-//  Try to determing if the phi node in a simple safe/unsafe data loop.
+//  Try to determining if the phi node in a simple safe/unsafe data loop.
 //  Returns:
 // enum LoopSafety { Safe = 0, Unsafe, UnsafeLoop };
 // Safe       - safe case when the phi and it's inputs reference only safe data
@@ -1687,7 +1687,7 @@
               progress = phase->C->top();
               break;
             }
-            // If tranformed to a MergeMem, get the desired slice
+            // If transformed to a MergeMem, get the desired slice
             // Otherwise the returned node represents memory for every slice
             Node *new_mem = (m->is_MergeMem()) ?
                              m->as_MergeMem()->memory_at(alias_idx) : m;
@@ -1962,7 +1962,7 @@
         f[CatchProjNode::fall_through_index] = Type::TOP;
       } else if( call->req() > TypeFunc::Parms ) {
         const Type *arg0 = phase->type( call->in(TypeFunc::Parms) );
-        // Check for null reciever to virtual or interface calls
+        // Check for null receiver to virtual or interface calls
         if( call->is_CallDynamicJava() &&
             arg0->higher_equal(TypePtr::NULL_PTR) ) {
           f[CatchProjNode::fall_through_index] = Type::TOP;
@@ -1995,7 +1995,7 @@
   // also remove any exception table entry.  Thus we must know the call
   // feeding the Catch will not really throw an exception.  This is ok for
   // the main fall-thru control (happens when we know a call can never throw
-  // an exception) or for "rethrow", because a further optimnization will
+  // an exception) or for "rethrow", because a further optimization will
   // yank the rethrow (happens when we inline a function that can throw an
   // exception and the caller has no handler).  Not legal, e.g., for passing
   // a NULL receiver to a v-call, or passing bad types to a slow-check-cast.
--- a/hotspot/src/share/vm/opto/chaitin.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/chaitin.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -149,6 +149,9 @@
 #endif
 {
   NOT_PRODUCT( Compile::TracePhase t3("ctorChaitin", &_t_ctorChaitin, TimeCompiler); )
+
+  _high_frequency_lrg = MIN2(float(OPTO_LRG_HIGH_FREQ), _cfg._outer_loop_freq);
+
   uint i,j;
   // Build a list of basic blocks, sorted by frequency
   _blks = NEW_RESOURCE_ARRAY( Block *, _cfg._num_blocks );
@@ -1246,7 +1249,7 @@
 
       // If the live range is not bound, then we actually had some choices
       // to make.  In this case, the mask has more bits in it than the colors
-      // choosen.  Restrict the mask to just what was picked.
+      // chosen.  Restrict the mask to just what was picked.
       if( lrg->num_regs() == 1 ) { // Size 1 live range
         lrg->Clear();           // Clear the mask
         lrg->Insert(reg);       // Set regmask to match selected reg
--- a/hotspot/src/share/vm/opto/chaitin.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/chaitin.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,7 +327,7 @@
   // True if lidx is used before any real register is def'd in the block
   bool prompt_use( Block *b, uint lidx );
   Node *get_spillcopy_wide( Node *def, Node *use, uint uidx );
-  // Insert the spill at chosen location.  Skip over any interveneing Proj's or
+  // Insert the spill at chosen location.  Skip over any intervening Proj's or
   // Phis.  Skip over a CatchNode and projs, inserting in the fall-through block
   // instead.  Update high-pressure indices.  Create a new live range.
   void insert_proj( Block *b, uint i, Node *spill, uint maxlrg );
@@ -338,6 +338,8 @@
 
   Block **_blks;                // Array of blocks sorted by frequency for coalescing
 
+  float _high_frequency_lrg;    // Frequency at which LRG will be spilled for debug info
+
 #ifndef PRODUCT
   bool _trace_spilling;
 #endif
@@ -360,6 +362,8 @@
 
   uint n2lidx( const Node *n ) const { return _names[n->_idx]; }
 
+  float high_frequency_lrg() const { return _high_frequency_lrg; }
+
 #ifndef PRODUCT
   bool trace_spilling() const { return _trace_spilling; }
 #endif
@@ -431,7 +435,7 @@
   void Simplify();
 
   // Select colors by re-inserting edges into the IFG.
-  // Return TRUE if any spills occured.
+  // Return TRUE if any spills occurred.
   uint Select( );
   // Helper function for select which allows biased coloring
   OptoReg::Name choose_color( LRG &lrg, int chunk );
--- a/hotspot/src/share/vm/opto/classes.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/classes.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -129,11 +129,13 @@
 macro(LShiftI)
 macro(LShiftL)
 macro(LoadB)
+macro(LoadUB)
 macro(LoadUS)
 macro(LoadD)
 macro(LoadD_unaligned)
 macro(LoadF)
 macro(LoadI)
+macro(LoadUI2L)
 macro(LoadKlass)
 macro(LoadNKlass)
 macro(LoadL)
@@ -182,6 +184,8 @@
 macro(Parm)
 macro(PartialSubtypeCheck)
 macro(Phi)
+macro(PopCountI)
+macro(PopCountL)
 macro(PowD)
 macro(PrefetchRead)
 macro(PrefetchWrite)
@@ -214,6 +218,8 @@
 macro(StoreP)
 macro(StoreN)
 macro(StrComp)
+macro(StrEquals)
+macro(StrIndexOf)
 macro(SubD)
 macro(SubF)
 macro(SubI)
--- a/hotspot/src/share/vm/opto/coalesce.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/coalesce.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -123,7 +123,7 @@
 }
 
 //------------------------------clone_projs------------------------------------
-// After cloning some rematierialized instruction, clone any MachProj's that
+// After cloning some rematerialized instruction, clone any MachProj's that
 // follow it.  Example: Intel zero is XOR, kills flags.  Sparc FP constants
 // use G3 as an address temp.
 int PhaseChaitin::clone_projs( Block *b, uint idx, Node *con, Node *copy, uint &maxlrg ) {
@@ -473,7 +473,7 @@
         } // End of is two-adr
 
         // Insert a copy at a debug use for a lrg which has high frequency
-        if( (b->_freq < OPTO_DEBUG_SPLIT_FREQ) && n->is_MachSafePoint() ) {
+        if( b->_freq < OPTO_DEBUG_SPLIT_FREQ || b->is_uncommon(_phc._cfg._bbs) ) {
           // Walk the debug inputs to the node and check for lrg freq
           JVMState* jvms = n->jvms();
           uint debug_start = jvms ? jvms->debug_start() : 999999;
@@ -487,7 +487,7 @@
             LRG &lrg = lrgs(nidx);
 
             // If this lrg has a high frequency use/def
-            if( lrg._maxfreq >= OPTO_LRG_HIGH_FREQ ) {
+            if( lrg._maxfreq >= _phc.high_frequency_lrg() ) {
               // If the live range is also live out of this block (like it
               // would be for a fast/slow idiom), the normal spill mechanism
               // does an excellent job.  If it is not live out of this block
@@ -694,8 +694,8 @@
           } // End of if not infinite-stack neighbor
         } // End of if actually inserted
       } // End of if live range overlaps
-    } // End of else collect intereferences for 1 node
-  } // End of while forever, scan back for intereferences
+    } // End of else collect interferences for 1 node
+  } // End of while forever, scan back for interferences
   return reg_degree;
 }
 
@@ -786,7 +786,7 @@
   if( rm_size == 0 ) return false;
 
   // Another early bail-out test is when we are double-coalescing and the
-  // 2 copies are seperated by some control flow.
+  // 2 copies are separated by some control flow.
   if( dst_copy != src_copy ) {
     Block *src_b = _phc._cfg._bbs[src_copy->_idx];
     Block *b2 = b;
--- a/hotspot/src/share/vm/opto/compile.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/compile.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -337,7 +337,7 @@
     tty->print_cr("*********************************************************");
   }
   if (env()->break_at_compile()) {
-    // Open the debugger when compiing this method.
+    // Open the debugger when compiling this method.
     tty->print("### Breaking when compiling: ");
     method()->print_short_name();
     tty->cr();
@@ -1191,8 +1191,8 @@
     default: ShouldNotReachHere();
     }
     break;
-  case 2:                       // No collasping at level 2; keep all splits
-  case 3:                       // No collasping at level 3; keep all splits
+  case 2:                       // No collapsing at level 2; keep all splits
+  case 3:                       // No collapsing at level 3; keep all splits
     break;
   default:
     Unimplemented();
@@ -2005,8 +2005,10 @@
   case Op_StoreP:
   case Op_StoreN:
   case Op_LoadB:
+  case Op_LoadUB:
   case Op_LoadUS:
   case Op_LoadI:
+  case Op_LoadUI2L:
   case Op_LoadKlass:
   case Op_LoadNKlass:
   case Op_LoadL:
@@ -2079,7 +2081,7 @@
 
 #ifdef _LP64
   case Op_CastPP:
-    if (n->in(1)->is_DecodeN() && UseImplicitNullCheckForNarrowOop) {
+    if (n->in(1)->is_DecodeN() && Universe::narrow_oop_use_implicit_null_checks()) {
       Compile* C = Compile::current();
       Node* in1 = n->in(1);
       const Type* t = n->bottom_type();
@@ -2102,7 +2104,7 @@
         // [base_reg + offset]
         // NullCheck base_reg
         //
-        // Pin the new DecodeN node to non-null path on these patforms (Sparc)
+        // Pin the new DecodeN node to non-null path on these platform (Sparc)
         // to keep the information to which NULL check the new DecodeN node
         // corresponds to use it as value in implicit_null_check().
         //
@@ -2134,7 +2136,7 @@
         new_in2 = in2->in(1);
       } else if (in2->Opcode() == Op_ConP) {
         const Type* t = in2->bottom_type();
-        if (t == TypePtr::NULL_PTR && UseImplicitNullCheckForNarrowOop) {
+        if (t == TypePtr::NULL_PTR && Universe::narrow_oop_use_implicit_null_checks()) {
           new_in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
           //
           // This transformation together with CastPP transformation above
--- a/hotspot/src/share/vm/opto/connode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/connode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -71,7 +71,7 @@
 to figure out which test post-dominates.  The real problem is that it doesn't
 matter which one you pick.  After you pick up, the dominating-test elider in
 IGVN can remove the test and allow you to hoist up to the dominating test on
-the choosen oop bypassing the test on the not-choosen oop.  Seen in testing.
+the chosen oop bypassing the test on the not-chosen oop.  Seen in testing.
 Oops.
 
 (3) Leave the CastPP's in.  This makes the graph more accurate in some sense;
@@ -433,7 +433,7 @@
 // If not converting int->oop, throw away cast after constant propagation
 Node *CastPPNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
   const Type *t = ccp->type(in(1));
-  if (!t->isa_oop_ptr() || in(1)->is_DecodeN()) {
+  if (!t->isa_oop_ptr() || (in(1)->is_DecodeN() && Universe::narrow_oop_use_implicit_null_checks())) {
     return NULL; // do not transform raw pointers or narrow oops
   }
   return ConstraintCastNode::Ideal_DU_postCCP(ccp);
--- a/hotspot/src/share/vm/opto/connode.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/connode.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -635,3 +635,23 @@
   virtual uint ideal_reg() const { return Op_RegL; }
   virtual const Type* Value( PhaseTransform *phase ) const;
 };
+
+//---------- PopCountINode -----------------------------------------------------
+// Population count (bit count) of an integer.
+class PopCountINode : public Node {
+public:
+  PopCountINode(Node* in1) : Node(0, in1) {}
+  virtual int Opcode() const;
+  const Type* bottom_type() const { return TypeInt::INT; }
+  virtual uint ideal_reg() const { return Op_RegI; }
+};
+
+//---------- PopCountLNode -----------------------------------------------------
+// Population count (bit count) of a long.
+class PopCountLNode : public Node {
+public:
+  PopCountLNode(Node* in1) : Node(0, in1) {}
+  virtual int Opcode() const;
+  const Type* bottom_type() const { return TypeInt::INT; }
+  virtual uint ideal_reg() const { return Op_RegI; }
+};
--- a/hotspot/src/share/vm/opto/divnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/divnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -35,7 +35,7 @@
 // by constant into a multiply/shift/add series. Return false if calculations
 // fail.
 //
-// Borrowed almost verbatum from Hacker's Delight by Henry S. Warren, Jr. with
+// Borrowed almost verbatim from Hacker's Delight by Henry S. Warren, Jr. with
 // minor type name and parameter changes.
 static bool magic_int_divide_constants(jint d, jint &M, jint &s) {
   int32_t p;
@@ -202,7 +202,7 @@
 // by constant into a multiply/shift/add series. Return false if calculations
 // fail.
 //
-// Borrowed almost verbatum from Hacker's Delight by Henry S. Warren, Jr. with
+// Borrowed almost verbatim from Hacker's Delight by Henry S. Warren, Jr. with
 // minor type name and parameter changes.  Adjusted to 64 bit word width.
 static bool magic_long_divide_constants(jlong d, jlong &M, jint &s) {
   int64_t p;
@@ -1069,7 +1069,7 @@
 
   int log2_con = -1;
 
-  // If this is a power of two, they maybe we can mask it
+  // If this is a power of two, then maybe we can mask it
   if( is_power_of_2_long(pos_con) ) {
     log2_con = log2_long(pos_con);
 
--- a/hotspot/src/share/vm/opto/domgraph.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/domgraph.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -183,7 +183,7 @@
       if (pre_order == 1)
         t->_parent = NULL;          // first block doesn't have parent
       else {
-        // Save parent (currernt top block on stack) in DFS
+        // Save parent (current top block on stack) in DFS
         t->_parent = &_tarjan[_stack_top->block->_pre_order];
       }
       // Now put this block on stack
--- a/hotspot/src/share/vm/opto/escape.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/escape.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -515,7 +515,7 @@
   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
   // constructor verifies correctness of the offset.
   //
-  // It could happend on subclass's branch (from the type profiling
+  // It could happened on subclass's branch (from the type profiling
   // inlining) which was not eliminated during parsing since the exactness
   // of the allocation type was not propagated to the subclass type check.
   //
@@ -703,7 +703,7 @@
   while (prev != result) {
     prev = result;
     if (result == start_mem)
-      break;  // hit one of our sentinals
+      break;  // hit one of our sentinels
     if (result->is_Mem()) {
       const Type *at = phase->type(result->in(MemNode::Address));
       if (at != Type::TOP) {
@@ -720,7 +720,7 @@
     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
       Node *proj_in = result->in(0);
       if (proj_in->is_Allocate() && proj_in->_idx == (uint)tinst->instance_id()) {
-        break;  // hit one of our sentinals
+        break;  // hit one of our sentinels
       } else if (proj_in->is_Call()) {
         CallNode *call = proj_in->as_Call();
         if (!call->may_modify(tinst, phase)) {
@@ -756,6 +756,16 @@
       } else {
         break;
       }
+    } else if (result->Opcode() == Op_SCMemProj) {
+      assert(result->in(0)->is_LoadStore(), "sanity");
+      const Type *at = phase->type(result->in(0)->in(MemNode::Address));
+      if (at != Type::TOP) {
+        assert (at->isa_ptr() != NULL, "pointer type required.");
+        int idx = C->get_alias_index(at->is_ptr());
+        assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
+        break;
+      }
+      result = result->in(0)->in(MemNode::Memory);
     }
   }
   if (result->is_Phi()) {
@@ -794,7 +804,7 @@
 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
 //            search the Memory chain for a store with the appropriate type
 //            address type.  If a Phi is found, create a new version with
-//            the approriate memory slices from each of the Phi inputs.
+//            the appropriate memory slices from each of the Phi inputs.
 //            For stores, process the users as follows:
 //               MemNode:  push on memnode_worklist
 //               MergeMem: push on mergemem_worklist
@@ -1548,7 +1558,7 @@
       has_non_escaping_obj = true; // Non GlobalEscape
     Node* n = ptn->_node;
     if (n->is_Allocate() && ptn->_scalar_replaceable ) {
-      // Push scalar replaceable alocations on alloc_worklist
+      // Push scalar replaceable allocations on alloc_worklist
       // for processing in split_unique_types().
       alloc_worklist.append(n);
     }
--- a/hotspot/src/share/vm/opto/gcm.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/gcm.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,6 +57,37 @@
   }
 }
 
+//----------------------------replace_block_proj_ctrl-------------------------
+// Nodes that have is_block_proj() nodes as their control need to use
+// the appropriate Region for their actual block as their control since
+// the projection will be in a predecessor block.
+void PhaseCFG::replace_block_proj_ctrl( Node *n ) {
+  const Node *in0 = n->in(0);
+  assert(in0 != NULL, "Only control-dependent");
+  const Node *p = in0->is_block_proj();
+  if (p != NULL && p != n) {    // Control from a block projection?
+    assert(!n->pinned() || n->is_SafePointScalarObject(), "only SafePointScalarObject pinned node is expected here");
+    // Find trailing Region
+    Block *pb = _bbs[in0->_idx]; // Block-projection already has basic block
+    uint j = 0;
+    if (pb->_num_succs != 1) {  // More then 1 successor?
+      // Search for successor
+      uint max = pb->_nodes.size();
+      assert( max > 1, "" );
+      uint start = max - pb->_num_succs;
+      // Find which output path belongs to projection
+      for (j = start; j < max; j++) {
+        if( pb->_nodes[j] == in0 )
+          break;
+      }
+      assert( j < max, "must find" );
+      // Change control to match head of successor basic block
+      j -= start;
+    }
+    n->set_req(0, pb->_succs[j]->head());
+  }
+}
+
 
 //------------------------------schedule_pinned_nodes--------------------------
 // Set the basic block for Nodes pinned into blocks
@@ -68,8 +99,10 @@
     Node *n = spstack.pop();
     if( !visited.test_set(n->_idx) ) { // Test node and flag it as visited
       if( n->pinned() && !_bbs.lookup(n->_idx) ) {  // Pinned?  Nail it down!
+        assert( n->in(0), "pinned Node must have Control" );
+        // Before setting block replace block_proj control edge
+        replace_block_proj_ctrl(n);
         Node *input = n->in(0);
-        assert( input, "pinned Node must have Control" );
         while( !input->is_block_start() )
           input = input->in(0);
         Block *b = _bbs[input->_idx];  // Basic block of controlling input
@@ -158,34 +191,12 @@
       uint  i = nstack_top_i;
 
       if (i == 0) {
-        // Special control input processing.
-        // While I am here, go ahead and look for Nodes which are taking control
-        // from a is_block_proj Node.  After I inserted RegionNodes to make proper
-        // blocks, the control at a is_block_proj more properly comes from the
-        // Region being controlled by the block_proj Node.
+        // Fixup some control.  Constants without control get attached
+        // to root and nodes that use is_block_proj() nodes should be attached
+        // to the region that starts their block.
         const Node *in0 = n->in(0);
         if (in0 != NULL) {              // Control-dependent?
-          const Node *p = in0->is_block_proj();
-          if (p != NULL && p != n) {    // Control from a block projection?
-            // Find trailing Region
-            Block *pb = _bbs[in0->_idx]; // Block-projection already has basic block
-            uint j = 0;
-            if (pb->_num_succs != 1) {  // More then 1 successor?
-              // Search for successor
-              uint max = pb->_nodes.size();
-              assert( max > 1, "" );
-              uint start = max - pb->_num_succs;
-              // Find which output path belongs to projection
-              for (j = start; j < max; j++) {
-                if( pb->_nodes[j] == in0 )
-                  break;
-              }
-              assert( j < max, "must find" );
-              // Change control to match head of successor basic block
-              j -= start;
-            }
-            n->set_req(0, pb->_succs[j]->head());
-          }
+          replace_block_proj_ctrl(n);
         } else {               // n->in(0) == NULL
           if (n->req() == 1) { // This guy is a constant with NO inputs?
             n->set_req(0, _root);
@@ -226,6 +237,8 @@
         if (!n->pinned()) {
           // Set earliest legal block.
           _bbs.map(n->_idx, find_deepest_input(n, _bbs));
+        } else {
+          assert(_bbs[n->_idx] == _bbs[n->in(0)->_idx], "Pinned Node should be at the same block as its control edge");
         }
 
         if (nstack.is_empty()) {
@@ -425,6 +438,12 @@
 #endif
   assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrComp),
          "String compare is only known 'load' that does not conflict with any stores");
+  assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrEquals),
+         "String equals is a 'load' that does not conflict with any stores");
+  assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrIndexOf),
+         "String indexOf is a 'load' that does not conflict with any stores");
+  assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_AryEq),
+         "Arrays equals is a 'load' that do not conflict with any stores");
 
   if (!C->alias_type(load_alias_idx)->is_rewritable()) {
     // It is impossible to spoil this load by putting stores before it,
@@ -593,7 +612,7 @@
           if (pred_block != early) {
             // If any predecessor of the Phi matches the load's "early block",
             // we do not need a precedence edge between the Phi and 'load'
-            // since the load will be forced into a block preceeding the Phi.
+            // since the load will be forced into a block preceding the Phi.
             pred_block->set_raise_LCA_mark(load_index);
             assert(!LCA_orig->dominates(pred_block) ||
                    early->dominates(pred_block), "early is high enough");
@@ -1361,6 +1380,9 @@
   _root_loop->_freq = 1.0;
   _root_loop->scale_freq();
 
+  // Save outmost loop frequency for LRG frequency threshold
+  _outer_loop_freq = _root_loop->outer_loop_freq();
+
   // force paths ending at uncommon traps to be infrequent
   if (!C->do_freq_based_layout()) {
     Block_List worklist;
@@ -1386,7 +1408,7 @@
 #ifdef ASSERT
   for (uint i = 0; i < _num_blocks; i++ ) {
     Block *b = _blocks[i];
-    assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requiers meaningful block frequency");
+    assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");
   }
 #endif
 
@@ -1639,7 +1661,7 @@
       // successor blocks.
       assert(_num_succs == 2, "expecting 2 successors of a null check");
       // If either successor has only one predecessor, then the
-      // probabiltity estimate can be derived using the
+      // probability estimate can be derived using the
       // relative frequency of the successor and this block.
       if (_succs[i]->num_preds() == 2) {
         return _succs[i]->_freq / _freq;
@@ -1841,7 +1863,7 @@
 }
 
 //------------------------------update_succ_freq-------------------------------
-// Update the appropriate frequency associated with block 'b', a succesor of
+// Update the appropriate frequency associated with block 'b', a successor of
 // a block in this loop.
 void CFGLoop::update_succ_freq(Block* b, float freq) {
   if (b->_loop == this) {
@@ -1885,10 +1907,12 @@
 // Do a top down traversal of loop tree (visit outer loops first.)
 void CFGLoop::scale_freq() {
   float loop_freq = _freq * trip_count();
+  _freq = loop_freq;
   for (int i = 0; i < _members.length(); i++) {
     CFGElement* s = _members.at(i);
     float block_freq = s->_freq * loop_freq;
-    if (block_freq < MIN_BLOCK_FREQUENCY) block_freq = MIN_BLOCK_FREQUENCY;
+    if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)
+      block_freq = MIN_BLOCK_FREQUENCY;
     s->_freq = block_freq;
   }
   CFGLoop* ch = _child;
@@ -1898,6 +1922,14 @@
   }
 }
 
+// Frequency of outer loop
+float CFGLoop::outer_loop_freq() const {
+  if (_child != NULL) {
+    return _child->_freq;
+  }
+  return _freq;
+}
+
 #ifndef PRODUCT
 //------------------------------dump_tree--------------------------------------
 void CFGLoop::dump_tree() const {
--- a/hotspot/src/share/vm/opto/graphKit.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/graphKit.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1148,7 +1148,7 @@
   Node   *tst = _gvn.transform( btst );
 
   //-----------
-  // if peephole optimizations occured, a prior test existed.
+  // if peephole optimizations occurred, a prior test existed.
   // If a prior test existed, maybe it dominates as we can avoid this test.
   if (tst != btst && type == T_OBJECT) {
     // At this point we want to scan up the CFG to see if we can
@@ -1196,7 +1196,7 @@
   // Consider using 'Reason_class_check' instead?
 
   // To cause an implicit null check, we set the not-null probability
-  // to the maximum (PROB_MAX).  For an explicit check the probablity
+  // to the maximum (PROB_MAX).  For an explicit check the probability
   // is set to a smaller value.
   if (null_control != NULL || too_many_traps(reason)) {
     // probability is less likely
@@ -2277,7 +2277,7 @@
   r_not_subtype->init_req(1, _gvn.transform( new (C, 1) IfTrueNode (iff2) ) );
   set_control(                _gvn.transform( new (C, 1) IfFalseNode(iff2) ) );
 
-  // Check for self.  Very rare to get here, but its taken 1/3 the time.
+  // Check for self.  Very rare to get here, but it is taken 1/3 the time.
   // No performance impact (too rare) but allows sharing of secondary arrays
   // which has some footprint reduction.
   Node *cmp3 = _gvn.transform( new (C, 3) CmpPNode( subklass, superklass ) );
@@ -2286,11 +2286,27 @@
   r_ok_subtype->init_req(2, _gvn.transform( new (C, 1) IfTrueNode ( iff3 ) ) );
   set_control(               _gvn.transform( new (C, 1) IfFalseNode( iff3 ) ) );
 
+  // -- Roads not taken here: --
+  // We could also have chosen to perform the self-check at the beginning
+  // of this code sequence, as the assembler does.  This would not pay off
+  // the same way, since the optimizer, unlike the assembler, can perform
+  // static type analysis to fold away many successful self-checks.
+  // Non-foldable self checks work better here in second position, because
+  // the initial primary superclass check subsumes a self-check for most
+  // types.  An exception would be a secondary type like array-of-interface,
+  // which does not appear in its own primary supertype display.
+  // Finally, we could have chosen to move the self-check into the
+  // PartialSubtypeCheckNode, and from there out-of-line in a platform
+  // dependent manner.  But it is worthwhile to have the check here,
+  // where it can be perhaps be optimized.  The cost in code space is
+  // small (register compare, branch).
+
   // Now do a linear scan of the secondary super-klass array.  Again, no real
   // performance impact (too rare) but it's gotta be done.
-  // (The stub also contains the self-check of subklass == superklass.
   // Since the code is rarely used, there is no penalty for moving it
-  // out of line, and it can only improve I-cache density.)
+  // out of line, and it can only improve I-cache density.
+  // The decision to inline or out-of-line this final check is platform
+  // dependent, and is found in the AD file definition of PartialSubtypeCheck.
   Node* psc = _gvn.transform(
     new (C, 3) PartialSubtypeCheckNode(control(), subklass, superklass) );
 
--- a/hotspot/src/share/vm/opto/graphKit.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/graphKit.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/opto/idealGraphPrinter.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/idealGraphPrinter.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/opto/ifg.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/ifg.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -292,7 +292,7 @@
 //------------------------------interfere_with_live----------------------------
 // Interfere this register with everything currently live.  Use the RegMasks
 // to trim the set of possible interferences. Return a count of register-only
-// inteferences as an estimate of register pressure.
+// interferences as an estimate of register pressure.
 void PhaseChaitin::interfere_with_live( uint r, IndexSet *liveout ) {
   uint retval = 0;
   // Interfere with everything live.
--- a/hotspot/src/share/vm/opto/ifnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/ifnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -81,7 +81,7 @@
   uint i4;
   for( i4 = 1; i4 < phi->req(); i4++ ) {
     con1 = phi->in(i4);
-    if( !con1 ) return NULL;    // Do not optimize partially collaped merges
+    if( !con1 ) return NULL;    // Do not optimize partially collapsed merges
     if( con1->is_Con() ) break; // Found a constant
     // Also allow null-vs-not-null checks
     const TypePtr *tp = igvn->type(con1)->isa_ptr();
@@ -204,7 +204,7 @@
   //      T  F                              T  F                  T  F
   // ..s..    ..t ..                   ..s..    ..t..        ..s..    ..t..
   //
-  // Split the paths coming into the merge point into 2 seperate groups of
+  // Split the paths coming into the merge point into 2 separate groups of
   // merges.  On the left will be all the paths feeding constants into the
   // Cmp's Phi.  On the right will be the remaining paths.  The Cmp's Phi
   // will fold up into a constant; this will let the Cmp fold up as well as
@@ -236,7 +236,7 @@
   }
 
   // Register the new RegionNodes but do not transform them.  Cannot
-  // transform until the entire Region/Phi conglerate has been hacked
+  // transform until the entire Region/Phi conglomerate has been hacked
   // as a single huge transform.
   igvn->register_new_node_with_optimizer( region_c );
   igvn->register_new_node_with_optimizer( region_x );
@@ -599,7 +599,7 @@
 
 //------------------------------fold_compares----------------------------
 // See if a pair of CmpIs can be converted into a CmpU.  In some cases
-// the direction of this if is determined by the preciding if so it
+// the direction of this if is determined by the preceding if so it
 // can be eliminate entirely.  Given an if testing (CmpI n c) check
 // for an immediately control dependent if that is testing (CmpI n c2)
 // and has one projection leading to this if and the other projection
@@ -811,7 +811,7 @@
     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
     // so all checks we inspect post-dominate the top-most check we find.
     // If we are going to fail the current check and we reach the top check
-    // then we are guarenteed to fail, so just start interpreting there.
+    // then we are guaranteed to fail, so just start interpreting there.
     // We 'expand' the top 2 range checks to include all post-dominating
     // checks.
 
--- a/hotspot/src/share/vm/opto/lcm.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/lcm.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -137,6 +137,8 @@
       if( mach->in(2) != val ) continue;
       break;                    // Found a memory op?
     case Op_StrComp:
+    case Op_StrEquals:
+    case Op_StrIndexOf:
     case Op_AryEq:
       // Not a legit memory op for implicit null check regardless of
       // embedded loads
@@ -158,7 +160,14 @@
           continue;             // Give up if offset is beyond page size
         // cannot reason about it; is probably not implicit null exception
       } else {
-        const TypePtr* tptr = base->bottom_type()->is_ptr();
+        const TypePtr* tptr;
+        if (UseCompressedOops && Universe::narrow_oop_shift() == 0) {
+          // 32-bits narrow oop can be the base of address expressions
+          tptr = base->bottom_type()->make_ptr();
+        } else {
+          // only regular oops are expected here
+          tptr = base->bottom_type()->is_ptr();
+        }
         // Give up if offset is not a compile-time constant
         if( offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot )
           continue;
--- a/hotspot/src/share/vm/opto/library_call.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/library_call.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -136,6 +136,7 @@
   bool inline_string_compareTo();
   bool inline_string_indexOf();
   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
+  bool inline_string_equals();
   Node* pop_math_arg();
   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
   bool inline_math_native(vmIntrinsics::ID id);
@@ -221,6 +222,7 @@
   bool inline_unsafe_CAS(BasicType type);
   bool inline_unsafe_ordered_store(BasicType type);
   bool inline_fp_conversions(vmIntrinsics::ID id);
+  bool inline_bitCount(vmIntrinsics::ID id);
   bool inline_reverseBytes(vmIntrinsics::ID id);
 };
 
@@ -260,6 +262,7 @@
     switch (id) {
     case vmIntrinsics::_indexOf:
     case vmIntrinsics::_compareTo:
+    case vmIntrinsics::_equals:
     case vmIntrinsics::_equalsC:
       break;  // InlineNatives does not control String.compareTo
     default:
@@ -274,6 +277,9 @@
   case vmIntrinsics::_indexOf:
     if (!SpecialStringIndexOf)  return NULL;
     break;
+  case vmIntrinsics::_equals:
+    if (!SpecialStringEquals)  return NULL;
+    break;
   case vmIntrinsics::_equalsC:
     if (!SpecialArraysEquals)  return NULL;
     break;
@@ -314,6 +320,11 @@
     if (!JDK_Version::is_gte_jdk14x_version())  return NULL;
     break;
 
+  case vmIntrinsics::_bitCount_i:
+  case vmIntrinsics::_bitCount_l:
+    if (!UsePopCountInstruction)  return NULL;
+    break;
+
  default:
     break;
   }
@@ -436,6 +447,8 @@
     return inline_string_compareTo();
   case vmIntrinsics::_indexOf:
     return inline_string_indexOf();
+  case vmIntrinsics::_equals:
+    return inline_string_equals();
 
   case vmIntrinsics::_getObject:
     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, false);
@@ -617,6 +630,10 @@
   case vmIntrinsics::_longBitsToDouble:
     return inline_fp_conversions(intrinsic_id());
 
+  case vmIntrinsics::_bitCount_i:
+  case vmIntrinsics::_bitCount_l:
+    return inline_bitCount(intrinsic_id());
+
   case vmIntrinsics::_reverseBytes_i:
   case vmIntrinsics::_reverseBytes_l:
     return inline_reverseBytes((vmIntrinsics::ID) intrinsic_id());
@@ -783,6 +800,8 @@
 //------------------------------inline_string_compareTo------------------------
 bool LibraryCallKit::inline_string_compareTo() {
 
+  if (!Matcher::has_match_rule(Op_StrComp)) return false;
+
   const int value_offset = java_lang_String::value_offset_in_bytes();
   const int count_offset = java_lang_String::count_offset_in_bytes();
   const int offset_offset = java_lang_String::offset_offset_in_bytes();
@@ -820,6 +839,82 @@
   return true;
 }
 
+//------------------------------inline_string_equals------------------------
+bool LibraryCallKit::inline_string_equals() {
+
+  if (!Matcher::has_match_rule(Op_StrEquals)) return false;
+
+  const int value_offset = java_lang_String::value_offset_in_bytes();
+  const int count_offset = java_lang_String::count_offset_in_bytes();
+  const int offset_offset = java_lang_String::offset_offset_in_bytes();
+
+  _sp += 2;
+  Node* argument = pop();  // pop non-receiver first:  it was pushed second
+  Node* receiver = pop();
+
+  // Null check on self without removing any arguments.  The argument
+  // null check technically happens in the wrong place, which can lead to
+  // invalid stack traces when string compare is inlined into a method
+  // which handles NullPointerExceptions.
+  _sp += 2;
+  receiver = do_null_check(receiver, T_OBJECT);
+  //should not do null check for argument for String.equals(), because spec
+  //allows to specify NULL as argument.
+  _sp -= 2;
+
+  if (stopped()) {
+    return true;
+  }
+
+  // get String klass for instanceOf
+  ciInstanceKlass* klass = env()->String_klass();
+
+  // two paths (plus control) merge
+  RegionNode* region = new (C, 3) RegionNode(3);
+  Node* phi = new (C, 3) PhiNode(region, TypeInt::BOOL);
+
+  Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
+  Node* cmp  = _gvn.transform(new (C, 3) CmpINode(inst, intcon(1)));
+  Node* bol  = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::eq));
+
+  IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
+
+  Node* if_true  = _gvn.transform(new (C, 1) IfTrueNode(iff));
+  set_control(if_true);
+
+  const TypeInstPtr* string_type =
+    TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
+
+  // instanceOf == true
+  Node* equals =
+    _gvn.transform(new (C, 7) StrEqualsNode(
+                        control(),
+                        memory(TypeAryPtr::CHARS),
+                        memory(string_type->add_offset(value_offset)),
+                        memory(string_type->add_offset(count_offset)),
+                        memory(string_type->add_offset(offset_offset)),
+                        receiver,
+                        argument));
+
+  phi->init_req(1, _gvn.transform(equals));
+  region->init_req(1, if_true);
+
+  //instanceOf == false, fallthrough
+  Node* if_false = _gvn.transform(new (C, 1) IfFalseNode(iff));
+  set_control(if_false);
+
+  phi->init_req(2, _gvn.transform(intcon(0)));
+  region->init_req(2, if_false);
+
+  // post merge
+  set_control(_gvn.transform(region));
+  record_for_igvn(region);
+
+  push(_gvn.transform(phi));
+
+  return true;
+}
+
 //------------------------------inline_array_equals----------------------------
 bool LibraryCallKit::inline_array_equals() {
 
@@ -984,80 +1079,115 @@
   return result;
 }
 
-
 //------------------------------inline_string_indexOf------------------------
 bool LibraryCallKit::inline_string_indexOf() {
 
-  _sp += 2;
-  Node *argument = pop();  // pop non-receiver first:  it was pushed second
-  Node *receiver = pop();
-
-  // don't intrinsify is argument isn't a constant string.
-  if (!argument->is_Con()) {
-    return false;
-  }
-  const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
-  if (str_type == NULL) {
-    return false;
-  }
-  ciInstanceKlass* klass = env()->String_klass();
-  ciObject* str_const = str_type->const_oop();
-  if (str_const == NULL || str_const->klass() != klass) {
-    return false;
-  }
-  ciInstance* str = str_const->as_instance();
-  assert(str != NULL, "must be instance");
-
   const int value_offset  = java_lang_String::value_offset_in_bytes();
   const int count_offset  = java_lang_String::count_offset_in_bytes();
   const int offset_offset = java_lang_String::offset_offset_in_bytes();
 
-  ciObject* v = str->field_value_by_offset(value_offset).as_object();
-  int       o = str->field_value_by_offset(offset_offset).as_int();
-  int       c = str->field_value_by_offset(count_offset).as_int();
-  ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
-
-  // constant strings have no offset and count == length which
-  // simplifies the resulting code somewhat so lets optimize for that.
-  if (o != 0 || c != pat->length()) {
-    return false;
-  }
-
-  // Null check on self without removing any arguments.  The argument
-  // null check technically happens in the wrong place, which can lead to
-  // invalid stack traces when string compare is inlined into a method
-  // which handles NullPointerExceptions.
   _sp += 2;
-  receiver = do_null_check(receiver, T_OBJECT);
-  // No null check on the argument is needed since it's a constant String oop.
-  _sp -= 2;
-  if (stopped()) {
-    return true;
+  Node *argument = pop();  // pop non-receiver first:  it was pushed second
+  Node *receiver = pop();
+
+  Node* result;
+  if (Matcher::has_match_rule(Op_StrIndexOf) &&
+      UseSSE42Intrinsics) {
+    // Generate SSE4.2 version of indexOf
+    // We currently only have match rules that use SSE4.2
+
+    // Null check on self without removing any arguments.  The argument
+    // null check technically happens in the wrong place, which can lead to
+    // invalid stack traces when string compare is inlined into a method
+    // which handles NullPointerExceptions.
+    _sp += 2;
+    receiver = do_null_check(receiver, T_OBJECT);
+    argument = do_null_check(argument, T_OBJECT);
+    _sp -= 2;
+
+    if (stopped()) {
+      return true;
+    }
+
+    ciInstanceKlass* klass = env()->String_klass();
+    const TypeInstPtr* string_type =
+      TypeInstPtr::make(TypePtr::BotPTR, klass, false, NULL, 0);
+
+    result =
+      _gvn.transform(new (C, 7)
+                     StrIndexOfNode(control(),
+                                    memory(TypeAryPtr::CHARS),
+                                    memory(string_type->add_offset(value_offset)),
+                                    memory(string_type->add_offset(count_offset)),
+                                    memory(string_type->add_offset(offset_offset)),
+                                    receiver,
+                                    argument));
+  } else { //Use LibraryCallKit::string_indexOf
+    // don't intrinsify is argument isn't a constant string.
+    if (!argument->is_Con()) {
+     return false;
+    }
+    const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
+    if (str_type == NULL) {
+      return false;
+    }
+    ciInstanceKlass* klass = env()->String_klass();
+    ciObject* str_const = str_type->const_oop();
+    if (str_const == NULL || str_const->klass() != klass) {
+      return false;
+    }
+    ciInstance* str = str_const->as_instance();
+    assert(str != NULL, "must be instance");
+
+    ciObject* v = str->field_value_by_offset(value_offset).as_object();
+    int       o = str->field_value_by_offset(offset_offset).as_int();
+    int       c = str->field_value_by_offset(count_offset).as_int();
+    ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
+
+    // constant strings have no offset and count == length which
+    // simplifies the resulting code somewhat so lets optimize for that.
+    if (o != 0 || c != pat->length()) {
+     return false;
+    }
+
+    // Null check on self without removing any arguments.  The argument
+    // null check technically happens in the wrong place, which can lead to
+    // invalid stack traces when string compare is inlined into a method
+    // which handles NullPointerExceptions.
+    _sp += 2;
+    receiver = do_null_check(receiver, T_OBJECT);
+    // No null check on the argument is needed since it's a constant String oop.
+    _sp -= 2;
+    if (stopped()) {
+     return true;
+    }
+
+    // The null string as a pattern always returns 0 (match at beginning of string)
+    if (c == 0) {
+      push(intcon(0));
+      return true;
+    }
+
+    // Generate default indexOf
+    jchar lastChar = pat->char_at(o + (c - 1));
+    int cache = 0;
+    int i;
+    for (i = 0; i < c - 1; i++) {
+      assert(i < pat->length(), "out of range");
+      cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
+    }
+
+    int md2 = c;
+    for (i = 0; i < c - 1; i++) {
+      assert(i < pat->length(), "out of range");
+      if (pat->char_at(o + i) == lastChar) {
+        md2 = (c - 1) - i;
+      }
+    }
+
+    result = string_indexOf(receiver, pat, o, cache, md2);
   }
 
-  // The null string as a pattern always returns 0 (match at beginning of string)
-  if (c == 0) {
-    push(intcon(0));
-    return true;
-  }
-
-  jchar lastChar = pat->char_at(o + (c - 1));
-  int cache = 0;
-  int i;
-  for (i = 0; i < c - 1; i++) {
-    assert(i < pat->length(), "out of range");
-    cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
-  }
-
-  int md2 = c;
-  for (i = 0; i < c - 1; i++) {
-    assert(i < pat->length(), "out of range");
-    if (pat->char_at(o + i) == lastChar) {
-      md2 = (c - 1) - i;
-    }
-  }
-
-  Node* result = string_indexOf(receiver, pat, o, cache, md2);
   push(result);
   return true;
 }
@@ -1267,7 +1397,7 @@
   //   result = DPow(x,y);
   // }
   // if (result != result)?  {
-  //   ucommon_trap();
+  //   uncommon_trap();
   // }
   // return result;
 
@@ -1324,7 +1454,7 @@
     // Check if (y isn't int) then go to slow path
 
     Node *bol2 = _gvn.transform( new (C, 2) BoolNode( cmpinty, BoolTest::ne ) );
-    // Branch eith way
+    // Branch either way
     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
     Node *slow_path = opt_iff(r,if2); // Set region path 2
 
@@ -1714,9 +1844,30 @@
   }
 }
 
+//----------------------------inline_bitCount_int/long-----------------------
+// inline int Integer.bitCount(int)
+// inline int Long.bitCount(long)
+bool LibraryCallKit::inline_bitCount(vmIntrinsics::ID id) {
+  assert(id == vmIntrinsics::_bitCount_i || id == vmIntrinsics::_bitCount_l, "not bitCount");
+  if (id == vmIntrinsics::_bitCount_i && !Matcher::has_match_rule(Op_PopCountI)) return false;
+  if (id == vmIntrinsics::_bitCount_l && !Matcher::has_match_rule(Op_PopCountL)) return false;
+  _sp += arg_size();  // restore stack pointer
+  switch (id) {
+  case vmIntrinsics::_bitCount_i:
+    push(_gvn.transform(new (C, 2) PopCountINode(pop())));
+    break;
+  case vmIntrinsics::_bitCount_l:
+    push(_gvn.transform(new (C, 2) PopCountLNode(pop_pair())));
+    break;
+  default:
+    ShouldNotReachHere();
+  }
+  return true;
+}
+
 //----------------------------inline_reverseBytes_int/long-------------------
-// inline Int.reverseBytes(int)
-// inline Long.reverseByes(long)
+// inline Integer.reverseBytes(int)
+// inline Long.reverseBytes(long)
 bool LibraryCallKit::inline_reverseBytes(vmIntrinsics::ID id) {
   assert(id == vmIntrinsics::_reverseBytes_i || id == vmIntrinsics::_reverseBytes_l, "not reverse Bytes");
   if (id == vmIntrinsics::_reverseBytes_i && !Matcher::has_match_rule(Op_ReverseBytesI)) return false;
@@ -1915,7 +2066,7 @@
     // addition to memory membars when is_volatile. This is a little
     // too strong, but avoids the need to insert per-alias-type
     // volatile membars (for stores; compare Parse::do_put_xxx), which
-    // we cannot do effctively here because we probably only have a
+    // we cannot do effectively here because we probably only have a
     // rough approximation of type.
     need_mem_bar = true;
     // For Stores, place a memory ordering barrier now.
@@ -2099,7 +2250,7 @@
   // overly confusing.  (This is a true fact! I originally combined
   // them, but even I was confused by it!) As much code/comments as
   // possible are retained from inline_unsafe_access though to make
-  // the correspondances clearer. - dl
+  // the correspondences clearer. - dl
 
   if (callee()->is_static())  return false;  // caller must have the capability!
 
@@ -2166,7 +2317,7 @@
   int alias_idx = C->get_alias_index(adr_type);
 
   // Memory-model-wise, a CAS acts like a little synchronized block,
-  // so needs barriers on each side.  These don't't translate into
+  // so needs barriers on each side.  These don't translate into
   // actual barriers on most machines, but we still need rest of
   // compiler to respect ordering.
 
@@ -3208,7 +3359,7 @@
   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
   Node *hshifted_header= _gvn.transform( new (C, 3) URShiftXNode(header, hash_shift) );
   // This hack lets the hash bits live anywhere in the mark object now, as long
-  // as the shift drops the relevent bits into the low 32 bits.  Note that
+  // as the shift drops the relevant bits into the low 32 bits.  Note that
   // Java spec says that HashCode is an int so there's no point in capturing
   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
   hshifted_header      = ConvX2I(hshifted_header);
@@ -3255,7 +3406,7 @@
 }
 
 //---------------------------inline_native_getClass----------------------------
-// Build special case code for calls to hashCode on an object.
+// Build special case code for calls to getClass on an object.
 bool LibraryCallKit::inline_native_getClass() {
   Node* obj = null_check_receiver(callee());
   if (stopped())  return true;
@@ -4594,7 +4745,7 @@
   }
 
   // The memory edges above are precise in order to model effects around
-  // array copyies accurately to allow value numbering of field loads around
+  // array copies accurately to allow value numbering of field loads around
   // arraycopy.  Such field loads, both before and after, are common in Java
   // collections and similar classes involving header/array data structures.
   //
--- a/hotspot/src/share/vm/opto/live.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/live.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,7 +39,7 @@
 // Leftover bits become the new live-in for the predecessor block, and the pred
 // block is put on the worklist.
 //   The locally live-in stuff is computed once and added to predecessor
-// live-out sets.  This seperate compilation is done in the outer loop below.
+// live-out sets.  This separate compilation is done in the outer loop below.
 PhaseLive::PhaseLive( const PhaseCFG &cfg, LRG_List &names, Arena *arena ) : Phase(LIVE), _cfg(cfg), _names(names), _arena(arena), _live(0) {
 }
 
--- a/hotspot/src/share/vm/opto/locknode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/locknode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -121,7 +121,7 @@
   kill_dead_locals();
 
   pop();                        // Pop oop to unlock
-  // Because monitors are guarenteed paired (else we bail out), we know
+  // Because monitors are guaranteed paired (else we bail out), we know
   // the matching Lock for this Unlock.  Hence we know there is no need
   // for a null check on Unlock.
   shared_unlock(map()->peek_monitor_box(), map()->peek_monitor_obj());
--- a/hotspot/src/share/vm/opto/loopTransform.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/loopTransform.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -119,7 +119,7 @@
 
 //---------------------is_invariant_addition-----------------------------
 // Return nonzero index of invariant operand for an Add or Sub
-// of (nonconstant) invariant and variant values. Helper for reassoicate_invariants.
+// of (nonconstant) invariant and variant values. Helper for reassociate_invariants.
 int IdealLoopTree::is_invariant_addition(Node* n, PhaseIdealLoop *phase) {
   int op = n->Opcode();
   if (op == Op_AddI || op == Op_SubI) {
@@ -520,7 +520,7 @@
 //------------------------------policy_align-----------------------------------
 // Return TRUE or FALSE if the loop should be cache-line aligned.  Gather the
 // expression that does the alignment.  Note that only one array base can be
-// aligned in a loop (unless the VM guarentees mutual alignment).  Note that
+// aligned in a loop (unless the VM guarantees mutual alignment).  Note that
 // if we vectorize short memory ops into longer memory ops, we may want to
 // increase alignment.
 bool IdealLoopTree::policy_align( PhaseIdealLoop *phase ) const {
--- a/hotspot/src/share/vm/opto/loopUnswitch.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/loopUnswitch.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -131,7 +131,7 @@
 
   ProjNode* proj_false = invar_iff->proj_out(0)->as_Proj();
 
-  // Hoist invariant casts out of each loop to the appropiate
+  // Hoist invariant casts out of each loop to the appropriate
   // control projection.
 
   Node_List worklist;
--- a/hotspot/src/share/vm/opto/loopnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/loopnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -274,7 +274,7 @@
   //
   // Canonicalize the condition on the test.  If we can exactly determine
   // the trip-counter exit value, then set limit to that value and use
-  // a '!=' test.  Otherwise use conditon '<' for count-up loops and
+  // a '!=' test.  Otherwise use condition '<' for count-up loops and
   // '>' for count-down loops.  If the condition is inverted and we will
   // be rolling through MININT to MAXINT, then bail out.
 
@@ -290,7 +290,7 @@
 
   // If compare points to incr, we are ok.  Otherwise the compare
   // can directly point to the phi; in this case adjust the compare so that
-  // it points to the incr by adusting the limit.
+  // it points to the incr by adjusting the limit.
   if( cmp->in(1) == phi || cmp->in(2) == phi )
     limit = gvn->transform(new (C, 3) AddINode(limit,stride));
 
@@ -471,7 +471,7 @@
   lazy_replace( x, l );
   set_idom(l, init_control, dom_depth(x));
 
-  // Check for immediately preceeding SafePoint and remove
+  // Check for immediately preceding SafePoint and remove
   Node *sfpt2 = le->in(0);
   if( sfpt2->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt2))
     lazy_replace( sfpt2, sfpt2->in(TypeFunc::Control));
@@ -1506,7 +1506,7 @@
 
   // Build Dominators for elision of NULL checks & loop finding.
   // Since nodes do not have a slot for immediate dominator, make
-  // a persistant side array for that info indexed on node->_idx.
+  // a persistent side array for that info indexed on node->_idx.
   _idom_size = C->unique();
   _idom      = NEW_RESOURCE_ARRAY( Node*, _idom_size );
   _dom_depth = NEW_RESOURCE_ARRAY( uint,  _idom_size );
@@ -1529,7 +1529,7 @@
 
   // Given dominators, try to find inner loops with calls that must
   // always be executed (call dominates loop tail).  These loops do
-  // not need a seperate safepoint.
+  // not need a separate safepoint.
   Node_List cisstack(a);
   _ltree_root->check_safepts(visited, cisstack);
 
@@ -2332,7 +2332,7 @@
       if (done) {
         // All of n's inputs have been processed, complete post-processing.
 
-        // Compute earilest point this Node can go.
+        // Compute earliest point this Node can go.
         // CFG, Phi, pinned nodes already know their controlling input.
         if (!has_node(n)) {
           // Record earliest legal location
@@ -2668,13 +2668,15 @@
     case Op_LoadD_unaligned:
     case Op_LoadL_unaligned:
     case Op_StrComp:            // Does a bunch of load-like effects
+    case Op_StrEquals:
+    case Op_StrIndexOf:
     case Op_AryEq:
       pinned = false;
     }
     if( pinned ) {
-      IdealLoopTree *choosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
-      if( !choosen_loop->_child )       // Inner loop?
-        choosen_loop->_body.push(n); // Collect inner loops
+      IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
+      if( !chosen_loop->_child )       // Inner loop?
+        chosen_loop->_body.push(n); // Collect inner loops
       return;
     }
   } else {                      // No slot zero
@@ -2746,9 +2748,9 @@
   set_ctrl(n, least);
 
   // Collect inner loop bodies
-  IdealLoopTree *choosen_loop = get_loop(least);
-  if( !choosen_loop->_child )   // Inner loop?
-    choosen_loop->_body.push(n);// Collect inner loops
+  IdealLoopTree *chosen_loop = get_loop(least);
+  if( !chosen_loop->_child )   // Inner loop?
+    chosen_loop->_body.push(n);// Collect inner loops
 }
 
 #ifndef PRODUCT
--- a/hotspot/src/share/vm/opto/loopnode.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/loopnode.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -390,7 +390,7 @@
 
   // Return TRUE or FALSE if the loop should be cache-line aligned.
   // Gather the expression that does the alignment.  Note that only
-  // one array base can be aligned in a loop (unless the VM guarentees
+  // one array base can be aligned in a loop (unless the VM guarantees
   // mutual alignment).  Note that if we vectorize short memory ops
   // into longer memory ops, we may want to increase alignment.
   bool policy_align( PhaseIdealLoop *phase ) const;
@@ -403,7 +403,7 @@
   // Reassociate invariant add and subtract expressions.
   Node* reassociate_add_sub(Node* n1, PhaseIdealLoop *phase);
   // Return nonzero index of invariant operand if invariant and variant
-  // are combined with an Add or Sub. Helper for reassoicate_invariants.
+  // are combined with an Add or Sub. Helper for reassociate_invariants.
   int is_invariant_addition(Node* n, PhaseIdealLoop *phase);
 
   // Return true if n is invariant
--- a/hotspot/src/share/vm/opto/loopopts.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/loopopts.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -97,7 +97,7 @@
       // (Note: This tweaking with igvn only works because x is a new node.)
       _igvn.set_type(x, t);
       // If x is a TypeNode, capture any more-precise type permanently into Node
-      // othewise it will be not updated during igvn->transform since
+      // otherwise it will be not updated during igvn->transform since
       // igvn->type(x) is set to x->Value() already.
       x->raise_bottom_type(t);
       Node *y = x->Identity(&_igvn);
@@ -879,7 +879,7 @@
             Node *x_ctrl = NULL;
             if( u->is_Phi() ) {
               // Replace all uses of normal nodes.  Replace Phi uses
-              // individually, so the seperate Nodes can sink down
+              // individually, so the separate Nodes can sink down
               // different paths.
               uint k = 1;
               while( u->in(k) != n ) k++;
--- a/hotspot/src/share/vm/opto/machnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/machnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -136,7 +136,7 @@
 // Size of instruction in bytes
 uint MachNode::size(PhaseRegAlloc *ra_) const {
   // If a virtual was not defined for this specific instruction,
-  // Call the helper which finds the size by emiting the bits.
+  // Call the helper which finds the size by emitting the bits.
   return MachNode::emit_size(ra_);
 }
 
@@ -340,6 +340,10 @@
   if (base == NodeSentinel)  return TypePtr::BOTTOM;
 
   const Type* t = base->bottom_type();
+  if (UseCompressedOops && Universe::narrow_oop_shift() == 0) {
+    // 32-bit unscaled narrow oop can be the base of any address expression
+    t = t->make_ptr();
+  }
   if (t->isa_intptr_t() && offset != 0 && offset != Type::OffsetBot) {
     // We cannot assert that the offset does not look oop-ish here.
     // Depending on the heap layout the cardmark base could land
@@ -353,6 +357,7 @@
 
   // be conservative if we do not recognize the type
   if (tp == NULL) {
+    assert(false, "this path may produce not optimal code");
     return TypePtr::BOTTOM;
   }
   assert(tp->base() != Type::AnyPtr, "not a bare pointer");
--- a/hotspot/src/share/vm/opto/macro.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/macro.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,7 @@
       uint old_unique = C->unique();
       Node* new_in = old_sosn->clone(jvms_adj, sosn_map);
       if (old_unique != C->unique()) {
+        new_in->set_req(0, newcall->in(0)); // reset control edge
         new_in = transform_later(new_in); // Register new node.
       }
       old_in = new_in;
@@ -215,7 +216,7 @@
   const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
   while (true) {
     if (mem == alloc_mem || mem == start_mem ) {
-      return mem;  // hit one of our sentinals
+      return mem;  // hit one of our sentinels
     } else if (mem->is_MergeMem()) {
       mem = mem->as_MergeMem()->memory_at(alias_idx);
     } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
@@ -250,6 +251,15 @@
         assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
       }
       mem = mem->in(MemNode::Memory);
+    } else if (mem->Opcode() == Op_SCMemProj) {
+      assert(mem->in(0)->is_LoadStore(), "sanity");
+      const TypePtr* atype = mem->in(0)->in(MemNode::Address)->bottom_type()->is_ptr();
+      int adr_idx = Compile::current()->get_alias_index(atype);
+      if (adr_idx == alias_idx) {
+        assert(false, "Object is not scalar replaceable if a LoadStore node access its field");
+        return NULL;
+      }
+      mem = mem->in(0)->in(MemNode::Memory);
     } else {
       return mem;
     }
@@ -329,8 +339,15 @@
           return NULL;
         }
         values.at_put(j, val);
+      } else if (val->Opcode() == Op_SCMemProj) {
+        assert(val->in(0)->is_LoadStore(), "sanity");
+        assert(false, "Object is not scalar replaceable if a LoadStore node access its field");
+        return NULL;
       } else {
+#ifdef ASSERT
+        val->dump();
         assert(false, "unknown node on this path");
+#endif
         return NULL;  // unknown node on this path
       }
     }
@@ -1651,7 +1668,7 @@
 
   if (UseOptoBiasInlining) {
     /*
-     *  See the full descrition in MacroAssembler::biased_locking_enter().
+     *  See the full description in MacroAssembler::biased_locking_enter().
      *
      *  if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
      *    // The object is biased.
@@ -1887,7 +1904,7 @@
 
   if (UseOptoBiasInlining) {
     // Check for biased locking unlock case, which is a no-op.
-    // See the full descrition in MacroAssembler::biased_locking_exit().
+    // See the full description in MacroAssembler::biased_locking_exit().
     region  = new (C, 4) RegionNode(4);
     // create a Phi for the memory state
     mem_phi = new (C, 4) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
--- a/hotspot/src/share/vm/opto/matcher.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/matcher.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -746,6 +746,8 @@
   if (nidx == Compile::AliasIdxBot && midx == Compile::AliasIdxTop) {
     switch (n->Opcode()) {
     case Op_StrComp:
+    case Op_StrEquals:
+    case Op_StrIndexOf:
     case Op_AryEq:
     case Op_MemBarVolatile:
     case Op_MemBarCPUOrder: // %%% these ideals should have narrower adr_type?
@@ -897,7 +899,7 @@
 #ifdef ASSERT
           _new2old_map.map(m->_idx, n);
 #endif
-          mstack.push(m, Post_Visit, n, i); // Don't neet to visit
+          mstack.push(m, Post_Visit, n, i); // Don't need to visit
           mstack.push(m->in(0), Visit, m, 0);
         } else {
           mstack.push(m, Visit, n, i);
@@ -1267,7 +1269,7 @@
     }
   }
 
-  // Not forceably cloning.  If shared, put it into a register.
+  // Not forceable cloning.  If shared, put it into a register.
   return shared;
 }
 
@@ -1481,8 +1483,13 @@
       const Type* mach_at = mach->adr_type();
       // DecodeN node consumed by an address may have different type
       // then its input. Don't compare types for such case.
-      if (m->adr_type() != mach_at && m->in(MemNode::Address)->is_AddP() &&
-          m->in(MemNode::Address)->in(AddPNode::Address)->is_DecodeN()) {
+      if (m->adr_type() != mach_at &&
+          (m->in(MemNode::Address)->is_DecodeN() ||
+           m->in(MemNode::Address)->is_AddP() &&
+           m->in(MemNode::Address)->in(AddPNode::Address)->is_DecodeN() ||
+           m->in(MemNode::Address)->is_AddP() &&
+           m->in(MemNode::Address)->in(AddPNode::Address)->is_AddP() &&
+           m->in(MemNode::Address)->in(AddPNode::Address)->in(AddPNode::Address)->is_DecodeN())) {
         mach_at = m->adr_type();
       }
       if (m->adr_type() != mach_at) {
@@ -1542,7 +1549,7 @@
   // This is what my child will give me.
   int opnd_class_instance = s->_rule[op];
   // Choose between operand class or not.
-  // This is what I will recieve.
+  // This is what I will receive.
   int catch_op = (FIRST_OPERAND_CLASS <= op && op < NUM_OPERANDS) ? opnd_class_instance : op;
   // New rule for child.  Chase operand classes to get the actual rule.
   int newrule = s->_rule[catch_op];
@@ -1707,11 +1714,18 @@
 void Matcher::find_shared( Node *n ) {
   // Allocate stack of size C->unique() * 2 to avoid frequent realloc
   MStack mstack(C->unique() * 2);
+  // Mark nodes as address_visited if they are inputs to an address expression
+  VectorSet address_visited(Thread::current()->resource_area());
   mstack.push(n, Visit);     // Don't need to pre-visit root node
   while (mstack.is_nonempty()) {
     n = mstack.node();       // Leave node on stack
     Node_State nstate = mstack.state();
+    uint nop = n->Opcode();
     if (nstate == Pre_Visit) {
+      if (address_visited.test(n->_idx)) { // Visited in address already?
+        // Flag as visited and shared now.
+        set_visited(n);
+      }
       if (is_visited(n)) {   // Visited already?
         // Node is shared and has no reason to clone.  Flag it as shared.
         // This causes it to match into a register for the sharing.
@@ -1726,7 +1740,7 @@
       set_visited(n);   // Flag as visited now
       bool mem_op = false;
 
-      switch( n->Opcode() ) {  // Handle some opcodes special
+      switch( nop ) {  // Handle some opcodes special
       case Op_Phi:             // Treat Phis as shared roots
       case Op_Parm:
       case Op_Proj:            // All handled specially during matching
@@ -1776,6 +1790,8 @@
         mstack.push(n->in(0), Pre_Visit);     // Visit Control input
         continue;                             // while (mstack.is_nonempty())
       case Op_StrComp:
+      case Op_StrEquals:
+      case Op_StrIndexOf:
       case Op_AryEq:
         set_shared(n); // Force result into register (it will be anyways)
         break;
@@ -1887,34 +1903,51 @@
             // to have a single use so force sharing here.
             set_shared(m->in(AddPNode::Base)->in(1));
           }
+
+          // Some inputs for address expression are not put on stack
+          // to avoid marking them as shared and forcing them into register
+          // if they are used only in address expressions.
+          // But they should be marked as shared if there are other uses
+          // besides address expressions.
+
           Node *off = m->in(AddPNode::Offset);
-          if( off->is_Con() ) {
-            set_visited(m);  // Flag as visited now
+          if( off->is_Con() &&
+              // When there are other uses besides address expressions
+              // put it on stack and mark as shared.
+              !is_visited(m) ) {
+            address_visited.test_set(m->_idx); // Flag as address_visited
             Node *adr = m->in(AddPNode::Address);
 
             // Intel, ARM and friends can handle 2 adds in addressing mode
             if( clone_shift_expressions && adr->is_AddP() &&
                 // AtomicAdd is not an addressing expression.
                 // Cheap to find it by looking for screwy base.
-                !adr->in(AddPNode::Base)->is_top() ) {
-              set_visited(adr);  // Flag as visited now
+                !adr->in(AddPNode::Base)->is_top() &&
+                // Are there other uses besides address expressions?
+                !is_visited(adr) ) {
+              address_visited.set(adr->_idx); // Flag as address_visited
               Node *shift = adr->in(AddPNode::Offset);
               // Check for shift by small constant as well
               if( shift->Opcode() == Op_LShiftX && shift->in(2)->is_Con() &&
-                  shift->in(2)->get_int() <= 3 ) {
-                set_visited(shift);  // Flag as visited now
+                  shift->in(2)->get_int() <= 3 &&
+                  // Are there other uses besides address expressions?
+                  !is_visited(shift) ) {
+                address_visited.set(shift->_idx); // Flag as address_visited
                 mstack.push(shift->in(2), Visit);
+                Node *conv = shift->in(1);
 #ifdef _LP64
                 // Allow Matcher to match the rule which bypass
                 // ConvI2L operation for an array index on LP64
                 // if the index value is positive.
-                if( shift->in(1)->Opcode() == Op_ConvI2L &&
-                    shift->in(1)->as_Type()->type()->is_long()->_lo >= 0 ) {
-                  set_visited(shift->in(1));  // Flag as visited now
-                  mstack.push(shift->in(1)->in(1), Pre_Visit);
+                if( conv->Opcode() == Op_ConvI2L &&
+                    conv->as_Type()->type()->is_long()->_lo >= 0 &&
+                    // Are there other uses besides address expressions?
+                    !is_visited(conv) ) {
+                  address_visited.set(conv->_idx); // Flag as address_visited
+                  mstack.push(conv->in(1), Pre_Visit);
                 } else
 #endif
-                mstack.push(shift->in(1), Pre_Visit);
+                mstack.push(conv, Pre_Visit);
               } else {
                 mstack.push(shift, Pre_Visit);
               }
@@ -1942,7 +1975,7 @@
       // BoolNode::match_edge always returns a zero.
 
       // We reorder the Op_If in a pre-order manner, so we can visit without
-      // accidently sharing the Cmp (the Bool and the If make 2 users).
+      // accidentally sharing the Cmp (the Bool and the If make 2 users).
       n->add_req( n->in(1)->in(1) ); // Add the Cmp next to the Bool
     }
     else if (nstate == Post_Visit) {
--- a/hotspot/src/share/vm/opto/memnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -100,12 +100,12 @@
   while (prev != result) {
     prev = result;
     if (result == start_mem)
-      break;  // hit one of our sentinals
+      break;  // hit one of our sentinels
     // skip over a call which does not affect this memory slice
     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
       Node *proj_in = result->in(0);
       if (proj_in->is_Allocate() && proj_in->_idx == instance_id) {
-        break;  // hit one of our sentinals
+        break;  // hit one of our sentinels
       } else if (proj_in->is_Call()) {
         CallNode *call = proj_in->as_Call();
         if (!call->may_modify(t_adr, phase)) {
@@ -198,7 +198,7 @@
     // If not, we can update the input infinitely along a MergeMem cycle
     // Equivalent code in PhiNode::Ideal
     Node* m  = phase->transform(mmem);
-    // If tranformed to a MergeMem, get the desired slice
+    // If transformed to a MergeMem, get the desired slice
     // Otherwise the returned node represents memory for every slice
     mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
     // Update input if it is progress over what we have now
@@ -778,7 +778,7 @@
            adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
          "use LoadRangeNode instead");
   switch (bt) {
-  case T_BOOLEAN:
+  case T_BOOLEAN: return new (C, 3) LoadUBNode(ctl, mem, adr, adr_type, rt->is_int()    );
   case T_BYTE:    return new (C, 3) LoadBNode (ctl, mem, adr, adr_type, rt->is_int()    );
   case T_INT:     return new (C, 3) LoadINode (ctl, mem, adr, adr_type, rt->is_int()    );
   case T_CHAR:    return new (C, 3) LoadUSNode(ctl, mem, adr, adr_type, rt->is_int()    );
@@ -970,7 +970,7 @@
   }
 
   // Search for an existing data phi which was generated before for the same
-  // instance's field to avoid infinite genertion of phis in a loop.
+  // instance's field to avoid infinite generation of phis in a loop.
   Node *region = mem->in(0);
   if (is_instance_field_load_with_local_phi(region)) {
     const TypePtr *addr_t = in(MemNode::Address)->bottom_type()->isa_ptr();
@@ -1066,11 +1066,11 @@
         break;
       }
     }
-    LoadNode* load = NULL;
-    if (allocation != NULL && base->in(load_index)->is_Load()) {
-      load = base->in(load_index)->as_Load();
-    }
-    if (load != NULL && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) {
+    bool has_load = ( allocation != NULL &&
+                      (base->in(load_index)->is_Load() ||
+                       base->in(load_index)->is_DecodeN() &&
+                       base->in(load_index)->in(1)->is_Load()) );
+    if (has_load && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) {
       // Push the loads from the phi that comes from valueOf up
       // through it to allow elimination of the loads and the recovery
       // of the original value.
@@ -1106,11 +1106,20 @@
       result->set_req(load_index, in2);
       return result;
     }
-  } else if (base->is_Load()) {
+  } else if (base->is_Load() ||
+             base->is_DecodeN() && base->in(1)->is_Load()) {
+    if (base->is_DecodeN()) {
+      // Get LoadN node which loads cached Integer object
+      base = base->in(1);
+    }
     // Eliminate the load of Integer.value for integers from the cache
     // array by deriving the value from the index into the array.
     // Capture the offset of the load and then reverse the computation.
     Node* load_base = base->in(Address)->in(AddPNode::Base);
+    if (load_base->is_DecodeN()) {
+      // Get LoadN node which loads IntegerCache.cache field
+      load_base = load_base->in(1);
+    }
     if (load_base != NULL) {
       Compile::AliasType* atp = phase->C->alias_type(load_base->adr_type());
       intptr_t cache_offset;
@@ -1245,7 +1254,7 @@
       // (This tweaking with igvn only works because x is a new node.)
       igvn->set_type(x, t);
       // If x is a TypeNode, capture any more-precise type permanently into Node
-      // othewise it will be not updated during igvn->transform since
+      // otherwise it will be not updated during igvn->transform since
       // igvn->type(x) is set to x->Value() already.
       x->raise_bottom_type(t);
       Node *y = x->Identity(igvn);
@@ -1607,6 +1616,22 @@
   return LoadNode::Ideal(phase, can_reshape);
 }
 
+//--------------------------LoadUBNode::Ideal-------------------------------------
+//
+//  If the previous store is to the same address as this load,
+//  and the value stored was larger than a byte, replace this load
+//  with the value stored truncated to a byte.  If no truncation is
+//  needed, the replacement is done in LoadNode::Identity().
+//
+Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) {
+  Node* mem = in(MemNode::Memory);
+  Node* value = can_see_stored_value(mem, phase);
+  if (value && !phase->type(value)->higher_equal(_type))
+    return new (phase->C, 3) AndINode(value, phase->intcon(0xFF));
+  // Identity call will handle the case where truncation is not needed.
+  return LoadNode::Ideal(phase, can_reshape);
+}
+
 //--------------------------LoadUSNode::Ideal-------------------------------------
 //
 //  If the previous store is to the same address as this load,
@@ -2456,6 +2481,31 @@
   return remove_dead_region(phase, can_reshape) ? this : NULL;
 }
 
+// Do we match on this edge? No memory edges
+uint StrEqualsNode::match_edge(uint idx) const {
+  return idx == 5 || idx == 6;
+}
+
+//------------------------------Ideal------------------------------------------
+// Return a node which is more "ideal" than the current node.  Strip out
+// control copies
+Node *StrEqualsNode::Ideal(PhaseGVN *phase, bool can_reshape){
+  return remove_dead_region(phase, can_reshape) ? this : NULL;
+}
+
+//=============================================================================
+// Do we match on this edge? No memory edges
+uint StrIndexOfNode::match_edge(uint idx) const {
+  return idx == 5 || idx == 6;
+}
+
+//------------------------------Ideal------------------------------------------
+// Return a node which is more "ideal" than the current node.  Strip out
+// control copies
+Node *StrIndexOfNode::Ideal(PhaseGVN *phase, bool can_reshape){
+  return remove_dead_region(phase, can_reshape) ? this : NULL;
+}
+
 //------------------------------Ideal------------------------------------------
 // Return a node which is more "ideal" than the current node.  Strip out
 // control copies
@@ -2463,7 +2513,6 @@
   return remove_dead_region(phase, can_reshape) ? this : NULL;
 }
 
-
 //=============================================================================
 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
   : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
@@ -2582,7 +2631,7 @@
 // capturing of nearby memory operations.
 //
 // During macro-expansion, all captured initializations which store
-// constant values of 32 bits or smaller are coalesced (if advantagous)
+// constant values of 32 bits or smaller are coalesced (if advantageous)
 // into larger 'tiles' 32 or 64 bits.  This allows an object to be
 // initialized in fewer memory operations.  Memory words which are
 // covered by neither tiles nor non-constant stores are pre-zeroed
@@ -3669,7 +3718,7 @@
     else if (old_mmem != NULL) {
       new_mem = old_mmem->memory_at(i);
     }
-    // else preceeding memory was not a MergeMem
+    // else preceding memory was not a MergeMem
 
     // replace equivalent phis (unfortunately, they do not GVN together)
     if (new_mem != NULL && new_mem != new_base &&
--- a/hotspot/src/share/vm/opto/memnode.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/memnode.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -207,6 +207,19 @@
   virtual BasicType memory_type() const { return T_BYTE; }
 };
 
+//------------------------------LoadUBNode-------------------------------------
+// Load a unsigned byte (8bits unsigned) from memory
+class LoadUBNode : public LoadNode {
+public:
+  LoadUBNode(Node* c, Node* mem, Node* adr, const TypePtr* at, const TypeInt* ti = TypeInt::UBYTE )
+    : LoadNode(c, mem, adr, at, ti) {}
+  virtual int Opcode() const;
+  virtual uint ideal_reg() const { return Op_RegI; }
+  virtual Node* Ideal(PhaseGVN *phase, bool can_reshape);
+  virtual int store_Opcode() const { return Op_StoreB; }
+  virtual BasicType memory_type() const { return T_BYTE; }
+};
+
 //------------------------------LoadUSNode-------------------------------------
 // Load an unsigned short/char (16bits unsigned) from memory
 class LoadUSNode : public LoadNode {
@@ -232,6 +245,18 @@
   virtual BasicType memory_type() const { return T_INT; }
 };
 
+//------------------------------LoadUI2LNode-----------------------------------
+// Load an unsigned integer into long from memory
+class LoadUI2LNode : public LoadNode {
+public:
+  LoadUI2LNode(Node* c, Node* mem, Node* adr, const TypePtr* at, const TypeLong* t = TypeLong::UINT)
+    : LoadNode(c, mem, adr, at, t) {}
+  virtual int Opcode() const;
+  virtual uint ideal_reg() const { return Op_RegL; }
+  virtual int store_Opcode() const { return Op_StoreL; }
+  virtual BasicType memory_type() const { return T_LONG; }
+};
+
 //------------------------------LoadRangeNode----------------------------------
 // Load an array length from the array
 class LoadRangeNode : public LoadINode {
@@ -740,6 +765,54 @@
   virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
 };
 
+//------------------------------StrEquals-------------------------------------
+class StrEqualsNode: public Node {
+public:
+  StrEqualsNode(Node *control,
+                Node* char_array_mem,
+                Node* value_mem,
+                Node* count_mem,
+                Node* offset_mem,
+                Node* s1, Node* s2): Node(control,
+                                          char_array_mem,
+                                          value_mem,
+                                          count_mem,
+                                          offset_mem,
+                                          s1, s2) {};
+  virtual int Opcode() const;
+  virtual bool depends_only_on_test() const { return false; }
+  virtual const Type* bottom_type() const { return TypeInt::BOOL; }
+  // a StrEqualsNode (conservatively) aliases with everything:
+  virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; }
+  virtual uint match_edge(uint idx) const;
+  virtual uint ideal_reg() const { return Op_RegI; }
+  virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
+};
+
+//------------------------------StrIndexOf-------------------------------------
+class StrIndexOfNode: public Node {
+public:
+  StrIndexOfNode(Node *control,
+                 Node* char_array_mem,
+                 Node* value_mem,
+                 Node* count_mem,
+                 Node* offset_mem,
+                 Node* s1, Node* s2): Node(control,
+                                           char_array_mem,
+                                           value_mem,
+                                           count_mem,
+                                           offset_mem,
+                                           s1, s2) {};
+  virtual int Opcode() const;
+  virtual bool depends_only_on_test() const { return false; }
+  virtual const Type* bottom_type() const { return TypeInt::INT; }
+  // a StrIndexOfNode (conservatively) aliases with everything:
+  virtual const TypePtr* adr_type() const { return TypePtr::BOTTOM; }
+  virtual uint match_edge(uint idx) const;
+  virtual uint ideal_reg() const { return Op_RegI; }
+  virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
+};
+
 //------------------------------AryEq---------------------------------------
 class AryEqNode: public Node {
 public:
@@ -757,10 +830,10 @@
 // Model.  Monitor-enter and volatile-load act as Aquires: no following ref
 // can be moved to before them.  We insert a MemBar-Acquire after a FastLock or
 // volatile-load.  Monitor-exit and volatile-store act as Release: no
-// preceeding ref can be moved to after them.  We insert a MemBar-Release
+// preceding ref can be moved to after them.  We insert a MemBar-Release
 // before a FastUnlock or volatile-store.  All volatiles need to be
 // serialized, so we follow all volatile-stores with a MemBar-Volatile to
-// seperate it from any following volatile-load.
+// separate it from any following volatile-load.
 class MemBarNode: public MultiNode {
   virtual uint hash() const ;                  // { return NO_HASH; }
   virtual uint cmp( const Node &n ) const ;    // Always fail, except on self
--- a/hotspot/src/share/vm/opto/mulnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/mulnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -486,20 +486,23 @@
     return new (phase->C, 3) AndINode(ldus, phase->intcon(mask&0xFFFF));
   }
 
-  // Masking sign bits off of a Byte?  Let the matcher use an unsigned load
-  if( lop == Op_LoadB &&
-      (!in(0) && load->in(0)) &&
-      (mask == 0x000000FF) ) {
-    // Associate this node with the LoadB, so the matcher can see them together.
-    // If we don't do this, it is common for the LoadB to have one control
-    // edge, and the store or call containing this AndI to have a different
-    // control edge.  This will cause Label_Root to group the AndI with
-    // the encoding store or call, so the matcher has no chance to match
-    // this AndI together with the LoadB.  Setting the control edge here
-    // prevents Label_Root from grouping the AndI with the store or call,
-    // if it has a control edge that is inconsistent with the LoadB.
-    set_req(0, load->in(0));
-    return this;
+  // Masking sign bits off of a Byte?  Do an unsigned byte load.
+  if (lop == Op_LoadB && mask == 0x000000FF) {
+    return new (phase->C, 3) LoadUBNode(load->in(MemNode::Control),
+                                        load->in(MemNode::Memory),
+                                        load->in(MemNode::Address),
+                                        load->adr_type());
+  }
+
+  // Masking sign bits off of a Byte plus additional lower bits?  Do
+  // an unsigned byte load plus an and.
+  if (lop == Op_LoadB && (mask & 0xFFFFFF00) == 0) {
+    Node* ldub = new (phase->C, 3) LoadUBNode(load->in(MemNode::Control),
+                                              load->in(MemNode::Memory),
+                                              load->in(MemNode::Address),
+                                              load->adr_type());
+    ldub = phase->transform(ldub);
+    return new (phase->C, 3) AndINode(ldub, phase->intcon(mask));
   }
 
   // Masking off sign bits?  Dont make them!
@@ -599,12 +602,21 @@
   if( !t2 || !t2->is_con() ) return MulNode::Ideal(phase, can_reshape);
   const jlong mask = t2->get_con();
 
-  Node *rsh = in(1);
-  uint rop = rsh->Opcode();
+  Node* in1 = in(1);
+  uint op = in1->Opcode();
+
+  // Masking sign bits off of an integer?  Do an unsigned integer to long load.
+  if (op == Op_ConvI2L && in1->in(1)->Opcode() == Op_LoadI && mask == 0x00000000FFFFFFFFL) {
+    Node* load = in1->in(1);
+    return new (phase->C, 3) LoadUI2LNode(load->in(MemNode::Control),
+                                          load->in(MemNode::Memory),
+                                          load->in(MemNode::Address),
+                                          load->adr_type());
+  }
 
   // Masking off sign bits?  Dont make them!
-  if( rop == Op_RShiftL ) {
-    const TypeInt *t12 = phase->type(rsh->in(2))->isa_int();
+  if (op == Op_RShiftL) {
+    const TypeInt *t12 = phase->type(in1->in(2))->isa_int();
     if( t12 && t12->is_con() ) { // Shift is by a constant
       int shift = t12->get_con();
       shift &= BitsPerJavaLong - 1;  // semantics of Java shifts
@@ -613,7 +625,7 @@
       // bits survive.  NO sign-extension bits survive the maskings.
       if( (sign_bits_mask & mask) == 0 ) {
         // Use zero-fill shift instead
-        Node *zshift = phase->transform(new (phase->C, 3) URShiftLNode(rsh->in(1),rsh->in(2)));
+        Node *zshift = phase->transform(new (phase->C, 3) URShiftLNode(in1->in(1), in1->in(2)));
         return new (phase->C, 3) AndLNode( zshift, in(2) );
       }
     }
--- a/hotspot/src/share/vm/opto/node.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/node.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -968,22 +968,23 @@
 // Example: when reshape "(X+3)+4" into "X+7" you must leave the Node for
 // "X+3" unchanged in case it is shared.
 //
-// If you modify the 'this' pointer's inputs, you must use 'set_req' with
-// def-use info.  If you are making a new Node (either as the new root or
-// some new internal piece) you must NOT use set_req with def-use info.
-// You can make a new Node with either 'new' or 'clone'.  In either case,
-// def-use info is (correctly) not generated.
+// If you modify the 'this' pointer's inputs, you should use
+// 'set_req'.  If you are making a new Node (either as the new root or
+// some new internal piece) you may use 'init_req' to set the initial
+// value.  You can make a new Node with either 'new' or 'clone'.  In
+// either case, def-use info is correctly maintained.
+//
 // Example: reshape "(X+3)+4" into "X+7":
-//    set_req(1,in(1)->in(1) /* grab X */, du /* must use DU on 'this' */);
-//    set_req(2,phase->intcon(7),du);
+//    set_req(1, in(1)->in(1));
+//    set_req(2, phase->intcon(7));
 //    return this;
-// Example: reshape "X*4" into "X<<1"
-//    return new (C,3) LShiftINode( in(1), phase->intcon(1) );
+// Example: reshape "X*4" into "X<<2"
+//    return new (C,3) LShiftINode(in(1), phase->intcon(2));
 //
 // You must call 'phase->transform(X)' on any new Nodes X you make, except
-// for the returned root node.  Example: reshape "X*31" with "(X<<5)-1".
+// for the returned root node.  Example: reshape "X*31" with "(X<<5)-X".
 //    Node *shift=phase->transform(new(C,3)LShiftINode(in(1),phase->intcon(5)));
-//    return new (C,3) AddINode(shift, phase->intcon(-1));
+//    return new (C,3) AddINode(shift, in(1));
 //
 // When making a Node for a constant use 'phase->makecon' or 'phase->intcon'.
 // These forms are faster than 'phase->transform(new (C,1) ConNode())' and Do
@@ -1679,7 +1680,7 @@
   if (visited.member(this))  return;
   visited.push(this);
 
-  // Walk over all input edges, checking for correspondance
+  // Walk over all input edges, checking for correspondence
   for( i = 0; i < len(); i++ ) {
     n = in(i);
     if (n != NULL && !n->is_top()) {
@@ -1723,7 +1724,7 @@
   // Contained in new_space or old_space?
   VectorSet *v = C->node_arena()->contains(n) ? &new_space : &old_space;
   // Check for visited in the proper space.  Numberings are not unique
-  // across spaces so we need a seperate VectorSet for each space.
+  // across spaces so we need a separate VectorSet for each space.
   if( v->test_set(n->_idx) ) return;
 
   if (n->is_Con() && n->bottom_type() == Type::TOP) {
--- a/hotspot/src/share/vm/opto/node.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/node.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -257,7 +257,7 @@
   Node **_in;                   // Array of use-def references to Nodes
   Node **_out;                  // Array of def-use references to Nodes
 
-  // Input edges are split into two catagories.  Required edges are required
+  // Input edges are split into two categories.  Required edges are required
   // for semantic correctness; order is important and NULLs are allowed.
   // Precedence edges are used to help determine execution order and are
   // added, e.g., for scheduling purposes.  They are unordered and not
@@ -854,7 +854,7 @@
 
   // If the hash function returns the special sentinel value NO_HASH,
   // the node is guaranteed never to compare equal to any other node.
-  // If we accidently generate a hash with value NO_HASH the node
+  // If we accidentally generate a hash with value NO_HASH the node
   // won't go into the table and we'll lose a little optimization.
   enum { NO_HASH = 0 };
   virtual uint hash() const;
--- a/hotspot/src/share/vm/opto/output.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/output.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1171,7 +1171,7 @@
         cb->flush_bundle(false);
 
       // The following logic is duplicated in the code ifdeffed for
-      // ENABLE_ZAP_DEAD_LOCALS which apppears above in this file.  It
+      // ENABLE_ZAP_DEAD_LOCALS which appears above in this file.  It
       // should be factored out.  Or maybe dispersed to the nodes?
 
       // Special handling for SafePoint/Call Nodes
@@ -1275,7 +1275,7 @@
         }
 
 #ifdef ASSERT
-        // Check that oop-store preceeds the card-mark
+        // Check that oop-store precedes the card-mark
         else if( mach->ideal_Opcode() == Op_StoreCM ) {
           uint storeCM_idx = j;
           Node *oop_store = mach->in(mach->_cnt);  // First precedence edge
@@ -1291,7 +1291,7 @@
 #endif
 
         else if( !n->is_Proj() ) {
-          // Remember the begining of the previous instruction, in case
+          // Remember the beginning of the previous instruction, in case
           // it's followed by a flag-kill and a null-check.  Happens on
           // Intel all the time, with add-to-memory kind of opcodes.
           previous_offset = current_offset;
@@ -1567,7 +1567,7 @@
 
   compile.set_node_bundling_limit(_node_bundling_limit);
 
-  // This one is persistant within the Compile class
+  // This one is persistent within the Compile class
   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
 
   // Allocate space for fixed-size arrays
@@ -1666,7 +1666,7 @@
 // Compute the latency of all the instructions.  This is fairly simple,
 // because we already have a legal ordering.  Walk over the instructions
 // from first to last, and compute the latency of the instruction based
-// on the latency of the preceeding instruction(s).
+// on the latency of the preceding instruction(s).
 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
 #ifndef PRODUCT
   if (_cfg->C->trace_opto_output())
@@ -1931,7 +1931,7 @@
     uint siz = _available.size();
 
     // Conditional branches can support an instruction that
-    // is unconditionally executed and not dependant by the
+    // is unconditionally executed and not dependent by the
     // branch, OR a conditionally executed instruction if
     // the branch is taken.  In practice, this means that
     // the first instruction at the branch target is
@@ -1947,7 +1947,7 @@
 #endif
 
       // At least 1 instruction is on the available list
-      // that is not dependant on the branch
+      // that is not dependent on the branch
       for (uint i = 0; i < siz; i++) {
         Node *d = _available[i];
         const Pipeline *avail_pipeline = d->pipeline();
--- a/hotspot/src/share/vm/opto/parse.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/parse.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -78,7 +78,7 @@
   };
 
   // See if it is OK to inline.
-  // The reciever is the inline tree for the caller.
+  // The receiver is the inline tree for the caller.
   //
   // The result is a temperature indication.  If it is hot or cold,
   // inlining is immediate or undesirable.  Otherwise, the info block
--- a/hotspot/src/share/vm/opto/parse1.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/parse1.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -95,7 +95,7 @@
   switch( bt ) {                // Signature is flattened
   case T_INT:     l = new (C, 3) LoadINode( 0, mem, adr, TypeRawPtr::BOTTOM ); break;
   case T_FLOAT:   l = new (C, 3) LoadFNode( 0, mem, adr, TypeRawPtr::BOTTOM ); break;
-  case T_ADDRESS:
+  case T_ADDRESS: l = new (C, 3) LoadPNode( 0, mem, adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM  ); break;
   case T_OBJECT:  l = new (C, 3) LoadPNode( 0, mem, adr, TypeRawPtr::BOTTOM, TypeInstPtr::BOTTOM ); break;
   case T_LONG:
   case T_DOUBLE: {
@@ -607,7 +607,7 @@
       if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) {
         // In the absence of irreducible loops, the Region and Phis
         // associated with a merge that doesn't involve a backedge can
-        // be simplfied now since the RPO parsing order guarantees
+        // be simplified now since the RPO parsing order guarantees
         // that any path which was supposed to reach here has already
         // been parsed or must be dead.
         Node* c = control();
--- a/hotspot/src/share/vm/opto/parse2.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/parse2.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -32,7 +32,7 @@
 void Parse::array_load(BasicType elem_type) {
   const Type* elem = Type::TOP;
   Node* adr = array_addressing(elem_type, 0, &elem);
-  if (stopped())  return;     // guarenteed null or range check
+  if (stopped())  return;     // guaranteed null or range check
   _sp -= 2;                   // Pop array and index
   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
   Node* ld = make_load(control(), adr, elem, elem_type, adr_type);
@@ -43,7 +43,7 @@
 //--------------------------------array_store----------------------------------
 void Parse::array_store(BasicType elem_type) {
   Node* adr = array_addressing(elem_type, 1);
-  if (stopped())  return;     // guarenteed null or range check
+  if (stopped())  return;     // guaranteed null or range check
   Node* val = pop();
   _sp -= 2;                   // Pop array and index
   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
@@ -1541,14 +1541,14 @@
   case Bytecodes::_aaload: array_load(T_OBJECT); break;
   case Bytecodes::_laload: {
     a = array_addressing(T_LONG, 0);
-    if (stopped())  return;     // guarenteed null or range check
+    if (stopped())  return;     // guaranteed null or range check
     _sp -= 2;                   // Pop array and index
     push_pair( make_load(control(), a, TypeLong::LONG, T_LONG, TypeAryPtr::LONGS));
     break;
   }
   case Bytecodes::_daload: {
     a = array_addressing(T_DOUBLE, 0);
-    if (stopped())  return;     // guarenteed null or range check
+    if (stopped())  return;     // guaranteed null or range check
     _sp -= 2;                   // Pop array and index
     push_pair( make_load(control(), a, Type::DOUBLE, T_DOUBLE, TypeAryPtr::DOUBLES));
     break;
@@ -1560,7 +1560,7 @@
   case Bytecodes::_fastore: array_store(T_FLOAT); break;
   case Bytecodes::_aastore: {
     d = array_addressing(T_OBJECT, 1);
-    if (stopped())  return;     // guarenteed null or range check
+    if (stopped())  return;     // guaranteed null or range check
     array_store_check();
     c = pop();                  // Oop to store
     b = pop();                  // index (already used)
@@ -1572,7 +1572,7 @@
   }
   case Bytecodes::_lastore: {
     a = array_addressing(T_LONG, 2);
-    if (stopped())  return;     // guarenteed null or range check
+    if (stopped())  return;     // guaranteed null or range check
     c = pop_pair();
     _sp -= 2;                   // Pop array and index
     store_to_memory(control(), a, c, T_LONG, TypeAryPtr::LONGS);
@@ -1580,7 +1580,7 @@
   }
   case Bytecodes::_dastore: {
     a = array_addressing(T_DOUBLE, 2);
-    if (stopped())  return;     // guarenteed null or range check
+    if (stopped())  return;     // guaranteed null or range check
     c = pop_pair();
     _sp -= 2;                   // Pop array and index
     c = dstore_rounding(c);
--- a/hotspot/src/share/vm/opto/phase.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/phase.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -73,7 +73,7 @@
 
 //------------------------------Phase------------------------------------------
 Phase::Phase( PhaseNumber pnum ) : _pnum(pnum), C( pnum == Compiler ? NULL : Compile::current()) {
-  // Poll for requests from shutdown mechanism to quiesce comiler (4448539, 4448544).
+  // Poll for requests from shutdown mechanism to quiesce compiler (4448539, 4448544).
   // This is an effective place to poll, since the compiler is full of phases.
   // In particular, every inlining site uses a recursively created Parse phase.
   CompileBroker::maybe_block();
--- a/hotspot/src/share/vm/opto/phaseX.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/phaseX.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -196,7 +196,7 @@
 }
 
 //------------------------------hash_delete------------------------------------
-// Replace in hash table with sentinal
+// Replace in hash table with sentinel
 bool NodeHash::hash_delete( const Node *n ) {
   Node *k;
   uint hash = n->hash();
@@ -207,7 +207,7 @@
   uint key = hash & (_max-1);
   uint stride = key | 0x01;
   debug_only( uint counter = 0; );
-  for( ; /* (k != NULL) && (k != _sentinal) */; ) {
+  for( ; /* (k != NULL) && (k != _sentinel) */; ) {
     debug_only( counter++ );
     debug_only( _delete_probes++ );
     k = _table[key];            // Get hashed value
@@ -715,7 +715,7 @@
 
 #ifdef ASSERT
 //------------------------------dead_loop_check--------------------------------
-// Check for a simple dead loop when a data node references itself direcly
+// Check for a simple dead loop when a data node references itself directly
 // or through an other data node excluding cons and phis.
 void PhaseGVN::dead_loop_check( Node *n ) {
   // Phi may reference itself in a loop
@@ -1359,7 +1359,7 @@
               worklist.push(p); // Propagate change to user
           }
         }
-        // If we changed the reciever type to a call, we need to revisit
+        // If we changed the receiver type to a call, we need to revisit
         // the Catch following the call.  It's looking for a non-NULL
         // receiver to know when to enable the regular fall-through path
         // in addition to the NullPtrException path
--- a/hotspot/src/share/vm/opto/postaloc.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/postaloc.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -46,7 +46,7 @@
   // be splitting live ranges for callee save registers to such
   // an extent that in large methods the chains can be very long
   // (50+). The conservative answer is to return true if we don't
-  // know as this prevents optimizations from occuring.
+  // know as this prevents optimizations from occurring.
 
   const int limit = 60;
   int i;
@@ -286,7 +286,7 @@
     //
     // n will be replaced with the old value but n might have
     // kills projections associated with it so remove them now so that
-    // yank_if_dead will be able to elminate the copy once the uses
+    // yank_if_dead will be able to eliminate the copy once the uses
     // have been transferred to the old[value].
     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
       Node* use = n->fast_out(i);
--- a/hotspot/src/share/vm/opto/reg_split.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/reg_split.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,8 +26,8 @@
 #include "incls/_reg_split.cpp.incl"
 
 //------------------------------Split--------------------------------------
-// Walk the graph in RPO and for each lrg which spills, propogate reaching
-// definitions.  During propogation, split the live range around regions of
+// Walk the graph in RPO and for each lrg which spills, propagate reaching
+// definitions.  During propagation, split the live range around regions of
 // High Register Pressure (HRP).  If a Def is in a region of Low Register
 // Pressure (LRP), it will not get spilled until we encounter a region of
 // HRP between it and one of its uses.  We will spill at the transition
@@ -88,7 +88,7 @@
 }
 
 //------------------------------insert_proj------------------------------------
-// Insert the spill at chosen location.  Skip over any interveneing Proj's or
+// Insert the spill at chosen location.  Skip over any intervening Proj's or
 // Phis.  Skip over a CatchNode and projs, inserting in the fall-through block
 // instead.  Update high-pressure indices.  Create a new live range.
 void PhaseChaitin::insert_proj( Block *b, uint i, Node *spill, uint maxlrg ) {
@@ -125,7 +125,7 @@
 }
 
 //------------------------------split_DEF--------------------------------------
-// There are four catagories of Split; UP/DOWN x DEF/USE
+// There are four categories of Split; UP/DOWN x DEF/USE
 // Only three of these really occur as DOWN/USE will always color
 // Any Split with a DEF cannot CISC-Spill now.  Thus we need
 // two helper routines, one for Split DEFS (insert after instruction),
@@ -726,7 +726,7 @@
       // ********** Handle Crossing HRP Boundry **********
       if( (insidx == b->_ihrp_index) || (insidx == b->_fhrp_index) ) {
         for( slidx = 0; slidx < spill_cnt; slidx++ ) {
-          // Check for need to split at HRP boundry - split if UP
+          // Check for need to split at HRP boundary - split if UP
           n1 = Reachblock[slidx];
           // bail out if no reaching DEF
           if( n1 == NULL ) continue;
--- a/hotspot/src/share/vm/opto/runtime.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/runtime.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1196,7 +1196,7 @@
 
 // The following does not work because for one thing, the
 // thread state is wrong; it expects java, but it is native.
-// Also, the invarients in a native stub are different and
+// Also, the invariants in a native stub are different and
 // I'm not sure it is safe to have a MachCalRuntimeDirectNode
 // in there.
 // So for now, we do not zap in native stubs.
--- a/hotspot/src/share/vm/opto/split_if.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/split_if.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -318,7 +318,7 @@
 
   if( use->is_Phi() ) {         // Phi uses in prior block
     // Grab the first Phi use; there may be many.
-    // Each will be handled as a seperate iteration of
+    // Each will be handled as a separate iteration of
     // the "while( phi->outcnt() )" loop.
     uint j;
     for( j = 1; j < use->req(); j++ )
--- a/hotspot/src/share/vm/opto/subnode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/subnode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -639,8 +639,8 @@
     int kps = (p0->isa_klassptr()?1:0) + (p1->isa_klassptr()?1:0);
     if (klass0 && klass1 &&
         kps != 1 &&             // both or neither are klass pointers
-        !klass0->is_interface() && // do not trust interfaces
-        !klass1->is_interface()) {
+        klass0->is_loaded() && !klass0->is_interface() && // do not trust interfaces
+        klass1->is_loaded() && !klass1->is_interface()) {
       bool unrelated_classes = false;
       // See if neither subclasses the other, or if the class on top
       // is precise.  In either of these cases, the compare is known
--- a/hotspot/src/share/vm/opto/superword.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/superword.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -454,9 +454,13 @@
           // or need to run igvn.optimize() again before SLP
         } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
           // Ditto.  Not sure what else to check further.
-        } else if (out->Opcode() == Op_StoreCM && out->in(4) == n) {
+        } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
           // StoreCM has an input edge used as a precedence edge.
           // Maybe an issue when oop stores are vectorized.
+        } else if( out->is_MergeMem() && prev &&
+                   prev->Opcode() == Op_StoreCM && out == prev->in(MemNode::OopStore)) {
+          // Oop store is a MergeMem! This should not happen. Temporarily remove the assertion
+          // for this case because it could not be superwordized anyway.
         } else {
           assert(out == prev || prev == NULL, "no branches off of store slice");
         }
@@ -470,7 +474,7 @@
 }
 
 //------------------------------stmts_can_pack---------------------------
-// Can s1 and s2 be in a pack with s1 immediately preceeding s2 and
+// Can s1 and s2 be in a pack with s1 immediately preceding s2 and
 // s1 aligned at "align"
 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
   if (isomorphic(s1, s2)) {
@@ -869,7 +873,7 @@
   for (uint i = start; i < end; i++) {
     if (!is_vector_use(p0, i)) {
       // For now, return false if not scalar promotion case (inputs are the same.)
-      // Later, implement PackNode and allow differring, non-vector inputs
+      // Later, implement PackNode and allow differing, non-vector inputs
       // (maybe just the ones from outside the block.)
       Node* p0_def = p0->in(i);
       for (uint j = 1; j < p->size(); j++) {
@@ -912,54 +916,175 @@
   }
 }
 
-//------------------------------co_locate_pack---------------------------
-// Within a pack, move stores down to the last executed store,
-// and move loads up to the first executed load.
+//-------------------------------remove_and_insert-------------------
+//remove "current" from its current position in the memory graph and insert
+//it after the appropriate insertion point (lip or uip)
+void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
+                                  Node *uip, Unique_Node_List &sched_before) {
+  Node* my_mem = current->in(MemNode::Memory);
+  _igvn.hash_delete(current);
+  _igvn.hash_delete(my_mem);
+
+  //remove current_store from its current position in the memmory graph
+  for (DUIterator i = current->outs(); current->has_out(i); i++) {
+    Node* use = current->out(i);
+    if (use->is_Mem()) {
+      assert(use->in(MemNode::Memory) == current, "must be");
+      _igvn.hash_delete(use);
+      if (use == prev) { // connect prev to my_mem
+        use->set_req(MemNode::Memory, my_mem);
+      } else if (sched_before.member(use)) {
+        _igvn.hash_delete(uip);
+        use->set_req(MemNode::Memory, uip);
+      } else {
+        _igvn.hash_delete(lip);
+        use->set_req(MemNode::Memory, lip);
+      }
+      _igvn._worklist.push(use);
+      --i; //deleted this edge; rescan position
+    }
+  }
+
+  bool sched_up = sched_before.member(current);
+  Node *insert_pt =  sched_up ?  uip : lip;
+  _igvn.hash_delete(insert_pt);
+
+  // all uses of insert_pt's memory state should use current's instead
+  for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
+    Node* use = insert_pt->out(i);
+    if (use->is_Mem()) {
+      assert(use->in(MemNode::Memory) == insert_pt, "must be");
+      _igvn.hash_delete(use);
+      use->set_req(MemNode::Memory, current);
+      _igvn._worklist.push(use);
+      --i; //deleted this edge; rescan position
+    } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
+      uint pos; //lip (lower insert point) must be the last one in the memory slice
+      _igvn.hash_delete(use);
+      for (pos=1; pos < use->req(); pos++) {
+        if (use->in(pos) == insert_pt) break;
+      }
+      use->set_req(pos, current);
+      _igvn._worklist.push(use);
+      --i;
+    }
+  }
+
+  //connect current to insert_pt
+  current->set_req(MemNode::Memory, insert_pt);
+  _igvn._worklist.push(current);
+}
+
+//------------------------------co_locate_pack----------------------------------
+// To schedule a store pack, we need to move any sandwiched memory ops either before
+// or after the pack, based upon dependence information:
+// (1) If any store in the pack depends on the sandwiched memory op, the
+//     sandwiched memory op must be scheduled BEFORE the pack;
+// (2) If a sandwiched memory op depends on any store in the pack, the
+//     sandwiched memory op must be scheduled AFTER the pack;
+// (3) If a sandwiched memory op (say, memA) depends on another sandwiched
+//     memory op (say memB), memB must be scheduled before memA. So, if memA is
+//     scheduled before the pack, memB must also be scheduled before the pack;
+// (4) If there is no dependence restriction for a sandwiched memory op, we simply
+//     schedule this store AFTER the pack
+// (5) We know there is no dependence cycle, so there in no other case;
+// (6) Finally, all memory ops in another single pack should be moved in the same direction.
+//
+// To schedule a load pack: the memory edge of every loads in the pack must be
+// the same as the memory edge of the last executed load in the pack
 void SuperWord::co_locate_pack(Node_List* pk) {
   if (pk->at(0)->is_Store()) {
-    // Push Stores down towards last executed pack member
     MemNode* first     = executed_first(pk)->as_Mem();
     MemNode* last      = executed_last(pk)->as_Mem();
-    MemNode* insert_pt = last;
+    Unique_Node_List schedule_before_pack;
+    Unique_Node_List memops;
+
     MemNode* current   = last->in(MemNode::Memory)->as_Mem();
+    MemNode* previous  = last;
     while (true) {
       assert(in_bb(current), "stay in block");
+      memops.push(previous);
+      for (DUIterator i = current->outs(); current->has_out(i); i++) {
+        Node* use = current->out(i);
+        if (use->is_Mem() && use != previous)
+          memops.push(use);
+      }
+      if(current == first) break;
+      previous = current;
+      current  = current->in(MemNode::Memory)->as_Mem();
+    }
+
+    // determine which memory operations should be scheduled before the pack
+    for (uint i = 1; i < memops.size(); i++) {
+      Node *s1 = memops.at(i);
+      if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
+        for (uint j = 0; j< i; j++) {
+          Node *s2 = memops.at(j);
+          if (!independent(s1, s2)) {
+            if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
+              schedule_before_pack.push(s1); //s1 must be scheduled before
+              Node_List* mem_pk = my_pack(s1);
+              if (mem_pk != NULL) {
+                for (uint ii = 0; ii < mem_pk->size(); ii++) {
+                  Node* s = mem_pk->at(ii); // follow partner
+                  if (memops.member(s) && !schedule_before_pack.member(s))
+                    schedule_before_pack.push(s);
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+
+    MemNode* lower_insert_pt = last;
+    Node*    upper_insert_pt = first->in(MemNode::Memory);
+    previous                 = last; //previous store in pk
+    current                  = last->in(MemNode::Memory)->as_Mem();
+
+    //start scheduling from "last" to "first"
+    while (true) {
+      assert(in_bb(current), "stay in block");
+      assert(in_pack(previous, pk), "previous stays in pack");
       Node* my_mem = current->in(MemNode::Memory);
+
       if (in_pack(current, pk)) {
-        // Forward users of my memory state to my input memory state
+        // Forward users of my memory state (except "previous) to my input memory state
         _igvn.hash_delete(current);
-        _igvn.hash_delete(my_mem);
         for (DUIterator i = current->outs(); current->has_out(i); i++) {
           Node* use = current->out(i);
-          if (use->is_Mem()) {
+          if (use->is_Mem() && use != previous) {
             assert(use->in(MemNode::Memory) == current, "must be");
             _igvn.hash_delete(use);
-            use->set_req(MemNode::Memory, my_mem);
+            if (schedule_before_pack.member(use)) {
+              _igvn.hash_delete(upper_insert_pt);
+              use->set_req(MemNode::Memory, upper_insert_pt);
+            } else {
+              _igvn.hash_delete(lower_insert_pt);
+              use->set_req(MemNode::Memory, lower_insert_pt);
+            }
             _igvn._worklist.push(use);
             --i; // deleted this edge; rescan position
           }
         }
-        // put current immediately before insert_pt
-        current->set_req(MemNode::Memory, insert_pt->in(MemNode::Memory));
-        _igvn.hash_delete(insert_pt);
-        insert_pt->set_req(MemNode::Memory, current);
-        _igvn._worklist.push(insert_pt);
-        _igvn._worklist.push(current);
-        insert_pt = current;
+        previous = current;
+      } else { // !in_pack(current, pk) ==> a sandwiched store
+        remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
       }
+
       if (current == first) break;
       current = my_mem->as_Mem();
-    }
-  } else if (pk->at(0)->is_Load()) {
-    // Pull Loads up towards first executed pack member
-    LoadNode* first = executed_first(pk)->as_Load();
-    Node* first_mem = first->in(MemNode::Memory);
-    _igvn.hash_delete(first_mem);
-    // Give each load same memory state as first
+    } // end while
+  } else if (pk->at(0)->is_Load()) { //load
+    // all use the memory state that the last executed load uses
+    LoadNode* last_load  = executed_last(pk)->as_Load();
+    Node* last_mem       = last_load->in(MemNode::Memory);
+    _igvn.hash_delete(last_mem);
+    // Give each load same memory state as last
     for (uint i = 0; i < pk->size(); i++) {
       LoadNode* ld = pk->at(i)->as_Load();
       _igvn.hash_delete(ld);
-      ld->set_req(MemNode::Memory, first_mem);
+      ld->set_req(MemNode::Memory, last_mem);
       _igvn._worklist.push(ld);
     }
   }
--- a/hotspot/src/share/vm/opto/superword.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/superword.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -308,7 +308,7 @@
   void dependence_graph();
   // Return a memory slice (node list) in predecessor order starting at "start"
   void mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds);
-  // Can s1 and s2 be in a pack with s1 immediately preceeding s2 and  s1 aligned at "align"
+  // Can s1 and s2 be in a pack with s1 immediately preceding s2 and  s1 aligned at "align"
   bool stmts_can_pack(Node* s1, Node* s2, int align);
   // Does s exist in a pack at position pos?
   bool exists_at(Node* s, uint pos);
@@ -341,8 +341,11 @@
   void filter_packs();
   // Adjust the memory graph for the packed operations
   void schedule();
-  // Within a pack, move stores down to the last executed store,
-  // and move loads up to the first executed load.
+  // Remove "current" from its current position in the memory graph and insert
+  // it after the appropriate insert points (lip or uip);
+  void remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip, Node *uip, Unique_Node_List &schd_before);
+  // Within a store pack, schedule stores together by moving out the sandwiched memory ops according
+  // to dependence info; and within a load pack, move loads down to the last executed load.
   void co_locate_pack(Node_List* p);
   // Convert packs into vector node operations
   void output();
--- a/hotspot/src/share/vm/opto/type.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/type.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -226,6 +226,7 @@
   TypeInt::CC_LE   = TypeInt::make(-1, 0, WidenMin);
   TypeInt::CC_GE   = TypeInt::make( 0, 1, WidenMin);  // == TypeInt::BOOL
   TypeInt::BYTE    = TypeInt::make(-128,127,     WidenMin); // Bytes
+  TypeInt::UBYTE   = TypeInt::make(0, 255,       WidenMin); // Unsigned Bytes
   TypeInt::CHAR    = TypeInt::make(0,65535,      WidenMin); // Java chars
   TypeInt::SHORT   = TypeInt::make(-32768,32767, WidenMin); // Java shorts
   TypeInt::POS     = TypeInt::make(0,max_jint,   WidenMin); // Non-neg values
@@ -1022,6 +1023,7 @@
 const TypeInt *TypeInt::CC_LE;  // [-1,0]
 const TypeInt *TypeInt::CC_GE;  // [0,1] == BOOL (!)
 const TypeInt *TypeInt::BYTE;   // Bytes, -128 to 127
+const TypeInt *TypeInt::UBYTE;  // Unsigned Bytes, 0 to 255
 const TypeInt *TypeInt::CHAR;   // Java chars, 0-65535
 const TypeInt *TypeInt::SHORT;  // Java shorts, -32768-32767
 const TypeInt *TypeInt::POS;    // Positive 32-bit integers or zero
@@ -2455,7 +2457,7 @@
     // code and dereferenced at the time the nmethod is made.  Until that time,
     // it is not reasonable to do arithmetic with the addresses of oops (we don't
     // have access to the addresses!).  This does not seem to currently happen,
-    // but this assertion here is to help prevent its occurrance.
+    // but this assertion here is to help prevent its occurence.
     tty->print_cr("Found oop constant with non-zero offset");
     ShouldNotReachHere();
   }
@@ -2761,7 +2763,7 @@
       // LCA is object_klass, but if we subclass from the top we can do better
       if( above_centerline(_ptr) ) { // if( _ptr == TopPTR || _ptr == AnyNull )
         // If 'this' (InstPtr) is above the centerline and it is Object class
-        // then we can subclass in the Java class heirarchy.
+        // then we can subclass in the Java class hierarchy.
         if (klass()->equals(ciEnv::current()->Object_klass())) {
           // that is, tp's array type is a subtype of my klass
           return TypeAryPtr::make(ptr, tp->ary(), tp->klass(), tp->klass_is_exact(), offset, instance_id);
@@ -3022,7 +3024,7 @@
 
 //------------------------------xdual------------------------------------------
 // Dual: do NOT dual on klasses.  This means I do NOT understand the Java
-// inheritence mechanism.
+// inheritance mechanism.
 const Type *TypeInstPtr::xdual() const {
   return new TypeInstPtr( dual_ptr(), klass(), klass_is_exact(), const_oop(), dual_offset(), dual_instance_id()  );
 }
@@ -3176,7 +3178,7 @@
   bool chg = false;
   if (lo < min_lo) { lo = min_lo; chg = true; }
   if (hi > max_hi) { hi = max_hi; chg = true; }
-  // Negative length arrays will produce weird intermediate dead fath-path code
+  // Negative length arrays will produce weird intermediate dead fast-path code
   if (lo > hi)
     return TypeInt::ZERO;
   if (!chg)
@@ -3358,7 +3360,7 @@
       // LCA is object_klass, but if we subclass from the top we can do better
       if (above_centerline(tp->ptr())) {
         // If 'tp'  is above the centerline and it is Object class
-        // then we can subclass in the Java class heirarchy.
+        // then we can subclass in the Java class hierarchy.
         if( tp->klass()->equals(ciEnv::current()->Object_klass()) ) {
           // that is, my array type is a subtype of 'tp' klass
           return make( ptr, _ary, _klass, _klass_is_exact, offset, instance_id );
--- a/hotspot/src/share/vm/opto/type.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/type.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -415,6 +415,7 @@
   static const TypeInt *CC_LE;  // [-1,0]
   static const TypeInt *CC_GE;  // [0,1] == BOOL (!)
   static const TypeInt *BYTE;
+  static const TypeInt *UBYTE;
   static const TypeInt *CHAR;
   static const TypeInt *SHORT;
   static const TypeInt *POS;
--- a/hotspot/src/share/vm/opto/vectornode.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/opto/vectornode.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/prims/jni.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jni.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -301,6 +301,10 @@
   klassOop k = SystemDictionary::resolve_from_stream(class_name, class_loader,
                                                      Handle(), &st, CHECK_NULL);
 
+  if (TraceClassResolution && k != NULL) {
+    trace_class_resolution(k);
+  }
+
   cls = (jclass)JNIHandles::make_local(
     env, Klass::cast(k)->java_mirror());
   return cls;
@@ -365,6 +369,10 @@
   result = find_class_from_class_loader(env, sym, true, loader,
                                         protection_domain, true, thread);
 
+  if (TraceClassResolution && result != NULL) {
+    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
+  }
+
   // If we were the first invocation of jni_FindClass, we enable compilation again
   // rather than just allowing invocation counter to overflow and decay.
   // Controlled by flag DelayCompilationDuringStartup.
@@ -2646,7 +2654,12 @@
   Handle protection_domain; // null protection domain
 
   symbolHandle sym = oopFactory::new_symbol_handle(name, CHECK_NULL);
-  return find_class_from_class_loader(env, sym, true, loader, protection_domain, true, CHECK_NULL);
+  jclass result =  find_class_from_class_loader(env, sym, true, loader, protection_domain, true, CHECK_NULL);
+
+  if (TraceClassResolution && result != NULL) {
+    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
+  }
+  return result;
 }
 
 // These lookups are done with the NULL (bootstrap) ClassLoader to
--- a/hotspot/src/share/vm/prims/jvm.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,7 @@
   ResourceMark rm;
   int line_number = -1;
   const char * source_file = NULL;
+  const char * trace = "explicit";
   klassOop caller = NULL;
   JavaThread* jthread = JavaThread::current();
   if (jthread->has_last_Java_frame()) {
@@ -107,12 +108,21 @@
                (last_caller->name() == vmSymbols::loadClassInternal_name() ||
                 last_caller->name() == vmSymbols::loadClass_name())) {
       found_it = true;
+    } else if (!vfst.at_end()) {
+      if (vfst.method()->is_native()) {
+        // JNI call
+        found_it = true;
+      }
     }
     if (found_it && !vfst.at_end()) {
       // found the caller
       caller = vfst.method()->method_holder();
       line_number = vfst.method()->line_number_from_bci(vfst.bci());
-      symbolOop s = instanceKlass::cast(vfst.method()->method_holder())->source_file_name();
+      if (line_number == -1) {
+        // show method name if it's a native method
+        trace = vfst.method()->name_and_sig_as_C_string();
+      }
+      symbolOop s = instanceKlass::cast(caller)->source_file_name();
       if (s != NULL) {
         source_file = s->as_C_string();
       }
@@ -124,15 +134,15 @@
       const char * to = Klass::cast(to_class)->external_name();
       // print in a single call to reduce interleaving between threads
       if (source_file != NULL) {
-        tty->print("RESOLVE %s %s %s:%d (explicit)\n", from, to, source_file, line_number);
+        tty->print("RESOLVE %s %s %s:%d (%s)\n", from, to, source_file, line_number, trace);
       } else {
-        tty->print("RESOLVE %s %s (explicit)\n", from, to);
+        tty->print("RESOLVE %s %s (%s)\n", from, to, trace);
       }
     }
   }
 }
 
-static void trace_class_resolution(klassOop to_class) {
+void trace_class_resolution(klassOop to_class) {
   EXCEPTION_MARK;
   trace_class_resolution_impl(to_class, THREAD);
   if (HAS_PENDING_EXCEPTION) {
@@ -1242,7 +1252,7 @@
 
            // Throws an exception if outer klass has not declared k as
            // an inner klass
-           Reflection::check_for_inner_class(k, inner_klass, CHECK_NULL);
+           Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
 
            result->obj_at_put(members, inner_klass->java_mirror());
            members++;
@@ -1265,16 +1275,29 @@
 
 
 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
-  const int inner_class_info_index = 0;
-  const int outer_class_info_index = 1;
-
+{
   // ofClass is a reference to a java_lang_Class object.
   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
       ! Klass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)))->oop_is_instance()) {
     return NULL;
   }
 
-  instanceKlassHandle k(thread, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass)));
+  symbolOop simple_name = NULL;
+  klassOop outer_klass
+    = instanceKlass::cast(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(ofClass))
+                          )->compute_enclosing_class(simple_name, CHECK_NULL);
+  if (outer_klass == NULL)  return NULL;  // already a top-level class
+  if (simple_name == NULL)  return NULL;  // an anonymous class (inside a method)
+  return (jclass) JNIHandles::make_local(env, Klass::cast(outer_klass)->java_mirror());
+}
+JVM_END
+
+// should be in instanceKlass.cpp, but is here for historical reasons
+klassOop instanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
+                                                     symbolOop& simple_name_result, TRAPS) {
+  Thread* thread = THREAD;
+  const int inner_class_info_index = inner_class_inner_class_info_offset;
+  const int outer_class_info_index = inner_class_outer_class_info_offset;
 
   if (k->inner_classes()->length() == 0) {
     // No inner class info => no declaring class
@@ -1288,35 +1311,51 @@
   bool found = false;
   klassOop ok;
   instanceKlassHandle outer_klass;
+  bool inner_is_member = false;
+  int simple_name_index = 0;
 
   // Find inner_klass attribute
-  for(int i = 0; i < i_length && !found; i+= 4) {
+  for (int i = 0; i < i_length && !found; i += inner_class_next_offset) {
     int ioff = i_icls->ushort_at(i + inner_class_info_index);
     int ooff = i_icls->ushort_at(i + outer_class_info_index);
-
-    if (ioff != 0 && ooff != 0) {
+    int noff = i_icls->ushort_at(i + inner_class_inner_name_offset);
+    if (ioff != 0) {
       // Check to see if the name matches the class we're looking for
       // before attempting to find the class.
       if (i_cp->klass_name_at_matches(k, ioff)) {
         klassOop inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
-        if (k() == inner_klass) {
-          found = true;
+        found = (k() == inner_klass);
+        if (found && ooff != 0) {
           ok = i_cp->klass_at(ooff, CHECK_NULL);
           outer_klass = instanceKlassHandle(thread, ok);
+          simple_name_index = noff;
+          inner_is_member = true;
         }
       }
     }
   }
 
+  if (found && outer_klass.is_null()) {
+    // It may be anonymous; try for that.
+    int encl_method_class_idx = k->enclosing_method_class_index();
+    if (encl_method_class_idx != 0) {
+      ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
+      outer_klass = instanceKlassHandle(thread, ok);
+      inner_is_member = false;
+    }
+  }
+
   // If no inner class attribute found for this class.
-  if (!found) return NULL;
+  if (outer_klass.is_null())  return NULL;
 
   // Throws an exception if outer klass has not declared k as an inner klass
-  Reflection::check_for_inner_class(outer_klass, k, CHECK_NULL);
-
-  return (jclass)JNIHandles::make_local(env, outer_klass->java_mirror());
-JVM_END
-
+  // We need evidence that each klass knows about the other, or else
+  // the system could allow a spoof of an inner class to gain access rights.
+  Reflection::check_for_inner_class(outer_klass, k, inner_is_member, CHECK_NULL);
+
+  simple_name_result = (inner_is_member ? i_cp->symbol_at(simple_name_index) : symbolOop(NULL));
+  return outer_klass();
+}
 
 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
   assert (cls != NULL, "illegal class");
@@ -3213,8 +3252,12 @@
   }
   Handle h_loader(THREAD, loader);
   Handle h_prot  (THREAD, protection_domain);
-  return find_class_from_class_loader(env, name, true, h_loader, h_prot,
-                                      false, thread);
+  jclass result =  find_class_from_class_loader(env, name, true, h_loader, h_prot,
+                                                false, thread);
+  if (TraceClassResolution && result != NULL) {
+    trace_class_resolution(java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(result)));
+  }
+  return result;
 JVM_END
 
 
--- a/hotspot/src/share/vm/prims/jvm_misc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvm_misc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -27,6 +27,7 @@
 
 jclass find_class_from_class_loader(JNIEnv* env, symbolHandle name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS);
 
+void trace_class_resolution(klassOop to_class);
 
 /*
  * Support for Serialization and RMI. Currently used by HotSpot only.
--- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -99,6 +99,9 @@
     }
     // otherwise, create the state
     state = JvmtiThreadState::state_for(java_thread);
+    if (state == NULL) {
+      return JVMTI_ERROR_THREAD_NOT_ALIVE;
+    }
   }
   state->env_thread_state(this)->set_agent_thread_local_storage_data((void*)data);
   return JVMTI_ERROR_NONE;
@@ -1308,6 +1311,9 @@
 
   // retrieve or create JvmtiThreadState.
   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
+  if (state == NULL) {
+    return JVMTI_ERROR_THREAD_NOT_ALIVE;
+  }
   uint32_t debug_bits = 0;
   if (is_thread_fully_suspended(java_thread, true, &debug_bits)) {
     err = get_frame_count(state, count_ptr);
@@ -1329,6 +1335,12 @@
   HandleMark hm(current_thread);
   uint32_t debug_bits = 0;
 
+  // retrieve or create the state
+  JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
+  if (state == NULL) {
+    return JVMTI_ERROR_THREAD_NOT_ALIVE;
+  }
+
   // Check if java_thread is fully suspended
   if (!is_thread_fully_suspended(java_thread, true /* wait for suspend completion */, &debug_bits)) {
     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
@@ -1399,9 +1411,6 @@
     // It's fine to update the thread state here because no JVMTI events
     // shall be posted for this PopFrame.
 
-    // retreive or create the state
-    JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
-
     state->update_for_pop_top_frame();
     java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
     // Set pending step flag for this popframe and it is cleared when next
@@ -1445,6 +1454,11 @@
   ResourceMark rm;
   uint32_t debug_bits = 0;
 
+  JvmtiThreadState *state = JvmtiThreadState::state_for(java_thread);
+  if (state == NULL) {
+    return JVMTI_ERROR_THREAD_NOT_ALIVE;
+  }
+
   if (!JvmtiEnv::is_thread_fully_suspended(java_thread, true, &debug_bits)) {
       return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
   }
@@ -1464,7 +1478,6 @@
 
   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
 
-  JvmtiThreadState *state = JvmtiThreadState::state_for(java_thread);
   int frame_number = state->count_frames() - depth;
   state->env_thread_state(this)->set_frame_pop(frame_number);
 
--- a/hotspot/src/share/vm/prims/jvmtiEnvBase.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnvBase.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -94,6 +94,35 @@
 }
 
 
+bool
+JvmtiEnvBase::is_valid() {
+  jint value = 0;
+
+  // This object might not be a JvmtiEnvBase so we can't assume
+  // the _magic field is properly aligned. Get the value in a safe
+  // way and then check against JVMTI_MAGIC.
+
+  switch (sizeof(_magic)) {
+  case 2:
+    value = Bytes::get_native_u2((address)&_magic);
+    break;
+
+  case 4:
+    value = Bytes::get_native_u4((address)&_magic);
+    break;
+
+  case 8:
+    value = Bytes::get_native_u8((address)&_magic);
+    break;
+
+  default:
+    guarantee(false, "_magic field is an unexpected size");
+  }
+
+  return value == JVMTI_MAGIC;
+}
+
+
 JvmtiEnvBase::JvmtiEnvBase() : _env_event_enable() {
   _env_local_storage = NULL;
   _tag_map = NULL;
@@ -1322,6 +1351,12 @@
   HandleMark   hm(current_thread);
   uint32_t debug_bits = 0;
 
+  // retrieve or create the state
+  JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
+  if (state == NULL) {
+    return JVMTI_ERROR_THREAD_NOT_ALIVE;
+  }
+
   // Check if java_thread is fully suspended
   if (!is_thread_fully_suspended(java_thread,
                                  true /* wait for suspend completion */,
@@ -1329,9 +1364,6 @@
     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
   }
 
-  // retreive or create the state
-  JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
-
   // Check to see if a ForceEarlyReturn was already in progress
   if (state->is_earlyret_pending()) {
     // Probably possible for JVMTI clients to trigger this, but the
--- a/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -120,7 +120,7 @@
 
  public:
 
-  bool is_valid()                                  { return _magic == JVMTI_MAGIC; }
+  bool is_valid();
 
   bool is_retransformable()                        { return _is_retransformable; }
 
--- a/hotspot/src/share/vm/prims/jvmtiEventController.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEventController.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -478,6 +478,11 @@
 // set external state accordingly.  Only thread-filtered events are included.
 jlong
 JvmtiEventControllerPrivate::recompute_thread_enabled(JvmtiThreadState *state) {
+  if (state == NULL) {
+    // associated JavaThread is exiting
+    return (jlong)0;
+  }
+
   jlong was_any_env_enabled = state->thread_event_enable()->_event_enabled.get_bits();
   jlong any_env_enabled = 0;
 
@@ -553,6 +558,7 @@
     {
       MutexLocker mu(Threads_lock);   //hold the Threads_lock for the iteration
       for (JavaThread *tp = Threads::first(); tp != NULL; tp = tp->next()) {
+        // state_for_while_locked() makes tp->is_exiting() check
         JvmtiThreadState::state_for_while_locked(tp);  // create the thread state if missing
       }
     }// release Threads_lock
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1872,6 +1872,9 @@
 {
   // register the stub with the current dynamic code event collector
   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
+  // state can only be NULL if the current thread is exiting which
+  // should not happen since we're trying to post an event
+  guarantee(state != NULL, "attempt to register stub via an exiting thread");
   JvmtiDynamicCodeEventCollector* collector = state->get_dynamic_code_event_collector();
   guarantee(collector != NULL, "attempt to register stub without event collector");
   collector->register_stub(name, code_begin, code_end);
@@ -2253,6 +2256,9 @@
 void JvmtiEventCollector::setup_jvmti_thread_state() {
   // set this event collector to be the current one.
   JvmtiThreadState* state = JvmtiThreadState::state_for(JavaThread::current());
+  // state can only be NULL if the current thread is exiting which
+  // should not happen since we're trying to configure for event collection
+  guarantee(state != NULL, "exiting thread called setup_jvmti_thread_state");
   if (is_vm_object_alloc_event()) {
     _prev = state->get_vm_object_alloc_event_collector();
     state->set_vm_object_alloc_event_collector((JvmtiVMObjectAllocEventCollector *)this);
--- a/hotspot/src/share/vm/prims/jvmtiImpl.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiImpl.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -238,6 +238,35 @@
 }
 
 
+bool
+JvmtiRawMonitor::is_valid() {
+  int value = 0;
+
+  // This object might not be a JvmtiRawMonitor so we can't assume
+  // the _magic field is properly aligned. Get the value in a safe
+  // way and then check against JVMTI_RM_MAGIC.
+
+  switch (sizeof(_magic)) {
+  case 2:
+    value = Bytes::get_native_u2((address)&_magic);
+    break;
+
+  case 4:
+    value = Bytes::get_native_u4((address)&_magic);
+    break;
+
+  case 8:
+    value = Bytes::get_native_u8((address)&_magic);
+    break;
+
+  default:
+    guarantee(false, "_magic field is an unexpected size");
+  }
+
+  return value == JVMTI_RM_MAGIC;
+}
+
+
 //
 // class JvmtiBreakpoint
 //
--- a/hotspot/src/share/vm/prims/jvmtiImpl.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiImpl.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -349,7 +349,7 @@
   ~JvmtiRawMonitor();
   int            magic()   { return _magic;  }
   const char *get_name()   { return _name; }
-  bool        is_valid()   { return _magic == JVMTI_RM_MAGIC;  }
+  bool        is_valid();
 };
 
 // Onload pending raw monitors
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -831,6 +831,9 @@
   ResourceMark rm(THREAD);
 
   JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
+  // state can only be NULL if the current thread is exiting which
+  // should not happen since we're trying to do a RedefineClasses
+  guarantee(state != NULL, "exiting thread calling load_new_class_versions");
   for (int i = 0; i < _class_count; i++) {
     oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
     // classes for primitives cannot be redefined
@@ -1349,39 +1352,39 @@
 
   // rewrite constant pool references in the methods:
   if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
   // rewrite constant pool references in the class_annotations:
   if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
   // rewrite constant pool references in the fields_annotations:
   if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
   // rewrite constant pool references in the methods_annotations:
   if (!rewrite_cp_refs_in_methods_annotations(scratch_class, THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
   // rewrite constant pool references in the methods_parameter_annotations:
   if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class,
          THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
   // rewrite constant pool references in the methods_default_annotations:
   if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class,
          THREAD)) {
-    // propogate failure back to caller
+    // propagate failure back to caller
     return false;
   }
 
@@ -1600,7 +1603,7 @@
            byte_i_ref, THREAD)) {
       RC_TRACE_WITH_THREAD(0x02000000, THREAD,
         ("bad annotation_struct at %d", calc_num_annotations));
-      // propogate failure back to caller
+      // propagate failure back to caller
       return false;
     }
   }
@@ -1666,7 +1669,7 @@
            byte_i_ref, THREAD)) {
       RC_TRACE_WITH_THREAD(0x02000000, THREAD,
         ("bad element_value at %d", calc_num_element_value_pairs));
-      // propogate failure back to caller
+      // propagate failure back to caller
       return false;
     }
   } // end for each component
@@ -1815,7 +1818,7 @@
       // field. This is a nested annotation.
       if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,
              byte_i_ref, THREAD)) {
-        // propogate failure back to caller
+        // propagate failure back to caller
         return false;
       }
       break;
@@ -1842,7 +1845,7 @@
                annotations_typeArray, byte_i_ref, THREAD)) {
           RC_TRACE_WITH_THREAD(0x02000000, THREAD,
             ("bad nested element_value at %d", calc_num_values));
-          // propogate failure back to caller
+          // propagate failure back to caller
           return false;
         }
       }
@@ -1886,7 +1889,7 @@
            THREAD)) {
       RC_TRACE_WITH_THREAD(0x02000000, THREAD,
         ("bad field_annotations at %d", i));
-      // propogate failure back to caller
+      // propagate failure back to caller
       return false;
     }
   }
@@ -1923,7 +1926,7 @@
            THREAD)) {
       RC_TRACE_WITH_THREAD(0x02000000, THREAD,
         ("bad method_annotations at %d", i));
-      // propogate failure back to caller
+      // propagate failure back to caller
       return false;
     }
   }
@@ -1991,7 +1994,7 @@
              method_parameter_annotations, byte_i, THREAD)) {
         RC_TRACE_WITH_THREAD(0x02000000, THREAD,
           ("bad method_parameter_annotations at %d", calc_num_parameters));
-        // propogate failure back to caller
+        // propagate failure back to caller
         return false;
       }
     }
@@ -2041,7 +2044,7 @@
            method_default_annotations, byte_i, THREAD)) {
       RC_TRACE_WITH_THREAD(0x02000000, THREAD,
         ("bad default element_value at %d", i));
-      // propogate failure back to caller
+      // propagate failure back to caller
       return false;
     }
   }
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -49,8 +49,8 @@
 //    0x00000400 |       1024 - previous class weak reference mgmt during
 //                              add previous ops (GC)
 //    0x00000800 |       2048 - previous class breakpoint mgmt
-//    0x00001000 |       4096 - unused
-//    0x00002000 |       8192 - unused
+//    0x00001000 |       4096 - detect calls to obsolete methods
+//    0x00002000 |       8192 - fail a guarantee() in addition to detection
 //    0x00004000 |      16384 - unused
 //    0x00008000 |      32768 - old/new method matching/add/delete
 //    0x00010000 |      65536 - impl details: CP size info
--- a/hotspot/src/share/vm/prims/jvmtiTagMap.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiTagMap.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/prims/jvmtiThreadState.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiThreadState.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -314,17 +314,24 @@
   void update_for_pop_top_frame();
 
   // already holding JvmtiThreadState_lock - retrieve or create JvmtiThreadState
+  // Can return NULL if JavaThread is exiting.
   inline static JvmtiThreadState *state_for_while_locked(JavaThread *thread) {
     assert(JvmtiThreadState_lock->is_locked(), "sanity check");
 
     JvmtiThreadState *state = thread->jvmti_thread_state();
     if (state == NULL) {
+      if (thread->is_exiting()) {
+        // don't add a JvmtiThreadState to a thread that is exiting
+        return NULL;
+      }
+
       state = new JvmtiThreadState(thread);
     }
     return state;
   }
 
   // retrieve or create JvmtiThreadState
+  // Can return NULL if JavaThread is exiting.
   inline static JvmtiThreadState *state_for(JavaThread *thread) {
     JvmtiThreadState *state = thread->jvmti_thread_state();
     if (state == NULL) {
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -852,16 +852,13 @@
       FreeHeap(value);
     }
     return true;
-  }
-  else if (strcmp(key, "sun.java.command") == 0) {
-
+  } else if (strcmp(key, "sun.java.command") == 0) {
     _java_command = value;
 
     // don't add this property to the properties exposed to the java application
     FreeHeap(key);
     return true;
-  }
-  else if (strcmp(key, "sun.java.launcher.pid") == 0) {
+  } else if (strcmp(key, "sun.java.launcher.pid") == 0) {
     // launcher.pid property is private and is processed
     // in process_sun_java_launcher_properties();
     // the sun.java.launcher property is passed on to the java application
@@ -870,13 +867,14 @@
       FreeHeap(value);
     }
     return true;
-  }
-  else if (strcmp(key, "java.vendor.url.bug") == 0) {
+  } else if (strcmp(key, "java.vendor.url.bug") == 0) {
     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
     // its value without going through the property list or making a Java call.
     _java_vendor_url_bug = value;
+  } else if (strcmp(key, "sun.boot.library.path") == 0) {
+    PropertyList_unique_add(&_system_properties, key, value, true);
+    return true;
   }
-
   // Create new property and add at the end of the list
   PropertyList_unique_add(&_system_properties, key, value);
   return true;
@@ -895,7 +893,7 @@
   // Ensure Agent_OnLoad has the correct initial values.
   // This may not be the final mode; mode may change later in onload phase.
   PropertyList_unique_add(&_system_properties, "java.vm.info",
-     (char*)Abstract_VM_Version::vm_info_string());
+                          (char*)Abstract_VM_Version::vm_info_string(), false);
 
   UseInterpreter             = true;
   UseCompiler                = true;
@@ -971,7 +969,7 @@
   } else {
     no_shared_spaces();
 
-    // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 correspondinly,
+    // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
     // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
     // we set them to 1024 and 1024.
     // See CR 6362902.
@@ -987,6 +985,16 @@
     if (AlwaysTenure) {
       FLAG_SET_CMDLINE(intx, MaxTenuringThreshold, 0);
     }
+    // When using compressed oops, we use local overflow stacks,
+    // rather than using a global overflow list chained through
+    // the klass word of the object's pre-image.
+    if (UseCompressedOops && !ParGCUseLocalOverflow) {
+      if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
+        warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
+      }
+      FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
+    }
+    assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
   }
 }
 
@@ -1211,7 +1219,9 @@
     if (UseLargePages && UseCompressedOops) {
       // Cannot allocate guard pages for implicit checks in indexed addressing
       // mode, when large pages are specified on windows.
-      FLAG_SET_DEFAULT(UseImplicitNullCheckForNarrowOop, false);
+      // This flag could be switched ON if narrow oop base address is set to 0,
+      // see code in Universe::initialize_heap().
+      Universe::set_narrow_oop_use_implicit_null_checks(false);
     }
 #endif //  _WIN64
   } else {
@@ -1364,9 +1374,6 @@
   if (AggressiveOpts && FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
     FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
   }
-  if (AggressiveOpts && FLAG_IS_DEFAULT(SpecialArraysEquals)) {
-    FLAG_SET_DEFAULT(SpecialArraysEquals, true);
-  }
   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
   }
@@ -2765,7 +2772,7 @@
 }
 
 // This add maintains unique property key in the list.
-void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v) {
+void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
   if (plist == NULL)
     return;
 
@@ -2773,7 +2780,11 @@
   SystemProperty* prop;
   for (prop = *plist; prop != NULL; prop = prop->next()) {
     if (strcmp(k, prop->key()) == 0) {
-      prop->set_value(v);
+      if (append) {
+        prop->append_value(v);
+      } else {
+        prop->set_value(v);
+      }
       return;
     }
   }
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -475,10 +475,13 @@
   // System properties
   static void init_system_properties();
 
-  // Proptery List manipulation
+  // Property List manipulation
   static void PropertyList_add(SystemProperty** plist, SystemProperty *element);
   static void PropertyList_add(SystemProperty** plist, const char* k, char* v);
-  static void PropertyList_unique_add(SystemProperty** plist, const char* k, char* v);
+  static void PropertyList_unique_add(SystemProperty** plist, const char* k, char* v) {
+    PropertyList_unique_add(plist, k, v, false);
+  }
+  static void PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append);
   static const char* PropertyList_get_value(SystemProperty* plist, const char* key);
   static int  PropertyList_count(SystemProperty* pl);
   static const char* PropertyList_get_key_at(SystemProperty* pl,int index);
--- a/hotspot/src/share/vm/runtime/extendedPC.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/extendedPC.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -23,7 +23,7 @@
  */
 
 // An ExtendedPC contains the _pc from a signal handler in a platform
-// independant way.
+// independent way.
 
 class ExtendedPC VALUE_OBJ_CLASS_SPEC {
  private:
--- a/hotspot/src/share/vm/runtime/fieldDescriptor.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/fieldDescriptor.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -107,13 +107,14 @@
 void fieldDescriptor::print_on_for(outputStream* st, oop obj) {
   print_on(st);
   BasicType ft = field_type();
-  jint as_int;
+  jint as_int = 0;
   switch (ft) {
     case T_BYTE:
       as_int = (jint)obj->byte_field(offset());
       st->print(" %d", obj->byte_field(offset()));
       break;
     case T_CHAR:
+      as_int = (jint)obj->char_field(offset());
       {
         jchar c = obj->char_field(offset());
         as_int = c;
@@ -128,6 +129,7 @@
       st->print(" %f", obj->float_field(offset()));
       break;
     case T_INT:
+      as_int = obj->int_field(offset());
       st->print(" %d", obj->int_field(offset()));
       break;
     case T_LONG:
@@ -144,12 +146,12 @@
       break;
     case T_ARRAY:
       st->print(" ");
-      as_int = obj->int_field(offset());
+      NOT_LP64(as_int = obj->int_field(offset()));
       obj->obj_field(offset())->print_value_on(st);
       break;
     case T_OBJECT:
       st->print(" ");
-      as_int = obj->int_field(offset());
+      NOT_LP64(as_int = obj->int_field(offset()));
       obj->obj_field(offset())->print_value_on(st);
       break;
     default:
@@ -158,9 +160,9 @@
   }
   // Print a hint as to the underlying integer representation. This can be wrong for
   // pointers on an LP64 machine
-  if (ft == T_LONG || ft == T_DOUBLE) {
+  if (ft == T_LONG || ft == T_DOUBLE LP64_ONLY(|| !is_java_primitive(ft)) ) {
     st->print(" (%x %x)", obj->int_field(offset()), obj->int_field(offset()+sizeof(jint)));
-  } else {
+  } else if (as_int < 0 || as_int > 9) {
     st->print(" (%x)", as_int);
   }
 }
--- a/hotspot/src/share/vm/runtime/fprofiler.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/fprofiler.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -988,7 +988,7 @@
 
 
 void ThreadProfiler::record_tick_for_running_frame(JavaThread* thread, frame fr) {
-  // The tick happend in real code -> non VM code
+  // The tick happened in real code -> non VM code
   if (fr.is_interpreted_frame()) {
     interval_data_ref()->inc_interpreted();
     record_interpreted_tick(thread, fr, tp_code, FlatProfiler::bytecode_ticks);
@@ -1019,7 +1019,7 @@
 }
 
 void ThreadProfiler::record_tick_for_calling_frame(JavaThread* thread, frame fr) {
-  // The tick happend in VM code
+  // The tick happened in VM code
   interval_data_ref()->inc_native();
   if (fr.is_interpreted_frame()) {
     record_interpreted_tick(thread, fr, tp_native, FlatProfiler::bytecode_ticks_stub);
--- a/hotspot/src/share/vm/runtime/frame.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/frame.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -930,7 +930,7 @@
         // => process callee's arguments
         //
         // Note: The expression stack can be empty if an exception
-        //       occured during method resolution/execution. In all
+        //       occurred during method resolution/execution. In all
         //       cases we empty the expression stack completely be-
         //       fore handling the exception (the exception handling
         //       code in the interpreter calls a blocking runtime
--- a/hotspot/src/share/vm/runtime/frame.inline.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/frame.inline.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -22,7 +22,7 @@
  *
  */
 
-// This file holds platform-independant bodies of inline functions for frames.
+// This file holds platform-independent bodies of inline functions for frames.
 
 // Note: The bcx usually contains the bcp; however during GC it contains the bci
 //       (changed by gc_prologue() and gc_epilogue()) to be methodOop position
--- a/hotspot/src/share/vm/runtime/globals.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,6 +47,7 @@
 define_pd_global(intx, OnStackReplacePercentage,     0);
 define_pd_global(bool, ResizeTLAB,                   false);
 define_pd_global(intx, FreqInlineSize,               0);
+define_pd_global(intx, InlineSmallCode,              0);
 define_pd_global(intx, NewSizeThreadIncrease,        4*K);
 define_pd_global(intx, NewRatio,                     4);
 define_pd_global(intx, InlineClassNatives,           true);
@@ -303,11 +304,14 @@
             "Use 32-bit object references in 64-bit VM. "                   \
             "lp64_product means flag is always constant in 32 bit VM")      \
                                                                             \
-  lp64_product(bool, CheckCompressedOops, trueInDebug,                      \
-            "generate checks in encoding/decoding code")                    \
-                                                                            \
-  product(bool, UseImplicitNullCheckForNarrowOop, true,                     \
-            "generate implicit null check in indexed addressing mode.")     \
+  notproduct(bool, CheckCompressedOops, true,                               \
+            "generate checks in encoding/decoding code in debug VM")        \
+                                                                            \
+  product_pd(uintx, HeapBaseMinAddress,                                     \
+            "OS specific low limit for heap base address")                  \
+                                                                            \
+  diagnostic(bool, PrintCompressedOopsMode, false,                          \
+            "Print compressed oops base address and encoding mode")         \
                                                                             \
   /* UseMembar is theoretically a temp flag used for memory barrier         \
    * removal testing.  It was supposed to be removed before FCS but has     \
@@ -487,9 +491,15 @@
   develop(bool, SpecialStringIndexOf, true,                                 \
           "special version of string indexOf")                              \
                                                                             \
-  product(bool, SpecialArraysEquals, false,                                 \
+  develop(bool, SpecialStringEquals, true,                                  \
+          "special version of string equals")                               \
+                                                                            \
+  develop(bool, SpecialArraysEquals, true,                                  \
           "special version of Arrays.equals(char[],char[])")                \
                                                                             \
+  product(bool, UseSSE42Intrinsics, false,                                  \
+          "SSE4.2 versions of intrinsics")                                  \
+                                                                            \
   develop(bool, TraceCallFixup, false,                                      \
           "traces all call fixups")                                         \
                                                                             \
@@ -662,6 +672,12 @@
   product(ccstrlist, OnOutOfMemoryError, "",                                \
           "Run user-defined commands on first java.lang.OutOfMemoryError")  \
                                                                             \
+  manageable(bool, HeapDumpBeforeFullGC, false,                             \
+          "Dump heap to file before any major stop-world GC")               \
+                                                                            \
+  manageable(bool, HeapDumpAfterFullGC, false,                              \
+          "Dump heap to file after any major stop-world GC")                \
+                                                                            \
   manageable(bool, HeapDumpOnOutOfMemoryError, false,                       \
           "Dump heap to file when java.lang.OutOfMemoryError is thrown")    \
                                                                             \
@@ -1307,6 +1323,12 @@
   product(intx, ParGCArrayScanChunk, 50,                                    \
           "Scan a subset and push remainder, if array is bigger than this") \
                                                                             \
+  product(bool, ParGCUseLocalOverflow, false,                               \
+          "Instead of a global overflow list, use local overflow stacks")   \
+                                                                            \
+  product(bool, ParGCTrimOverflow, true,                                    \
+          "Eagerly trim the local overflow lists (when ParGCUseLocalOverflow") \
+                                                                            \
   notproduct(bool, ParGCWorkQueueOverflowALot, false,                       \
           "Whether we should simulate work queue overflow in ParNew")       \
                                                                             \
@@ -1971,6 +1993,12 @@
   product(bool, PrintHeapAtSIGBREAK, true,                                  \
           "Print heap layout in response to SIGBREAK")                      \
                                                                             \
+  manageable(bool, PrintClassHistogramBeforeFullGC, false,                  \
+          "Print a class histogram before any major stop-world GC")         \
+                                                                            \
+  manageable(bool, PrintClassHistogramAfterFullGC, false,                   \
+          "Print a class histogram after any major stop-world GC")          \
+                                                                            \
   manageable(bool, PrintClassHistogram, false,                              \
           "Print a histogram of class instances")                           \
                                                                             \
@@ -2157,6 +2185,9 @@
   diagnostic(bool, PrintIntrinsics, false,                                  \
           "prints attempted and successful inlining of intrinsics")         \
                                                                             \
+  product(bool, UsePopCountInstruction, false,                              \
+          "Use population count instruction")                               \
+                                                                            \
   diagnostic(ccstrlist, DisableIntrinsic, "",                               \
           "do not expand intrinsics whose (internal) names appear here")    \
                                                                             \
@@ -2598,7 +2629,7 @@
   develop(intx, MaxRecursiveInlineLevel, 1,                                 \
           "maximum number of nested recursive calls that are inlined")      \
                                                                             \
-  product(intx, InlineSmallCode, 1000,                                      \
+  product_pd(intx, InlineSmallCode,                                         \
           "Only inline already compiled methods if their code size is "     \
           "less than this")                                                 \
                                                                             \
--- a/hotspot/src/share/vm/runtime/handles.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/handles.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -137,6 +137,14 @@
     assert(is_null() || obj()->is_klass(), "not a klassOop");
   }
 
+  // Direct interface, use very sparingly.
+  // Used by SystemDictionaryHandles to create handles on existing WKKs.
+  // The obj of such a klass handle may be null, because the handle is formed
+  // during system bootstrapping.
+  KlassHandle(klassOop *handle, bool dummy) : Handle((oop*)handle, dummy) {
+    assert(SharedSkipVerify || is_null() || obj() == NULL || obj()->is_klass(), "not a klassOop");
+  }
+
   // General access
   klassOop    operator () () const               { return obj(); }
   Klass*      operator -> () const               { return as_klass(); }
--- a/hotspot/src/share/vm/runtime/hpi.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/hpi.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -90,7 +90,7 @@
   static inline struct protoent* get_proto_by_name(char* name);
 
   // HPI_LibraryInterface
-  static inline void   dll_build_name(char *buf, int buf_len, char* path,
+  static inline void   dll_build_name(char *buf, int buf_len, const char* path,
                                       const char *name);
   static inline void*  dll_load(const char *name, char *ebuf, int ebuflen);
   static inline void   dll_unload(void *lib);
@@ -137,7 +137,15 @@
     return result;                            \
   }
 
-
+#define VM_HPIDECL_VOID(name, names, func, arg_type, arg_print, arg)   \
+  inline void  hpi::name arg_type {           \
+    if (TraceHPI) {                           \
+      tty->print("hpi::" names "(");          \
+      tty->print arg_print;                   \
+      tty->print(") = ");                     \
+    }                                         \
+    func arg;                                 \
+  }
 
 #define HPIDECL_VOID(name, names, intf, func, arg_type, arg_print, arg) \
   inline void hpi::name arg_type {            \
@@ -197,11 +205,11 @@
         (fd, size));
 
 // HPI_LibraryInterface
-HPIDECL_VOID(dll_build_name, "dll_build_name", _library, BuildLibName,
-             (char *buf, int buf_len, char *path, const char *name),
-             ("buf = %p, buflen = %d, path = %s, name = %s",
-              buf, buf_len, path, name),
-             (buf, buf_len, path, name));
+VM_HPIDECL_VOID(dll_build_name, "dll_build_name", os::dll_build_name,
+               (char *buf, int buf_len, const char *path, const char *name),
+               ("buf = %p, buflen = %d, path = %s, name = %s",
+                buf, buf_len, path, name),
+               (buf, buf_len, path, name));
 
 VM_HPIDECL(dll_load, "dll_load", os::dll_load,
         void *, "(void *)%p",
--- a/hotspot/src/share/vm/runtime/javaCalls.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/javaCalls.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/runtime/memprofiler.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/memprofiler.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/runtime/mutex.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/mutex.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -82,7 +82,7 @@
 // *in that order*.  If their implementations change such that these
 // assumptions are violated, a whole lot of code will break.
 
-// The default length of monitor name is choosen to be 64 to avoid false sharing.
+// The default length of monitor name is chosen to be 64 to avoid false sharing.
 static const int MONITOR_NAME_LEN = 64;
 
 class Monitor : public CHeapObj {
--- a/hotspot/src/share/vm/runtime/orderAccess.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/orderAccess.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -26,3 +26,15 @@
 # include "incls/_orderAccess.cpp.incl"
 
 volatile intptr_t OrderAccess::dummy = 0;
+
+void OrderAccess::StubRoutines_fence() {
+  // Use a stub if it exists.  It may not exist during bootstrap so do
+  // nothing in that case but assert if no fence code exists after threads have been created
+  void (*func)() = CAST_TO_FN_PTR(void (*)(), StubRoutines::fence_entry());
+
+  if (func != NULL) {
+    (*func)();
+    return;
+  }
+  assert(Threads::number_of_threads() == 0, "for bootstrap only");
+}
--- a/hotspot/src/share/vm/runtime/orderAccess.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/orderAccess.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -31,7 +31,7 @@
 // at runtime.
 //
 // In the following, the terms 'previous', 'subsequent', 'before',
-// 'after', 'preceeding' and 'succeeding' refer to program order.  The
+// 'after', 'preceding' and 'succeeding' refer to program order.  The
 // terms 'down' and 'below' refer to forward load or store motion
 // relative to program order, while 'up' and 'above' refer to backward
 // motion.
@@ -300,4 +300,10 @@
   // In order to force a memory access, implementations may
   // need a volatile externally visible dummy variable.
   static volatile intptr_t dummy;
+
+ private:
+  // This is a helper that invokes the StubRoutines::fence_entry()
+  // routine if it exists, It should only be used by platforms that
+  // don't another way to do the inline eassembly.
+  static void StubRoutines_fence();
 };
--- a/hotspot/src/share/vm/runtime/os.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/os.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -207,7 +207,8 @@
         VMThread::execute(&op1);
         Universe::print_heap_at_SIGBREAK();
         if (PrintClassHistogram) {
-          VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
+          VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,
+                                   true /* need_prologue */);
           VMThread::execute(&op1);
         }
         if (JvmtiExport::should_post_data_dump()) {
@@ -862,7 +863,6 @@
 
 
 bool os::set_boot_path(char fileSep, char pathSep) {
-
     const char* home = Arguments::get_java_home();
     int home_len = (int)strlen(home);
 
@@ -892,6 +892,60 @@
     return true;
 }
 
+/*
+ * Splits a path, based on its separator, the number of
+ * elements is returned back in n.
+ * It is the callers responsibility to:
+ *   a> check the value of n, and n may be 0.
+ *   b> ignore any empty path elements
+ *   c> free up the data.
+ */
+char** os::split_path(const char* path, int* n) {
+  *n = 0;
+  if (path == NULL || strlen(path) == 0) {
+    return NULL;
+  }
+  const char psepchar = *os::path_separator();
+  char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1);
+  if (inpath == NULL) {
+    return NULL;
+  }
+  strncpy(inpath, path, strlen(path));
+  int count = 1;
+  char* p = strchr(inpath, psepchar);
+  // Get a count of elements to allocate memory
+  while (p != NULL) {
+    count++;
+    p++;
+    p = strchr(p, psepchar);
+  }
+  char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count);
+  if (opath == NULL) {
+    return NULL;
+  }
+
+  // do the actual splitting
+  p = inpath;
+  for (int i = 0 ; i < count ; i++) {
+    size_t len = strcspn(p, os::path_separator());
+    if (len > JVM_MAXPATHLEN) {
+      return NULL;
+    }
+    // allocate the string and add terminator storage
+    char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1);
+    if (s == NULL) {
+      return NULL;
+    }
+    strncpy(s, p, len);
+    s[len] = '\0';
+    opath[i] = s;
+    p += len + 1;
+  }
+  FREE_C_HEAP_ARRAY(char, inpath);
+  *n = count;
+  return opath;
+}
+
 void os::set_memory_serialize_page(address page) {
   int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
   _mem_serialize_page = (volatile int32_t *)page;
@@ -943,7 +997,7 @@
   assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
   address sp = current_stack_pointer();
   // Check if we have StackShadowPages above the yellow zone.  This parameter
-  // is dependant on the depth of the maximum VM call stack possible from
+  // is dependent on the depth of the maximum VM call stack possible from
   // the handler for stack overflow.  'instanceof' in the stack overflow
   // handler or a println uses at least 8k stack of VM and native code
   // respectively.
--- a/hotspot/src/share/vm/runtime/os.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -202,8 +202,10 @@
   static char*  attempt_reserve_memory_at(size_t bytes, char* addr);
   static void   split_reserved_memory(char *base, size_t size,
                                       size_t split, bool realloc);
-  static bool   commit_memory(char* addr, size_t bytes);
-  static bool   commit_memory(char* addr, size_t size, size_t alignment_hint);
+  static bool   commit_memory(char* addr, size_t bytes,
+                              bool executable = false);
+  static bool   commit_memory(char* addr, size_t size, size_t alignment_hint,
+                              bool executable = false);
   static bool   uncommit_memory(char* addr, size_t bytes);
   static bool   release_memory(char* addr, size_t bytes);
 
@@ -243,7 +245,8 @@
 
   static char*  non_memory_address_word();
   // reserve, commit and pin the entire memory region
-  static char*  reserve_memory_special(size_t size);
+  static char*  reserve_memory_special(size_t size, char* addr = NULL,
+                bool executable = false);
   static bool   release_memory_special(char* addr, size_t bytes);
   static bool   large_page_init();
   static size_t large_page_size();
@@ -604,6 +607,7 @@
                                 char fileSep,
                                 char pathSep);
   static bool set_boot_path(char fileSep, char pathSep);
+  static char** split_path(const char* path, int* n);
 };
 
 // Note that "PAUSE" is almost always used with synchronization
--- a/hotspot/src/share/vm/runtime/reflection.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/reflection.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -554,10 +554,18 @@
   return instanceKlass::cast(class1)->is_same_class_package(class2);
 }
 
+bool Reflection::is_same_package_member(klassOop class1, klassOop class2, TRAPS) {
+  return instanceKlass::cast(class1)->is_same_package_member(class2, THREAD);
+}
+
 
 // Checks that the 'outer' klass has declared 'inner' as being an inner klass. If not,
 // throw an incompatible class change exception
-void Reflection::check_for_inner_class(instanceKlassHandle outer, instanceKlassHandle inner, TRAPS) {
+// If inner_is_member, require the inner to be a member of the outer.
+// If !inner_is_member, require the inner to be anonymous (a non-member).
+// Caller is responsible for figuring out in advance which case must be true.
+void Reflection::check_for_inner_class(instanceKlassHandle outer, instanceKlassHandle inner,
+                                       bool inner_is_member, TRAPS) {
   const int inner_class_info_index = 0;
   const int outer_class_info_index = 1;
 
@@ -567,7 +575,7 @@
      int ioff = icls->ushort_at(i + inner_class_info_index);
      int ooff = icls->ushort_at(i + outer_class_info_index);
 
-     if (ioff != 0 && ooff != 0) {
+     if (inner_is_member && ioff != 0 && ooff != 0) {
         klassOop o = cp->klass_at(ooff, CHECK);
         if (o == outer()) {
           klassOop i = cp->klass_at(ioff, CHECK);
@@ -576,6 +584,13 @@
           }
         }
      }
+     if (!inner_is_member && ioff != 0 && ooff == 0 &&
+         cp->klass_name_at_matches(inner, ioff)) {
+        klassOop i = cp->klass_at(ioff, CHECK);
+        if (i == inner()) {
+          return;
+        }
+     }
   }
 
   // 'inner' not declared as an inner klass in outer
--- a/hotspot/src/share/vm/runtime/reflection.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/reflection.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -87,12 +87,18 @@
                                       bool classloader_only,
                                       bool protected_restriction = false);
   static bool     is_same_class_package(klassOop class1, klassOop class2);
+  static bool     is_same_package_member(klassOop class1, klassOop class2, TRAPS);
 
   static bool can_relax_access_check_for(
     klassOop accessor, klassOop accesee, bool classloader_only);
 
   // inner class reflection
-  static void check_for_inner_class(instanceKlassHandle outer, instanceKlassHandle inner, TRAPS);
+  // raise an ICCE unless the required relationship can be proven to hold
+  // If inner_is_member, require the inner to be a member of the outer.
+  // If !inner_is_member, require the inner to be anonymous (a non-member).
+  // Caller is responsible for figuring out in advance which case must be true.
+  static void check_for_inner_class(instanceKlassHandle outer, instanceKlassHandle inner,
+                                    bool inner_is_member, TRAPS);
 
   //
   // Support for reflection based on dynamic bytecode generation (JDK 1.4)
--- a/hotspot/src/share/vm/runtime/safepoint.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/safepoint.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -369,7 +369,7 @@
 
     // Start suspended threads
     for(JavaThread *current = Threads::first(); current; current = current->next()) {
-      // A problem occuring on Solaris is when attempting to restart threads
+      // A problem occurring on Solaris is when attempting to restart threads
       // the first #cpus - 1 go well, but then the VMThread is preempted when we get
       // to the next one (since it has been running the longest).  We then have
       // to wait for a cpu to become available before we can continue restarting
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -377,6 +377,32 @@
   throw_and_post_jvmti_exception(thread, h_exception);
 }
 
+// The interpreter code to call this tracing function is only
+// called/generated when TraceRedefineClasses has the right bits
+// set. Since obsolete methods are never compiled, we don't have
+// to modify the compilers to generate calls to this function.
+//
+JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
+    JavaThread* thread, methodOopDesc* method))
+  assert(RC_TRACE_IN_RANGE(0x00001000, 0x00002000), "wrong call");
+
+  if (method->is_obsolete()) {
+    // We are calling an obsolete method, but this is not necessarily
+    // an error. Our method could have been redefined just after we
+    // fetched the methodOop from the constant pool.
+
+    // RC_TRACE macro has an embedded ResourceMark
+    RC_TRACE_WITH_THREAD(0x00001000, thread,
+                         ("calling obsolete method '%s'",
+                          method->name_and_sig_as_C_string()));
+    if (RC_TRACE_ENABLED(0x00002000)) {
+      // this option is provided to debug calls to obsolete methods
+      guarantee(false, "faulting at call to an obsolete method.");
+    }
+  }
+  return 0;
+JRT_END
+
 // ret_pc points into caller; we are returning caller's exception handler
 // for given exception
 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
@@ -649,48 +675,6 @@
 JRT_END
 
 
-// ---------------------------------------------------------------------------------------------------------
-// Non-product code
-#ifndef PRODUCT
-
-void SharedRuntime::verify_caller_frame(frame caller_frame, methodHandle callee_method) {
-  ResourceMark rm;
-  assert (caller_frame.is_interpreted_frame(), "sanity check");
-  assert (callee_method->has_compiled_code(), "callee must be compiled");
-  methodHandle caller_method (Thread::current(), caller_frame.interpreter_frame_method());
-  jint bci = caller_frame.interpreter_frame_bci();
-  methodHandle method = find_callee_method_inside_interpreter(caller_frame, caller_method, bci);
-  assert (callee_method == method, "incorrect method");
-}
-
-methodHandle SharedRuntime::find_callee_method_inside_interpreter(frame caller_frame, methodHandle caller_method, int bci) {
-  EXCEPTION_MARK;
-  Bytecode_invoke* bytecode = Bytecode_invoke_at(caller_method, bci);
-  methodHandle staticCallee = bytecode->static_target(CATCH); // Non-product code
-
-  bytecode = Bytecode_invoke_at(caller_method, bci);
-  int bytecode_index = bytecode->index();
-  Bytecodes::Code bc = bytecode->adjusted_invoke_code();
-
-  Handle receiver;
-  if (bc == Bytecodes::_invokeinterface ||
-      bc == Bytecodes::_invokevirtual ||
-      bc == Bytecodes::_invokespecial) {
-    symbolHandle signature (THREAD, staticCallee->signature());
-    receiver = Handle(THREAD, retrieve_receiver(signature, caller_frame));
-  } else {
-    receiver = Handle();
-  }
-  CallInfo result;
-  constantPoolHandle constants (THREAD, caller_method->constants());
-  LinkResolver::resolve_invoke(result, receiver, constants, bytecode_index, bc, CATCH); // Non-product code
-  methodHandle calleeMethod = result.selected_method();
-  return calleeMethod;
-}
-
-#endif  // PRODUCT
-
-
 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
   assert(obj->is_oop(), "must be a valid oop");
   assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise");
--- a/hotspot/src/share/vm/runtime/sharedRuntime.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -166,6 +166,9 @@
   static void throw_and_post_jvmti_exception(JavaThread *thread, Handle h_exception);
   static void throw_and_post_jvmti_exception(JavaThread *thread, symbolOop name, const char *message = NULL);
 
+  // RedefineClasses() tracing support for obsolete method entry
+  static int rc_trace_method_entry(JavaThread* thread, methodOopDesc* m);
+
   // To be used as the entry point for unresolved native methods.
   static address native_method_throw_unsatisfied_link_error_entry();
 
@@ -177,9 +180,6 @@
 
   static oop retrieve_receiver( symbolHandle sig, frame caller );
 
-  static void verify_caller_frame(frame caller_frame, methodHandle callee_method) PRODUCT_RETURN;
-  static methodHandle find_callee_method_inside_interpreter(frame caller_frame, methodHandle caller_method, int bci) PRODUCT_RETURN_(return methodHandle(););
-
   static void register_finalizer(JavaThread* thread, oopDesc* obj);
 
   // dtrace notifications
--- a/hotspot/src/share/vm/runtime/signature.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/signature.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -266,7 +266,7 @@
 class NativeSignatureIterator: public SignatureIterator {
  private:
   methodHandle _method;
-// We need seperate JNI and Java offset values because in 64 bit mode,
+// We need separate JNI and Java offset values because in 64 bit mode,
 // the argument offsets are not in sync with the Java stack.
 // For example a long takes up 1 "C" stack entry but 2 Java stack entries.
   int          _offset;                // The java stack offset
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/runtime/thread.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -3007,17 +3007,19 @@
       }
 
       if (UseStringCache) {
-        // Forcibly initialize java/lang/String and mutate the private
+        // Forcibly initialize java/lang/StringValue and mutate the private
         // static final "stringCacheEnabled" field before we start creating instances
-        klassOop k_o = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_String(), Handle(), Handle(), CHECK_0);
-        KlassHandle k = KlassHandle(THREAD, k_o);
-        guarantee(k.not_null(), "Must find java/lang/String");
-        instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
-        ik->initialize(CHECK_0);
-        fieldDescriptor fd;
-        // Possible we might not find this field; if so, don't break
-        if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
-          k()->bool_field_put(fd.offset(), true);
+        klassOop k_o = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
+        // Possible that StringValue isn't present: if so, silently don't break
+        if (k_o != NULL) {
+          KlassHandle k = KlassHandle(THREAD, k_o);
+          instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
+          ik->initialize(CHECK_0);
+          fieldDescriptor fd;
+          // Possible we might not find this field: if so, silently don't break
+          if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
+            k()->bool_field_put(fd.offset(), true);
+          }
         }
       }
     }
--- a/hotspot/src/share/vm/runtime/thread.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/thread.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1345,6 +1345,13 @@
  public:
   // Thread local information maintained by JVMTI.
   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
+  // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
+  // getter is used to get this JavaThread's JvmtiThreadState if it has
+  // one which means NULL can be returned. JvmtiThreadState::state_for()
+  // is used to get the specified JavaThread's JvmtiThreadState if it has
+  // one or it allocates a new JvmtiThreadState for the JavaThread and
+  // returns it. JvmtiThreadState::state_for() will return NULL only if
+  // the specified JavaThread is exiting.
   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
   void set_jvmti_get_loaded_classes_closure(JvmtiGetLoadedClassesClosure* value) { _jvmti_get_loaded_classes_closure = value; }
--- a/hotspot/src/share/vm/runtime/threadCritical.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/threadCritical.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 // Due to race conditions during vm exit, some of the os level
 // synchronization primitives may not be deallocated at exit. It
-// is a good plan to implement the platform dependant sections of
+// is a good plan to implement the platform dependent sections of
 // code with resources that are recoverable during process
 // cleanup by the os. Calling the initialize method before use
 // is also problematic, it is best to use preinitialized primitives
--- a/hotspot/src/share/vm/runtime/virtualspace.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/virtualspace.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -28,7 +28,7 @@
 
 // ReservedSpace
 ReservedSpace::ReservedSpace(size_t size) {
-  initialize(size, 0, false, NULL, 0);
+  initialize(size, 0, false, NULL, 0, false);
 }
 
 ReservedSpace::ReservedSpace(size_t size, size_t alignment,
@@ -36,7 +36,13 @@
                              char* requested_address,
                              const size_t noaccess_prefix) {
   initialize(size+noaccess_prefix, alignment, large, requested_address,
-             noaccess_prefix);
+             noaccess_prefix, false);
+}
+
+ReservedSpace::ReservedSpace(size_t size, size_t alignment,
+                             bool large,
+                             bool executable) {
+  initialize(size, alignment, large, NULL, 0, executable);
 }
 
 char *
@@ -109,6 +115,7 @@
                              const size_t prefix_align,
                              const size_t suffix_size,
                              const size_t suffix_align,
+                             char* requested_address,
                              const size_t noaccess_prefix)
 {
   assert(prefix_size != 0, "sanity");
@@ -131,7 +138,8 @@
   const bool try_reserve_special = UseLargePages &&
     prefix_align == os::large_page_size();
   if (!os::can_commit_large_page_memory() && try_reserve_special) {
-    initialize(size, prefix_align, true, NULL, noaccess_prefix);
+    initialize(size, prefix_align, true, requested_address, noaccess_prefix,
+               false);
     return;
   }
 
@@ -140,13 +148,20 @@
   _alignment = 0;
   _special = false;
   _noaccess_prefix = 0;
+  _executable = false;
 
   // Assert that if noaccess_prefix is used, it is the same as prefix_align.
   assert(noaccess_prefix == 0 ||
          noaccess_prefix == prefix_align, "noaccess prefix wrong");
 
   // Optimistically try to reserve the exact size needed.
-  char* addr = os::reserve_memory(size, NULL, prefix_align);
+  char* addr;
+  if (requested_address != 0) {
+    addr = os::attempt_reserve_memory_at(size,
+                                         requested_address-noaccess_prefix);
+  } else {
+    addr = os::reserve_memory(size, NULL, prefix_align);
+  }
   if (addr == NULL) return;
 
   // Check whether the result has the needed alignment (unlikely unless
@@ -182,7 +197,8 @@
 
 void ReservedSpace::initialize(size_t size, size_t alignment, bool large,
                                char* requested_address,
-                               const size_t noaccess_prefix) {
+                               const size_t noaccess_prefix,
+                               bool executable) {
   const size_t granularity = os::vm_allocation_granularity();
   assert((size & granularity - 1) == 0,
          "size not aligned to os::vm_allocation_granularity()");
@@ -194,6 +210,7 @@
   _base = NULL;
   _size = 0;
   _special = false;
+  _executable = executable;
   _alignment = 0;
   _noaccess_prefix = 0;
   if (size == 0) {
@@ -206,12 +223,8 @@
   char* base = NULL;
 
   if (special) {
-    // It's not hard to implement reserve_memory_special() such that it can
-    // allocate at fixed address, but there seems no use of this feature
-    // for now, so it's not implemented.
-    assert(requested_address == NULL, "not implemented");
 
-    base = os::reserve_memory_special(size);
+    base = os::reserve_memory_special(size, requested_address, executable);
 
     if (base != NULL) {
       // Check alignment constraints
@@ -281,7 +294,7 @@
 
 
 ReservedSpace::ReservedSpace(char* base, size_t size, size_t alignment,
-                             bool special) {
+                             bool special, bool executable) {
   assert((size % os::vm_allocation_granularity()) == 0,
          "size not allocation aligned");
   _base = base;
@@ -289,6 +302,7 @@
   _alignment = alignment;
   _noaccess_prefix = 0;
   _special = special;
+  _executable = executable;
 }
 
 
@@ -296,9 +310,10 @@
                                         bool split, bool realloc) {
   assert(partition_size <= size(), "partition failed");
   if (split) {
-    os::split_reserved_memory(_base, _size, partition_size, realloc);
+    os::split_reserved_memory(base(), size(), partition_size, realloc);
   }
-  ReservedSpace result(base(), partition_size, alignment, special());
+  ReservedSpace result(base(), partition_size, alignment, special(),
+                       executable());
   return result;
 }
 
@@ -307,7 +322,7 @@
 ReservedSpace::last_part(size_t partition_size, size_t alignment) {
   assert(partition_size <= size(), "partition failed");
   ReservedSpace result(base() + partition_size, size() - partition_size,
-                       alignment, special());
+                       alignment, special(), executable());
   return result;
 }
 
@@ -345,6 +360,7 @@
     _size = 0;
     _noaccess_prefix = 0;
     _special = false;
+    _executable = false;
   }
 }
 
@@ -372,7 +388,8 @@
                                      bool large, char* requested_address) :
   ReservedSpace(size, alignment, large,
                 requested_address,
-                UseCompressedOops && UseImplicitNullCheckForNarrowOop ?
+                (UseCompressedOops && (Universe::narrow_oop_base() != NULL) &&
+                 Universe::narrow_oop_use_implicit_null_checks()) ?
                   lcm(os::vm_page_size(), alignment) : 0) {
   // Only reserved space for the java heap should have a noaccess_prefix
   // if using compressed oops.
@@ -382,13 +399,24 @@
 ReservedHeapSpace::ReservedHeapSpace(const size_t prefix_size,
                                      const size_t prefix_align,
                                      const size_t suffix_size,
-                                     const size_t suffix_align) :
+                                     const size_t suffix_align,
+                                     char* requested_address) :
   ReservedSpace(prefix_size, prefix_align, suffix_size, suffix_align,
-                UseCompressedOops && UseImplicitNullCheckForNarrowOop ?
+                requested_address,
+                (UseCompressedOops && (Universe::narrow_oop_base() != NULL) &&
+                 Universe::narrow_oop_use_implicit_null_checks()) ?
                   lcm(os::vm_page_size(), prefix_align) : 0) {
   protect_noaccess_prefix(prefix_size+suffix_size);
 }
 
+// Reserve space for code segment.  Same as Java heap only we mark this as
+// executable.
+ReservedCodeSpace::ReservedCodeSpace(size_t r_size,
+                                     size_t rs_align,
+                                     bool large) :
+  ReservedSpace(r_size, rs_align, large, /*executable*/ true) {
+}
+
 // VirtualSpace
 
 VirtualSpace::VirtualSpace() {
@@ -406,6 +434,7 @@
   _middle_alignment       = 0;
   _upper_alignment        = 0;
   _special                = false;
+  _executable             = false;
 }
 
 
@@ -419,6 +448,7 @@
   _high = low();
 
   _special = rs.special();
+  _executable = rs.executable();
 
   // When a VirtualSpace begins life at a large size, make all future expansion
   // and shrinking occur aligned to a granularity of large pages.  This avoids
@@ -476,6 +506,7 @@
   _middle_alignment       = 0;
   _upper_alignment        = 0;
   _special                = false;
+  _executable             = false;
 }
 
 
@@ -585,7 +616,7 @@
     assert(low_boundary() <= lower_high() &&
            lower_high() + lower_needs <= lower_high_boundary(),
            "must not expand beyond region");
-    if (!os::commit_memory(lower_high(), lower_needs)) {
+    if (!os::commit_memory(lower_high(), lower_needs, _executable)) {
       debug_only(warning("os::commit_memory failed"));
       return false;
     } else {
@@ -596,7 +627,8 @@
     assert(lower_high_boundary() <= middle_high() &&
            middle_high() + middle_needs <= middle_high_boundary(),
            "must not expand beyond region");
-    if (!os::commit_memory(middle_high(), middle_needs, middle_alignment())) {
+    if (!os::commit_memory(middle_high(), middle_needs, middle_alignment(),
+                           _executable)) {
       debug_only(warning("os::commit_memory failed"));
       return false;
     }
@@ -606,7 +638,7 @@
     assert(middle_high_boundary() <= upper_high() &&
            upper_high() + upper_needs <= upper_high_boundary(),
            "must not expand beyond region");
-    if (!os::commit_memory(upper_high(), upper_needs)) {
+    if (!os::commit_memory(upper_high(), upper_needs, _executable)) {
       debug_only(warning("os::commit_memory failed"));
       return false;
     } else {
--- a/hotspot/src/share/vm/runtime/virtualspace.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/virtualspace.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -32,12 +32,15 @@
   size_t _noaccess_prefix;
   size_t _alignment;
   bool   _special;
+  bool   _executable;
 
   // ReservedSpace
-  ReservedSpace(char* base, size_t size, size_t alignment, bool special);
+  ReservedSpace(char* base, size_t size, size_t alignment, bool special,
+                bool executable);
   void initialize(size_t size, size_t alignment, bool large,
                   char* requested_address,
-                  const size_t noaccess_prefix);
+                  const size_t noaccess_prefix,
+                  bool executable);
 
   // Release parts of an already-reserved memory region [addr, addr + len) to
   // get a new region that has "compound alignment."  Return the start of the
@@ -73,17 +76,18 @@
                 const size_t noaccess_prefix = 0);
   ReservedSpace(const size_t prefix_size, const size_t prefix_align,
                 const size_t suffix_size, const size_t suffix_align,
-                const size_t noaccess_prefix);
+                char* requested_address,
+                const size_t noaccess_prefix = 0);
+  ReservedSpace(size_t size, size_t alignment, bool large, bool executable);
 
   // Accessors
-  char*  base()      const { return _base;      }
-  size_t size()      const { return _size;      }
-  size_t alignment() const { return _alignment; }
-  bool   special()   const { return _special;   }
-
-  size_t noaccess_prefix()   const { return _noaccess_prefix;   }
-
-  bool is_reserved() const { return _base != NULL; }
+  char*  base()            const { return _base;      }
+  size_t size()            const { return _size;      }
+  size_t alignment()       const { return _alignment; }
+  bool   special()         const { return _special;   }
+  bool   executable()      const { return _executable;   }
+  size_t noaccess_prefix() const { return _noaccess_prefix;   }
+  bool is_reserved()       const { return _base != NULL; }
   void release();
 
   // Splitting
@@ -121,7 +125,15 @@
   ReservedHeapSpace(size_t size, size_t forced_base_alignment,
                     bool large, char* requested_address);
   ReservedHeapSpace(const size_t prefix_size, const size_t prefix_align,
-                    const size_t suffix_size, const size_t suffix_align);
+                    const size_t suffix_size, const size_t suffix_align,
+                    char* requested_address);
+};
+
+// Class encapsulating behavior specific memory space for Code
+class ReservedCodeSpace : public ReservedSpace {
+ public:
+  // Constructor
+  ReservedCodeSpace(size_t r_size, size_t rs_align, bool large);
 };
 
 // VirtualSpace is data structure for committing a previously reserved address range in smaller chunks.
@@ -141,6 +153,9 @@
   // os::commit_memory() or os::uncommit_memory().
   bool _special;
 
+  // Need to know if commit should be executable.
+  bool   _executable;
+
   // MPSS Support
   // Each virtualspace region has a lower, middle, and upper region.
   // Each region has an end boundary and a high pointer which is the
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -263,7 +263,9 @@
      static_field(Universe,                    _bootstrapping,                                bool)                                  \
      static_field(Universe,                    _fully_initialized,                            bool)                                  \
      static_field(Universe,                    _verify_count,                                 int)                                   \
-     static_field(Universe,                    _heap_base,                                    address)                                   \
+     static_field(Universe,                    _narrow_oop._base,                             address)                               \
+     static_field(Universe,                    _narrow_oop._shift,                            int)                                   \
+     static_field(Universe,                    _narrow_oop._use_implicit_null_checks,         bool)                                  \
                                                                                                                                      \
   /**********************************************************************************/                                               \
   /* Generation and Space hierarchies                                               */                                               \
--- a/hotspot/src/share/vm/runtime/vm_operations.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/vm_operations.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -59,7 +59,6 @@
   template(G1CollectFull)                         \
   template(G1CollectForAllocation)                \
   template(G1IncCollectionPause)                  \
-  template(G1PopRegionCollectionPause)            \
   template(EnableBiasedLocking)                   \
   template(RevokeBias)                            \
   template(BulkRevokeBias)                        \
--- a/hotspot/src/share/vm/runtime/vm_version.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/runtime/vm_version.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -163,9 +163,11 @@
       #elif _MSC_VER == 1200
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 6.0"
       #elif _MSC_VER == 1310
-        #define HOTSPOT_BUILD_COMPILER "MS VC++ 7.1"
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 7.1 (VS2003)"
       #elif _MSC_VER == 1400
-        #define HOTSPOT_BUILD_COMPILER "MS VC++ 8.0"
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 8.0 (VS2005)"
+      #elif _MSC_VER == 1500
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 9.0 (VS2008)"
       #else
         #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER)
       #endif
--- a/hotspot/src/share/vm/services/attachListener.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/services/attachListener.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -194,7 +194,7 @@
     }
     live_objects_only = strcmp(arg0, "-live") == 0;
   }
-  VM_GC_HeapInspection heapop(out, live_objects_only /* request gc */);
+  VM_GC_HeapInspection heapop(out, live_objects_only /* request full gc */, true /* need_prologue */);
   VMThread::execute(&heapop);
   return JNI_OK;
 }
--- a/hotspot/src/share/vm/services/heapDumper.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/services/heapDumper.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -347,7 +347,6 @@
   INITIAL_CLASS_COUNT = 200
 };
 
-
 // Supports I/O operations on a dump file
 
 class DumpWriter : public StackObj {
@@ -1303,7 +1302,9 @@
 // The VM operation that performs the heap dump
 class VM_HeapDumper : public VM_GC_Operation {
  private:
-  DumpWriter* _writer;
+  static VM_HeapDumper* _global_dumper;
+  static DumpWriter*    _global_writer;
+  DumpWriter*           _local_writer;
   bool _gc_before_heap_dump;
   bool _is_segmented_dump;
   jlong _dump_start;
@@ -1311,8 +1312,20 @@
   ThreadStackTrace** _stack_traces;
   int _num_threads;
 
-  // accessors
-  DumpWriter* writer() const                    { return _writer; }
+  // accessors and setters
+  static VM_HeapDumper* dumper()         {  assert(_global_dumper != NULL, "Error"); return _global_dumper; }
+  static DumpWriter* writer()            {  assert(_global_writer != NULL, "Error"); return _global_writer; }
+  void set_global_dumper() {
+    assert(_global_dumper == NULL, "Error");
+    _global_dumper = this;
+  }
+  void set_global_writer() {
+    assert(_global_writer == NULL, "Error");
+    _global_writer = _local_writer;
+  }
+  void clear_global_dumper() { _global_dumper = NULL; }
+  void clear_global_writer() { _global_writer = NULL; }
+
   bool is_segmented_dump() const                { return _is_segmented_dump; }
   void set_segmented_dump()                     { _is_segmented_dump = true; }
   jlong dump_start() const                      { return _dump_start; }
@@ -1357,7 +1370,7 @@
     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
                     0 /* total full collections, dummy, ignored */,
                     gc_before_heap_dump) {
-    _writer = writer;
+    _local_writer = writer;
     _gc_before_heap_dump = gc_before_heap_dump;
     _is_segmented_dump = false;
     _dump_start = (jlong)-1;
@@ -1381,6 +1394,9 @@
   void doit();
 };
 
+VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
+DumpWriter*    VM_HeapDumper::_global_writer = NULL;
+
 bool VM_HeapDumper::skip_operation() const {
   return false;
 }
@@ -1479,31 +1495,28 @@
 void VM_HeapDumper::do_load_class(klassOop k) {
   static u4 class_serial_num = 0;
 
-  VM_HeapDumper* dumper = ((VM_HeapDumper*)VMThread::vm_operation());
-  DumpWriter* writer = dumper->writer();
-
   // len of HPROF_LOAD_CLASS record
   u4 remaining = 2*oopSize + 2*sizeof(u4);
 
   // write a HPROF_LOAD_CLASS for the class and each array class
   do {
-    DumperSupport::write_header(writer, HPROF_LOAD_CLASS, remaining);
+    DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
 
     // class serial number is just a number
-    writer->write_u4(++class_serial_num);
+    writer()->write_u4(++class_serial_num);
 
     // class ID
     Klass* klass = Klass::cast(k);
-    writer->write_classID(klass);
+    writer()->write_classID(klass);
 
     // add the klassOop and class serial number pair
-    dumper->add_class_serial_number(klass, class_serial_num);
+    dumper()->add_class_serial_number(klass, class_serial_num);
 
-    writer->write_u4(STACK_TRACE_ID);
+    writer()->write_u4(STACK_TRACE_ID);
 
     // class name ID
     symbolOop name = klass->name();
-    writer->write_objectID(name);
+    writer()->write_objectID(name);
 
     // write a LOAD_CLASS record for the array type (if it exists)
     k = klass->array_klass_or_null();
@@ -1512,17 +1525,13 @@
 
 // writes a HPROF_GC_CLASS_DUMP record for the given class
 void VM_HeapDumper::do_class_dump(klassOop k) {
-  VM_HeapDumper* dumper = ((VM_HeapDumper*)VMThread::vm_operation());
-  DumpWriter* writer = dumper->writer();
-  DumperSupport::dump_class_and_array_classes(writer, k);
+  DumperSupport::dump_class_and_array_classes(writer(), k);
 }
 
 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
 // array (and each multi-dimensional array too)
 void VM_HeapDumper::do_basic_type_array_class_dump(klassOop k) {
-  VM_HeapDumper* dumper = ((VM_HeapDumper*)VMThread::vm_operation());
-  DumpWriter* writer = dumper->writer();
-  DumperSupport::dump_basic_type_array_class(writer, k);
+  DumperSupport::dump_basic_type_array_class(writer(), k);
 }
 
 // Walk the stack of the given thread.
@@ -1658,6 +1667,11 @@
     ch->ensure_parsability(false);
   }
 
+  // At this point we should be the only dumper active, so
+  // the following should be safe.
+  set_global_dumper();
+  set_global_writer();
+
   // Write the file header - use 1.0.2 for large heaps, otherwise 1.0.1
   size_t used = ch->used();
   const char* header;
@@ -1667,6 +1681,7 @@
   } else {
     header = "JAVA PROFILE 1.0.1";
   }
+
   // header is few bytes long - no chance to overflow int
   writer()->write_raw((void*)header, (int)strlen(header));
   writer()->write_u1(0); // terminator
@@ -1723,6 +1738,10 @@
   // fixes up the length of the dump record. In the case of a segmented
   // heap then the HPROF_HEAP_DUMP_END record is also written.
   end_of_dump();
+
+  // Now we clear the global variables, so that a future dumper might run.
+  clear_global_dumper();
+  clear_global_writer();
 }
 
 void VM_HeapDumper::dump_stack_traces() {
@@ -1790,7 +1809,12 @@
 
   // generate the dump
   VM_HeapDumper dumper(&writer, _gc_before_heap_dump);
-  VMThread::execute(&dumper);
+  if (Thread::current()->is_VM_thread()) {
+    assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
+    dumper.doit();
+  } else {
+    VMThread::execute(&dumper);
+  }
 
   // close dump file and record any error that the writer may have encountered
   writer.close();
@@ -1845,49 +1869,68 @@
   }
 }
 
-
-// Called by error reporting
+// Called by error reporting by a single Java thread outside of a JVM safepoint,
+// or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
+// callers are strictly serialized and guaranteed not to interfere below. For more
+// general use, however, this method will need modification to prevent
+// inteference when updating the static variables base_path and dump_file_seq below.
 void HeapDumper::dump_heap() {
-  static char path[JVM_MAXPATHLEN];
+  static char base_path[JVM_MAXPATHLEN] = {'\0'};
+  static uint dump_file_seq = 0;
+  char   my_path[JVM_MAXPATHLEN] = {'\0'};
 
   // The dump file defaults to java_pid<pid>.hprof in the current working
   // directory. HeapDumpPath=<file> can be used to specify an alternative
   // dump file name or a directory where dump file is created.
-  bool use_default_filename = true;
-  if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
-    path[0] = '\0'; // HeapDumpPath=<file> not specified
-  } else {
-    assert(strlen(HeapDumpPath) < sizeof(path), "HeapDumpPath too long");
-    strcpy(path, HeapDumpPath);
-    // check if the path is a directory (must exist)
-    DIR* dir = os::opendir(path);
-    if (dir == NULL) {
-      use_default_filename = false;
+  if (dump_file_seq == 0) { // first time in, we initialize base_path
+    bool use_default_filename = true;
+    if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
+      // HeapDumpPath=<file> not specified
     } else {
-      // HeapDumpPath specified a directory. We append a file separator
-      // (if needed).
-      os::closedir(dir);
-      size_t fs_len = strlen(os::file_separator());
-      if (strlen(path) >= fs_len) {
-        char* end = path;
-        end += (strlen(path) - fs_len);
-        if (strcmp(end, os::file_separator()) != 0) {
-          assert(strlen(path) + strlen(os::file_separator()) < sizeof(path),
-            "HeapDumpPath too long");
-          strcat(path, os::file_separator());
+      assert(strlen(HeapDumpPath) < sizeof(base_path), "HeapDumpPath too long");
+      strcpy(base_path, HeapDumpPath);
+      // check if the path is a directory (must exist)
+      DIR* dir = os::opendir(base_path);
+      if (dir == NULL) {
+        use_default_filename = false;
+      } else {
+        // HeapDumpPath specified a directory. We append a file separator
+        // (if needed).
+        os::closedir(dir);
+        size_t fs_len = strlen(os::file_separator());
+        if (strlen(base_path) >= fs_len) {
+          char* end = base_path;
+          end += (strlen(base_path) - fs_len);
+          if (strcmp(end, os::file_separator()) != 0) {
+            assert(strlen(base_path) + strlen(os::file_separator()) < sizeof(base_path),
+              "HeapDumpPath too long");
+            strcat(base_path, os::file_separator());
+          }
         }
       }
     }
+    // If HeapDumpPath wasn't a file name then we append the default name
+    if (use_default_filename) {
+      char fn[32];
+      sprintf(fn, "java_pid%d", os::current_process_id());
+      assert(strlen(base_path) + strlen(fn) < sizeof(base_path), "HeapDumpPath too long");
+      strcat(base_path, fn);
+    }
+    assert(strlen(base_path) < sizeof(my_path), "Buffer too small");
+    strcpy(my_path, base_path);
+  } else {
+    // Append a sequence number id for dumps following the first
+    char fn[33];
+    sprintf(fn, ".%d", dump_file_seq);
+    assert(strlen(base_path) + strlen(fn) < sizeof(my_path), "HeapDumpPath too long");
+    strcpy(my_path, base_path);
+    strcat(my_path, fn);
   }
-  // If HeapDumpPath wasn't a file name then we append the default name
-  if (use_default_filename) {
-    char fn[32];
-    sprintf(fn, "java_pid%d.hprof", os::current_process_id());
-    assert(strlen(path) + strlen(fn) < sizeof(path), "HeapDumpPath too long");
-    strcat(path, fn);
-  }
+  dump_file_seq++;   // increment seq number for next time we dump
+  assert(strlen(".hprof") + strlen(my_path) < sizeof(my_path), "HeapDumpPath too long");
+  strcat(my_path, ".hprof");
 
   HeapDumper dumper(false /* no GC before heap dump */,
                     true  /* send to tty */);
-  dumper.dump(path);
+  dumper.dump(my_path);
 }
--- a/hotspot/src/share/vm/services/heapDumper.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/services/heapDumper.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -53,7 +53,7 @@
 
  public:
   HeapDumper(bool gc_before_heap_dump) :
-    _gc_before_heap_dump(gc_before_heap_dump), _error(NULL), _print_to_tty(false)  { }
+    _gc_before_heap_dump(gc_before_heap_dump), _error(NULL), _print_to_tty(false) { }
   HeapDumper(bool gc_before_heap_dump, bool print_to_tty) :
     _gc_before_heap_dump(gc_before_heap_dump), _error(NULL), _print_to_tty(print_to_tty) { }
 
--- a/hotspot/src/share/vm/services/management.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/services/management.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -881,7 +881,7 @@
     i++; p *= 2;
   }
   // p = 2^(i+1) && x < p (i.e., 2^i <= x < 2^(i+1))
-  // (if p = 0 then overflow occured and i = 31)
+  // (if p = 0 then overflow occurred and i = 31)
   return i;
 }
 
@@ -895,7 +895,7 @@
     i++; p *= 2;
   }
   // p = 2^(i+1) && x < p (i.e., 2^i <= x < 2^(i+1))
-  // (if p = 0 then overflow occured and i = 63)
+  // (if p = 0 then overflow occurred and i = 63)
   return i;
 }
 
--- a/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/globalDefinitions_visCPP.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_visCPP.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -153,16 +153,8 @@
 //----------------------------------------------------------------------------------------------------
 // Miscellaneous
 
-inline int vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
-  // If number of characters written == count, Windows doesn't write a
-  // terminating NULL, so we do it ourselves.
-  int ret = _vsnprintf(buf, count, fmt, argptr);
-  if (count > 0) buf[count-1] = '\0';
-  return ret;
-}
-
 // Visual Studio 2005 deprecates POSIX names - use ISO C++ names instead
-#if _MSC_VER >= 1400 && !defined(_WIN64)
+#if _MSC_VER >= 1400
 #define open _open
 #define close _close
 #define read  _read
@@ -180,6 +172,17 @@
 #pragma warning( disable : 4201 ) // nonstandard extension used : nameless struct/union (needed in windows.h)
 #pragma warning( disable : 4511 ) // copy constructor could not be generated
 #pragma warning( disable : 4291 ) // no matching operator delete found; memory will not be freed if initialization thows an exception
+#if _MSC_VER >= 1400
+#pragma warning( disable : 4996 ) // unsafe string functions. Same as define _CRT_SECURE_NO_WARNINGS/_CRT_SECURE_NO_DEPRICATE
+#endif
+
+inline int vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
+  // If number of characters written == count, Windows doesn't write a
+  // terminating NULL, so we do it ourselves.
+  int ret = _vsnprintf(buf, count, fmt, argptr);
+  if (count > 0) buf[count-1] = '\0';
+  return ret;
+}
 
 // Portability macros
 #define PRAGMA_INTERFACE
--- a/hotspot/src/share/vm/utilities/growableArray.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/growableArray.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -43,11 +43,13 @@
 #endif
 
 void* GenericGrowableArray::raw_allocate(int elementSize) {
+  assert(_max >= 0, "integer overflow");
+  size_t byte_size = elementSize * (size_t) _max;
   if (on_stack()) {
-    return (void*)resource_allocate_bytes(elementSize * _max);
+    return (void*)resource_allocate_bytes(byte_size);
   } else if (on_C_heap()) {
-    return (void*)AllocateHeap(elementSize * _max, "GrET in " __FILE__);
+    return (void*)AllocateHeap(byte_size, "GrET in " __FILE__);
   } else {
-    return _arena->Amalloc(elementSize * _max);
+    return _arena->Amalloc(byte_size);
   }
 }
--- a/hotspot/src/share/vm/utilities/ostream.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/taskqueue.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/taskqueue.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/taskqueue.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/taskqueue.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/utilities/vmError.cpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/vmError.cpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -306,7 +306,7 @@
 
          strncpy(buf, file, buflen);
          if (len + 10 < buflen) {
-           sprintf(buf + len, ":" SIZE_FORMAT, _lineno);
+           sprintf(buf + len, ":%d", _lineno);
          }
          st->print(" (%s)", buf);
        } else {
@@ -420,7 +420,7 @@
 
        if (fr.sp()) {
          st->print(",  sp=" PTR_FORMAT, fr.sp());
-         st->print(",  free space=%dk",
+         st->print(",  free space=%" INTPTR_FORMAT "k",
                      ((intptr_t)fr.sp() - (intptr_t)stack_bottom) >> 10);
        }
 
--- a/hotspot/src/share/vm/utilities/vmError.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/vmError.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
 
   // additional info for VM internal errors
   const char * _filename;
-  size_t       _lineno;
+  int          _lineno;
 
   // used by fatal error handler
   int          _current_step;
--- a/hotspot/src/share/vm/utilities/workgroup.hpp	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/src/share/vm/utilities/workgroup.hpp	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/test/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/test/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/6378821/Test6378821.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6378821
+ * @summary where available, bitCount() should use POPC on SPARC processors and AMD+10h
+ *
+ * @run main/othervm -Xcomp -XX:CompileOnly=Test6378821.fcomp Test6378821
+ */
+
+public class Test6378821 {
+    static final int[]  ia = new int[]  { 0x12345678 };
+    static final long[] la = new long[] { 0x12345678abcdefL };
+
+    public static void main(String [] args) {
+        // Resolve the class and the method.
+        Integer.bitCount(1);
+        Long.bitCount(1);
+
+        sub(ia[0]);
+        sub(la[0]);
+        sub(ia);
+        sub(la);
+    }
+
+    static void check(int i, int expected, int result) {
+        if (result != expected) {
+            throw new InternalError("Wrong population count for " + i + ": " + result + " != " + expected);
+        }
+    }
+
+    static void check(long l, int expected, int result) {
+        if (result != expected) {
+            throw new InternalError("Wrong population count for " + l + ": " + result + " != " + expected);
+        }
+    }
+
+    static void sub(int i)     { check(i,     fint(i),  fcomp(i) ); }
+    static void sub(int[] ia)  { check(ia[0], fint(ia), fcomp(ia)); }
+    static void sub(long l)    { check(l,     fint(l),  fcomp(l) ); }
+    static void sub(long[] la) { check(la[0], fint(la), fcomp(la)); }
+
+    static int fint (int i)     { return Integer.bitCount(i); }
+    static int fcomp(int i)     { return Integer.bitCount(i); }
+
+    static int fint (int[] ia)  { return Integer.bitCount(ia[0]); }
+    static int fcomp(int[] ia)  { return Integer.bitCount(ia[0]); }
+
+    static int fint (long l)    { return Long.bitCount(l); }
+    static int fcomp(long l)    { return Long.bitCount(l); }
+
+    static int fint (long[] la) { return Long.bitCount(la[0]); }
+    static int fcomp(long[] la) { return Long.bitCount(la[0]); }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/6636138/Test1.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @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 -XX:+UseSuperword Test1
+ */
+
+class Test1 {
+
+    public static void init(int src[], int [] dst, int[] ref) {
+        // initialize the arrays
+        for (int i =0; i<src.length; i++) {
+            src[i] =  i;
+            dst[i] = 2;      // yes, dst[i] needed(otherwise src[i] will be replaced with i)
+            ref[i] = src[i]; // src[i] depends on the store src[i]
+        }
+    }
+
+    public static void verify(int src[], int[] ref) {
+        // check whether src and ref are equal
+        for (int i = 0; i < src.length; i++) {
+            if (src[i] != ref[i]) {
+                System.out.println("Error: src and ref don't match at " + i);
+                System.exit(-1);
+            }
+        }
+    }
+
+    public static void test() {
+        int[] src = new int[34];
+        int[] dst = new int[34];
+        int[] ref = new int[34];
+
+        init(src, dst, ref);
+        verify(src, ref);
+    }
+
+    public static void main(String[] args) {
+        for (int i=0; i< 2000; i++) {
+            test();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/6636138/Test2.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @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 -XX:+UseSuperword Test2
+ */
+
+class Test2 {
+
+    public static void init(int src[]) {
+        // Initialize the array
+        for (int i = 0; i < src.length; i++)
+            src[i] = i;
+    }
+
+   public static void shift(int src[]) {
+       //left-shift the array
+       for (int i = src.length-1; i > 0; i--){
+           int tmp  = src[i];
+           src[i]   = src[i-1];
+           src[i-1] = tmp;
+       }
+    }
+
+    public static void verify(int src[]) {
+        for (int i = 0; i < src.length; i++){
+            int value = (i-1 + src.length)%src.length; // correct value after shifting
+                if (src[i] != value) {
+                    System.out.println("Error: src["+i+"] should be "+ value + " instead of " + src[i]);
+                    System.exit(-1);
+                }
+        }
+    }
+
+    public static void test() {
+        int[] src = new int[10];
+        init(src);
+        shift(src);
+        verify(src);
+    }
+
+    public static void main(String[] args) {
+        for (int i=0; i< 2000; i++)
+            test();
+    }
+}
--- a/hotspot/test/compiler/6757316/Test6757316.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/test/compiler/6757316/Test6757316.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/test/compiler/6758234/Test6758234.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/test/compiler/6758234/Test6758234.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/test/compiler/6775880/Test.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/test/compiler/6775880/Test.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/test/compiler/6778657/Test.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/hotspot/test/compiler/6778657/Test.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/6797305/Test6797305.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6797305
+ * @summary Add LoadUB and LoadUI opcode class
+ *
+ * @run main/othervm -Xcomp -XX:CompileOnly=Test6797305.loadB,Test6797305.loadB2L,Test6797305.loadUB,Test6797305.loadUBmask,Test6797305.loadUB2L,Test6797305.loadS,Test6797305.loadS2L,Test6797305.loadUS,Test6797305.loadUSmask,Test6797305.loadUS2L,Test6797305.loadI,Test6797305.loadI2L,Test6797305.loadUI2L,Test6797305.loadL Test6797305
+ */
+
+public class Test6797305 {
+    static final byte[]  ba = new byte[]  { -1 };
+    static final short[] sa = new short[] { -1 };
+    static final int[]   ia = new int[]   { -1 };
+    static final long[]  la = new long[]  { -1 };
+
+    public static void main(String[] args)
+    {
+        long b = loadB(ba);
+        if (b != -1)
+            throw new InternalError("loadB failed: " + b + " != " + -1);
+
+        long b2l = loadB2L(ba);
+        if (b2l != -1L)
+            throw new InternalError("loadB2L failed: " + b2l + " != " + -1L);
+
+        int ub = loadUB(ba);
+        if (ub != 0xFF)
+            throw new InternalError("loadUB failed: " + ub + " != " + 0xFF);
+
+        int ubmask = loadUBmask(ba);
+        if (ubmask != 0xFE)
+            throw new InternalError("loadUBmask failed: " + ubmask + " != " + 0xFE);
+
+        long ub2l = loadUB2L(ba);
+        if (ub2l != 0xFFL)
+            throw new InternalError("loadUB2L failed: " + ub2l + " != " + 0xFFL);
+
+        int s = loadS(sa);
+        if (s != -1)
+            throw new InternalError("loadS failed: " + s + " != " + -1);
+
+        long s2l = loadS2L(sa);
+        if (s2l != -1L)
+            throw new InternalError("loadS2L failed: " + s2l + " != " + -1L);
+
+        int us = loadUS(sa);
+        if (us != 0xFFFF)
+            throw new InternalError("loadUS failed: " + us + " != " + 0xFFFF);
+
+        int usmask = loadUSmask(sa);
+        if (usmask != 0xFFFE)
+            throw new InternalError("loadUBmask failed: " + ubmask + " != " + 0xFFFE);
+
+        long us2l = loadUS2L(sa);
+        if (us2l != 0xFFFFL)
+            throw new InternalError("loadUS2L failed: " + us2l + " != " + 0xFFFFL);
+
+        int i = loadI(ia);
+        if (i != -1)
+            throw new InternalError("loadI failed: " + i + " != " + -1);
+
+        long i2l = loadI2L(ia);
+        if (i2l != -1L)
+            throw new InternalError("loadI2L failed: " + i2l + " != " + -1L);
+
+        long ui2l = loadUI2L(ia);
+        if (ui2l != 0xFFFFFFFFL)
+            throw new InternalError("loadUI2L failed: " + ui2l + " != " + 0xFFFFFFFFL);
+
+        long l = loadL(la);
+        if (l != -1L)
+            throw new InternalError("loadL failed: " + l + " != " + -1L);
+    }
+
+    static int  loadB     (byte[] ba)  { return ba[0];               }
+    static long loadB2L   (byte[] ba)  { return ba[0];               }
+    static int  loadUB    (byte[] ba)  { return ba[0] & 0xFF;        }
+    static int  loadUBmask(byte[] ba)  { return ba[0] & 0xFE;        }
+    static long loadUB2L  (byte[] ba)  { return ba[0] & 0xFF;        }
+
+    static int  loadS     (short[] sa) { return sa[0];               }
+    static long loadS2L   (short[] sa) { return sa[0];               }
+    static int  loadUS    (short[] sa) { return sa[0] & 0xFFFF;      }
+    static int  loadUSmask(short[] sa) { return sa[0] & 0xFFFE;      }
+    static long loadUS2L  (short[] sa) { return sa[0] & 0xFFFF;      }
+
+    static int  loadI     (int[] ia)   { return ia[0];               }
+    static long loadI2L   (int[] ia)   { return ia[0];               }
+    static long loadUI2L  (int[] ia)   { return ia[0] & 0xFFFFFFFFL; }
+
+    static long loadL     (long[] la)  { return la[0];               }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/6819213/TestBootNativeLibraryPath.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test TestBootNativeLibraryPath.java
+ * @bug 6819213
+ * @compile -XDignore.symbol.file TestBootNativeLibraryPath.java
+ * @summary verify sun.boot.native.library.path is expandable on 32 bit systems
+ * @run main TestBootNativeLibraryPath
+ * @author ksrini
+*/
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+public class TestBootNativeLibraryPath {
+
+    private static final String TESTFILE = "Test6";
+
+    static void createTestClass() throws IOException {
+        FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
+        PrintStream ps = new PrintStream(fos);
+        ps.println("public class " + TESTFILE + "{");
+        ps.println("public static void main(String[] args) {\n");
+        ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
+        ps.println("}}\n");
+        ps.close();
+        fos.close();
+
+        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
+        String javacOpts[] = {TESTFILE + ".java"};
+        if (javac.run(null, null, null,  javacOpts) != 0) {
+            throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
+        }
+    }
+
+    static List<String> doExec(String... args) {
+        String javaCmd = System.getProperty("java.home") + "/bin/java";
+        if (!new File(javaCmd).exists()) {
+            javaCmd = System.getProperty("java.home") + "/bin/java.exe";
+        }
+
+        ArrayList<String> cmds = new ArrayList<String>();
+        cmds.add(javaCmd);
+        for (String x : args) {
+            cmds.add(x);
+        }
+        System.out.println("cmds=" + cmds);
+        ProcessBuilder pb = new ProcessBuilder(cmds);
+
+        Map<String, String> env = pb.environment();
+        pb.directory(new File("."));
+
+        List<String> out = new ArrayList<String>();
+        try {
+            pb.redirectErrorStream(true);
+            Process p = pb.start();
+            BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()),8192);
+            String in = rd.readLine();
+            while (in != null) {
+                out.add(in);
+                System.out.println(in);
+                in = rd.readLine();
+            }
+            int retval = p.waitFor();
+            p.destroy();
+            if (retval != 0) {
+                throw new RuntimeException("Error: test returned non-zero value");
+            }
+            return out;
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            throw new RuntimeException(ex.getMessage());
+        }
+    }
+
+    public static void main(String[] args) {
+        try {
+            if (!System.getProperty("sun.arch.data.model").equals("32")) {
+                System.out.println("Warning: test skipped for 64-bit systems\n");
+                return;
+            }
+            String osname = System.getProperty("os.name");
+            if (osname.startsWith("Windows")) {
+                osname = "Windows";
+            }
+
+            createTestClass();
+
+            // Test a simple path
+            String libpath = File.pathSeparator + "tmp" + File.pathSeparator + "foobar";
+            List<String> processOut = null;
+            String sunbootlibrarypath = "-Dsun.boot.library.path=" + libpath;
+            processOut = doExec(sunbootlibrarypath, "-cp", ".", TESTFILE);
+            if (processOut == null || !processOut.get(0).endsWith(libpath)) {
+                throw new RuntimeException("Error: did not get expected error string");
+            }
+        } catch (IOException ex) {
+            throw new RuntimeException("Unexpected error " + ex);
+        }
+    }
+}
--- a/jaxp/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/jaxp/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 d711ad1954b294957737ea386cfd4d3c05028a36 jdk7-b47
 39de90eb4822cafaacc69edd67ab5547e55ae920 jdk7-b48
 5c1f24531903573c1830775432276da567243f9c jdk7-b49
+e8514e2be76d90889ebdb90d627aca2db5c150c6 jdk7-b50
+ae890d80d5dffcd4dc77a1f17d768e192d1852c7 jdk7-b51
+69ad87dc25cbcaaaded4727199395ad0c78bc427 jdk7-b52
+e8837366d3fd72f7c7a47ebfdbd5106c16156f12 jdk7-b53
--- a/jaxp/make/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jaxp/make/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jaxp/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-#!echo "This is not a shell script"
-#############################################################################
-#
-# Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-#############################################################################
-#
-# JPRT shell configuration for building.
-#
-# Input environment variables:
-#    ALT_BOOTDIR
-#    ALT_SLASH_JAVA
-#    ALT_JDK_IMPORT_PATH
-#    Windows Only:
-#      PATH
-#      PROCESSOR_IDENTIFIER
-#      ROOTDIR
-#
-# Output variable settings:
-#    make    Full path to GNU make
-#
-# Output environment variables:
-#    PATH
-#    Windows Only:
-#      ALT_DEVTOOLS_PATH (To avoid the C:/UTILS default)
-#
-# After JDK6, most settings will be found via ALT_SLASH_JAVA or
-#   by way of other system environment variables. If this was JDK5
-#   or an older JDK, you might need to export more ALT_* variables.
-#
-#############################################################################
-
-#############################################################################
-# Error
-error() # message
-{
-  echo "ERROR: $1"
-  exit 6
-}
-# Directory must exist
-dirMustExist() # dir name
-{
-  if [ ! -d "$1" ] ; then
-    error "Directory for $2 does not exist: $1"
-  fi
-}
-# File must exist
-fileMustExist() # dir name
-{
-  if [ ! -f "$1" ] ; then
-    error "File for $2 does not exist: $1"
-  fi
-}
-#############################################################################
-
-# Should be set by JPRT as the 3 basic inputs
-bootdir="${ALT_BOOTDIR}"
-slashjava="${ALT_SLASH_JAVA}"
-jdk_import="${ALT_JDK_IMPORT_PATH}"
-
-# Check input
-dirMustExist "${bootdir}"    ALT_BOOTDIR
-dirMustExist "${slashjava}"  ALT_SLASH_JAVA
-dirMustExist "${jdk_import}" ALT_JDK_IMPORT_PATH
-
-# Uses 'uname -s', but only expect SunOS or Linux, assume Windows otherwise.
-osname=`uname -s`
-if [ "${osname}" = SunOS ] ; then
-   
-    # SOLARIS: Sparc or X86
-    osarch=`uname -p`
-    if [ "${osarch}" = sparc ] ; then
-	solaris_arch=sparc
-    else
-	solaris_arch=i386
-    fi
-
-    # Add basic solaris system paths
-    path4sdk=/usr/ccs/bin:/usr/ccs/lib:/usr/bin:/bin:/usr/sfw/bin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-
-    # Find GNU make
-    make=/usr/sfw/bin/gmake
-    if [ ! -f ${make} ] ; then
-	make=/opt/sfw/bin/gmake
-	if [ ! -f ${make} ] ; then
-	    make=${slashjava}/devtools/${solaris_arch}/bin/gnumake
-        fi 
-    fi
-    fileMustExist "${make}" make
-
-    # File creation mask
-    umask 002
-
-elif [ "${osname}" = Linux ] ; then
-   
-    # LINUX: X86, AMD64
-    osarch=`uname -m`
-    if [ "${osarch}" = i686 ] ; then
-	linux_arch=i586
-    elif [ "${osarch}" = x86_64 ] ; then
-	linux_arch=amd64
-    fi
-
-    # Add basic paths
-    path4sdk=/usr/bin:/bin:/usr/sbin:/sbin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-    
-    # Find GNU make
-    make=/usr/bin/make
-    fileMustExist "${make}" make
-
-    umask 002
-
-else
-
-    # Windows: Differs on CYGWIN vs. MKS.
-    #   Also, blanks in pathnames gives GNU make headaches, so anything placed
-    #   in any ALT_* variable should be the short windows dosname.
-   
-    # WINDOWS: Install and use MKS or CYGWIN (should have already been done)
-    #   Assumption here is that you are in a shell window via MKS or cygwin.
-    #   MKS install should have defined the environment variable ROOTDIR.
-    #   We also need to figure out which one we have: X86, AMD64
-    if [ "`echo ${PROCESSOR_IDENTIFIER} | fgrep AMD64`" != "" ] ; then
-	windows_arch=amd64
-    else
-	windows_arch=i586
-    fi
-    
-    # We need to determine if we are running a CYGWIN shell or an MKS shell
-    #    (if uname isn't available, then it will be unix_toolset=unknown)
-    unix_toolset=unknown
-    if [ "`uname -a | fgrep Cygwin`" = "" -a -d "${ROOTDIR}" ] ; then
-        # We kind of assume ROOTDIR is where MKS is and it's ok
-        unix_toolset=MKS
-        mkshome=`dosname -s "${ROOTDIR}"`
-	# Utility to convert to short pathnames without spaces
-	dosname="${mkshome}/mksnt/dosname -s"
-        # Most unix utilities are in the mksnt directory of ROOTDIR
-        unixcommand_path="${mkshome}/mksnt"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-	devtools_path="${slashjava}/devtools/win32/bin"
-	path4sdk="${devtools_path};${path4sdk}"
-	# Normally this need not be set, but on Windows it's default is C:/UTILS
-        ALT_DEVTOOLS_PATH="${devtools_path}"
-	export ALT_DEVTOOLS_PATH
-        dirMustExist "${devtools_path}" ALT_DEVTOOLS_PATH
-        # Find GNU make
-        make="${devtools_path}/gnumake.exe"
-        fileMustExist "${make}" make
-    elif [ "`uname -a | fgrep Cygwin`" != "" -a -f /bin/cygpath ] ; then
-        # For CYGWIN, uname will have "Cygwin" in it, and /bin/cygpath should exist
-        unix_toolset=CYGWIN
-	# Utility to convert to short pathnames without spaces
-	dosname="/usr/bin/cygpath -a -m -s"
-        # Most unix utilities are in the /usr/bin
-        unixcommand_path="/usr/bin"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-        # Find GNU make
-        make="${unixcommand_path}/make.exe"
-        fileMustExist "${make}" make
-    else
-      echo "WARNING: Cannot figure out if this is MKS or CYGWIN"
-    fi
-
-    # WINDOWS: Get the previous JDK to be used to bootstrap the build
-    path4sdk="${bootdir}/bin;${path4sdk}"
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk="${antbindir};${path4sdk}"
-
-    # Turn all \\ into /, remove duplicates and trailing /
-    slash_path="`echo ${path4sdk} | sed -e 's@\\\\@/@g' -e 's@//@/@g' -e 's@/$@@' -e 's@/;@;@g'`"
-    
-    # For windows, it's hard to know where the system is, so we just add this
-    #    to PATH.
-    path4sdk="${slash_path};${PATH}"
-    
-    # Convert path4sdk to cygwin style
-    if [ "${unix_toolset}" = CYGWIN ] ; then
-	path4sdk="`/usr/bin/cygpath -p ${path4sdk}`"
-    fi
-
-fi
-
-# Export PATH setting
-PATH="${path4sdk}"
-export PATH
-
-# Things we need to unset
-unset LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH_32
-unset LD_LIBRARY_PATH_64
-unset JAVA_HOME
-
--- a/jaxws/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/jaxws/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 223011570edbd49bb0fe51cdeb2089f95d305267 jdk7-b47
 01e5dd31d0c10a2db3d50db346905d2d3db45e88 jdk7-b48
 18ca864890f3d4ed942ecbffb78c936a57759921 jdk7-b49
+5be52db581f1ea91ab6e0eb34ba7f439125bfb16 jdk7-b50
+41a66a42791ba90bff489af72cbfea71be9b40a5 jdk7-b51
+e646890d18b770f625f14ed4ad5c50554d8d3d8b jdk7-b52
+b250218eb2e534384667ec73e3713e684667fd4c jdk7-b53
--- a/jaxws/make/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jaxws/make/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jaxws/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-#!echo "This is not a shell script"
-#############################################################################
-#
-# Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-#############################################################################
-#
-# JPRT shell configuration for building.
-#
-# Input environment variables:
-#    ALT_BOOTDIR
-#    ALT_SLASH_JAVA
-#    ALT_JDK_IMPORT_PATH
-#    Windows Only:
-#      PATH
-#      PROCESSOR_IDENTIFIER
-#      ROOTDIR
-#
-# Output variable settings:
-#    make    Full path to GNU make
-#
-# Output environment variables:
-#    PATH
-#    Windows Only:
-#      ALT_DEVTOOLS_PATH (To avoid the C:/UTILS default)
-#
-# After JDK6, most settings will be found via ALT_SLASH_JAVA or
-#   by way of other system environment variables. If this was JDK5
-#   or an older JDK, you might need to export more ALT_* variables.
-#
-#############################################################################
-
-#############################################################################
-# Error
-error() # message
-{
-  echo "ERROR: $1"
-  exit 6
-}
-# Directory must exist
-dirMustExist() # dir name
-{
-  if [ ! -d "$1" ] ; then
-    error "Directory for $2 does not exist: $1"
-  fi
-}
-# File must exist
-fileMustExist() # dir name
-{
-  if [ ! -f "$1" ] ; then
-    error "File for $2 does not exist: $1"
-  fi
-}
-#############################################################################
-
-# Should be set by JPRT as the 3 basic inputs
-bootdir="${ALT_BOOTDIR}"
-slashjava="${ALT_SLASH_JAVA}"
-jdk_import="${ALT_JDK_IMPORT_PATH}"
-
-# Check input
-dirMustExist "${bootdir}"    ALT_BOOTDIR
-dirMustExist "${slashjava}"  ALT_SLASH_JAVA
-dirMustExist "${jdk_import}" ALT_JDK_IMPORT_PATH
-
-# Uses 'uname -s', but only expect SunOS or Linux, assume Windows otherwise.
-osname=`uname -s`
-if [ "${osname}" = SunOS ] ; then
-   
-    # SOLARIS: Sparc or X86
-    osarch=`uname -p`
-    if [ "${osarch}" = sparc ] ; then
-	solaris_arch=sparc
-    else
-	solaris_arch=i386
-    fi
-
-    # Add basic solaris system paths
-    path4sdk=/usr/ccs/bin:/usr/ccs/lib:/usr/bin:/bin:/usr/sfw/bin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-
-    # Find GNU make
-    make=/usr/sfw/bin/gmake
-    if [ ! -f ${make} ] ; then
-	make=/opt/sfw/bin/gmake
-	if [ ! -f ${make} ] ; then
-	    make=${slashjava}/devtools/${solaris_arch}/bin/gnumake
-        fi 
-    fi
-    fileMustExist "${make}" make
-
-    # File creation mask
-    umask 002
-
-elif [ "${osname}" = Linux ] ; then
-   
-    # LINUX: X86, AMD64
-    osarch=`uname -m`
-    if [ "${osarch}" = i686 ] ; then
-	linux_arch=i586
-    elif [ "${osarch}" = x86_64 ] ; then
-	linux_arch=amd64
-    fi
-
-    # Add basic paths
-    path4sdk=/usr/bin:/bin:/usr/sbin:/sbin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-    
-    # Find GNU make
-    make=/usr/bin/make
-    fileMustExist "${make}" make
-
-    umask 002
-
-else
-
-    # Windows: Differs on CYGWIN vs. MKS.
-    #   Also, blanks in pathnames gives GNU make headaches, so anything placed
-    #   in any ALT_* variable should be the short windows dosname.
-   
-    # WINDOWS: Install and use MKS or CYGWIN (should have already been done)
-    #   Assumption here is that you are in a shell window via MKS or cygwin.
-    #   MKS install should have defined the environment variable ROOTDIR.
-    #   We also need to figure out which one we have: X86, AMD64
-    if [ "`echo ${PROCESSOR_IDENTIFIER} | fgrep AMD64`" != "" ] ; then
-	windows_arch=amd64
-    else
-	windows_arch=i586
-    fi
-    
-    # We need to determine if we are running a CYGWIN shell or an MKS shell
-    #    (if uname isn't available, then it will be unix_toolset=unknown)
-    unix_toolset=unknown
-    if [ "`uname -a | fgrep Cygwin`" = "" -a -d "${ROOTDIR}" ] ; then
-        # We kind of assume ROOTDIR is where MKS is and it's ok
-        unix_toolset=MKS
-        mkshome=`dosname -s "${ROOTDIR}"`
-	# Utility to convert to short pathnames without spaces
-	dosname="${mkshome}/mksnt/dosname -s"
-        # Most unix utilities are in the mksnt directory of ROOTDIR
-        unixcommand_path="${mkshome}/mksnt"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-	devtools_path="${slashjava}/devtools/win32/bin"
-	path4sdk="${devtools_path};${path4sdk}"
-	# Normally this need not be set, but on Windows it's default is C:/UTILS
-        ALT_DEVTOOLS_PATH="${devtools_path}"
-	export ALT_DEVTOOLS_PATH
-        dirMustExist "${devtools_path}" ALT_DEVTOOLS_PATH
-        # Find GNU make
-        make="${devtools_path}/gnumake.exe"
-        fileMustExist "${make}" make
-    elif [ "`uname -a | fgrep Cygwin`" != "" -a -f /bin/cygpath ] ; then
-        # For CYGWIN, uname will have "Cygwin" in it, and /bin/cygpath should exist
-        unix_toolset=CYGWIN
-	# Utility to convert to short pathnames without spaces
-	dosname="/usr/bin/cygpath -a -m -s"
-        # Most unix utilities are in the /usr/bin
-        unixcommand_path="/usr/bin"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-        # Find GNU make
-        make="${unixcommand_path}/make.exe"
-        fileMustExist "${make}" make
-    else
-      echo "WARNING: Cannot figure out if this is MKS or CYGWIN"
-    fi
-
-    # WINDOWS: Get the previous JDK to be used to bootstrap the build
-    path4sdk="${bootdir}/bin;${path4sdk}"
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk="${antbindir};${path4sdk}"
-
-    # Turn all \\ into /, remove duplicates and trailing /
-    slash_path="`echo ${path4sdk} | sed -e 's@\\\\@/@g' -e 's@//@/@g' -e 's@/$@@' -e 's@/;@;@g'`"
-    
-    # For windows, it's hard to know where the system is, so we just add this
-    #    to PATH.
-    path4sdk="${slash_path};${PATH}"
-    
-    # Convert path4sdk to cygwin style
-    if [ "${unix_toolset}" = CYGWIN ] ; then
-	path4sdk="`/usr/bin/cygpath -p ${path4sdk}`"
-    fi
-
-fi
-
-# Export PATH setting
-PATH="${path4sdk}"
-export PATH
-
-# Things we need to unset
-unset LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH_32
-unset LD_LIBRARY_PATH_64
-unset JAVA_HOME
-
--- a/jdk/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 b4ac413b1f129eeef0acab3f31081c1b7dfe3b27 jdk7-b47
 5fbd9ea7def17186693b6f7099b5d0dc73903eee jdk7-b48
 8311105ea7a3db7bcbcb2b696459127c7f2297a4 jdk7-b49
+58ba2cd5a25053684ec53205d95edeeaa0006f13 jdk7-b50
+fea0898259ae41c73620b1815aa48f036216155c jdk7-b51
+bcbeadb4a5d759b29e876ee2c83401e91ff22f60 jdk7-b52
+a2033addca678f9e4c0d92ffa1e389171cc9321d jdk7-b53
--- a/jdk/THIRD_PARTY_README	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/THIRD_PARTY_README	Fri Apr 10 13:05:12 2009 -0700
@@ -61,6 +61,28 @@
 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 notice is provided with respect to littlecms, which may be included with this software:  
+
+Little cms
+Copyright (C) 1998-2004 Marti Maria
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 %% This notice is provided with respect to zlib 1.1.3, which may be included with this software:   
 
 Acknowledgments:
@@ -115,16 +137,6 @@
 The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders.
 ____________________________________
 This formulation of W3C's notice and license became active on August 14 1998 so as to improve compatibility with GPL. This version ensures that W3C software licensing terms are no more restrictive than GPL and consequently W3C software may be distributed in GPL packages. See the older formulation for the policy prior to this date. Please see our Copyright FAQ for common questions about using materials from our site, including specific terms and conditions for packages like libwww, Amaya, and Jigsaw. Other questions about this notice can be directed to site-policy@w3.org.

-%% This notice is provided with respect to jscheme.jar, which may be included with this software: 
-Software License Agreement
-Copyright © 1998-2002 by Peter Norvig. 
-Permission is granted to anyone to use this software, in source or object code form, on any computer system, and to modify, compile, decompile, run, and redistribute it to anyone else, subject to the following restrictions: 
-1.The author makes no warranty of any kind, either expressed or implied, about the suitability of this software for any purpose.
-2.The author accepts no liability of any kind for damages or other consequences of the use of this software, even if they arise from defects in the software.
-3.The origin of this software must not be misrepresented, either by explicit claim or by omission.
-4.Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Altered versions may be distributed in packages under other licenses (such as the GNU license). 
-If you find this software useful, it would be nice if you let me (peter@norvig.com) know about it, and nicer still if you send me modifications that you are willing to share. However, you are not required to do so.
 
 
 %% This notice is provided with respect to PC/SC Lite for Suse Linux v. 1.1.1, which may be included with this software: 
--- a/jdk/make/com/sun/jmx/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/com/sun/jmx/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -41,7 +41,15 @@
 # Note : some targets are double colon rules and some single colon rules
 # within common included gmk files : that is why the following for loop
 # has been duplicated.
-SUBDIRS = snmp
+
+# When building the openjdk, build snmp only if importing binary plugs,
+ifdef OPENJDK
+  ifeq ($(IMPORT_BINARY_PLUGS),true)
+    SUBDIRS = snmp
+  endif
+else
+  SUBDIRS = snmp
+endif
 
 all build:
 	$(SUBDIRS-loop)
--- a/jdk/make/common/Defs-linux.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/Defs-linux.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -94,6 +94,9 @@
     OPTIMIZATION_LEVEL = LOWER
   endif
 endif
+ifndef FASTDEBUG_OPTIMIZATION_LEVEL
+  FASTDEBUG_OPTIMIZATION_LEVEL = LOWER
+endif
 
 CC_OPT/NONE     = 
 CC_OPT/LOWER    = -O2
@@ -116,6 +119,14 @@
 CFLAGS_REQUIRED         =  $(CFLAGS_REQUIRED_$(ARCH))
 LDFLAGS_COMMON          += $(LDFLAGS_COMMON_$(ARCH))
 
+# If this is a --hash-style=gnu system, use --hash-style=both
+#   The gnu .hash section won't work on some Linux systems like SuSE 10.
+_HAS_HASH_STYLE_GNU:=$(shell $(CC) -dumpspecs | $(GREP) -- '--hash-style=gnu')
+ifneq ($(_HAS_HASH_STYLE_GNU),)
+  LDFLAGS_HASH_STYLE = -Wl,--hash-style=both
+endif
+LDFLAGS_COMMON          += $(LDFLAGS_HASH_STYLE)
+
 #
 # Selection of warning messages
 #
@@ -165,8 +176,8 @@
 
 # FASTDEBUG: Optimize the code in the -g versions, gives us a faster debug java
 ifeq ($(FASTDEBUG), true)
-  CFLAGS_DBG    += $(CC_OPT/LOWER)
-  CXXFLAGS_DBG	+= $(CC_OPT/LOWER)
+  CFLAGS_DBG    += $(CC_OPT/$(FASTDEBUG_OPTIMIZATION_LEVEL))
+  CXXFLAGS_DBG	+= $(CC_OPT/$(FASTDEBUG_OPTIMIZATION_LEVEL))
 endif
 
 CPPFLAGS_COMMON = -D$(ARCH) -DARCH='"$(ARCH)"' -DLINUX $(VERSION_DEFINES) \
--- a/jdk/make/common/Defs-solaris.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/Defs-solaris.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -93,6 +93,9 @@
     OPTIMIZATION_LEVEL = LOWER
   endif
 endif
+ifndef FASTDEBUG_OPTIMIZATION_LEVEL
+  FASTDEBUG_OPTIMIZATION_LEVEL = LOWER
+endif
 
 #
 # If -Xa is in CFLAGS_COMMON it will end up ahead of $(CC_OPT) for the
@@ -143,8 +146,8 @@
 #        Performance/size of files should be about the same, maybe smaller.
 #
 ifeq ($(FASTDEBUG), true)
-  CFLAGS_DEBUG_OPTION    = -g  $(CC_OPT/LOWER)
-  CXXFLAGS_DEBUG_OPTION  = -g0 $(CXX_OPT/LOWER)
+  CFLAGS_DEBUG_OPTION    = -g  $(CC_OPT/$(FASTDEBUG_OPTIMIZATION_LEVEL))
+  CXXFLAGS_DEBUG_OPTION  = -g0 $(CXX_OPT/$(FASTDEBUG_OPTIMIZATION_LEVEL))
 endif
 
 CFLAGS_COMMON   = -L$(OBJDIR)
--- a/jdk/make/common/Defs-windows.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/Defs-windows.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -70,7 +70,6 @@
 #     not to be REBASEd, see deploy/make/common/Release.gmk.
 #     msvcrt.dll, msvcrnn.dll [msvcr71 or msvcr80 or msvcr90] : Microsoft runtimes
 MS_RUNTIME_LIBRARIES = msvcrt.dll
-MSVCRNN_DLL =
 ifeq ($(ARCH_DATA_MODEL), 32)
   ifeq ($(COMPILER_VERSION), VS2003)
     MSVCRNN_DLL = msvcr71.dll
@@ -89,6 +88,13 @@
   endif
 endif
 
+ifeq ($(ARCH_DATA_MODEL), 64)
+  ifeq ($(COMPILER_VERSION), VS2008)
+    MSVCRNN_DLL = msvcr90.dll
+    MSVCPNN_DLL = msvcp90.dll
+    MS_RUNTIME_LIBRARIES += $(MSVCRNN_DLL)
+  endif
+endif
 
 EXTRA_LFLAGS += /LIBPATH:$(DXSDK_LIB_PATH)
 
@@ -105,6 +111,9 @@
     OPTIMIZATION_LEVEL = LOWER
   endif
 endif
+ifndef FASTDEBUG_OPTIMIZATION_LEVEL
+  FASTDEBUG_OPTIMIZATION_LEVEL = LOWER
+endif
 
 ifeq ($(CC_VERSION),msvc)
   # Visual Studio .NET 2003 or VS2003 compiler option definitions:
@@ -345,16 +354,11 @@
 CFLAGS_COMMON += $(COMPILER_WARNINGS_TO_IGNORE:%=-wd%)
 
 #
-# Add warnings and extra on 64bit issues
-#
-ifeq ($(ARCH_DATA_MODEL), 64)
-  CFLAGS_COMMON += -Wp64 
-endif
-
-#
 # Treat compiler warnings as errors, if requested
 #
 CFLAGS_COMMON += -W$(COMPILER_WARNING_LEVEL)
+# Turn off security warnings about using the standard C library function strcpy
+CFLAGS_COMMON += -D _CRT_SECURE_NO_DEPRECATE
 ifeq ($(COMPILER_WARNINGS_FATAL),true)
   CFLAGS_COMMON += -WX
 endif
--- a/jdk/make/common/Defs.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/Defs.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -145,6 +145,11 @@
 #     2. ALT_BINARY_PLUGS_PATH overrides all locations of classes and libraries
 #     3. ALT_BUILD_BINARY_PLUGS_PATH is used to find a ALT_BINARY_PLUGS_PATH
 #     4. ALT_CLOSED_JDK_IMPORT_PATH is used to locate classes and libraries
+#   Note: If any of the ALT_ variables are modified here, it is assumed
+#         that the build should be done with IMPORT_BINARY_PLUGS=true as
+#         well.  Otherwise the default will be IMPORT_BINARY_PLUGS=false.
+#         Lastly, setting IMPORT_BINARY_PLUGS=false on the command line
+#         will override this logic, and plugs will not be imported.
 #
 
 # Always needed, defines the name of the imported/exported jarfile
@@ -155,9 +160,11 @@
     CLOSED_JDK_IMPORT_PATH = $(ALT_CLOSED_JDK_IMPORT_PATH)
     BINARY_PLUGS_PATH = $(CLOSED_JDK_IMPORT_PATH)
     BINARY_PLUGS_JARFILE = $(CLOSED_JDK_IMPORT_PATH)/jre/lib/rt.jar
+    IMPORT_BINARY_PLUGS=true
   endif
   ifdef ALT_BUILD_BINARY_PLUGS_PATH
     BUILD_BINARY_PLUGS_PATH = $(ALT_BUILD_BINARY_PLUGS_PATH)
+    IMPORT_BINARY_PLUGS=true
   else
     BUILD_BINARY_PLUGS_PATH = $(SLASH_JAVA)/re/jdk/$(JDK_VERSION)/promoted/latest/openjdk/binaryplugs
   endif
@@ -166,9 +173,11 @@
   ifdef ALT_BINARY_PLUGS_PATH
     BINARY_PLUGS_PATH  = $(ALT_BINARY_PLUGS_PATH)
     BINARY_PLUGS_JARFILE = $(BINARY_PLUGS_PATH)/jre/lib/$(BINARY_PLUGS_JARNAME)
+    IMPORT_BINARY_PLUGS=true
   endif
   ifdef ALT_BINARY_PLUGS_JARFILE
     BINARY_PLUGS_JARFILE = $(ALT_BINARY_PLUGS_JARFILE)
+    IMPORT_BINARY_PLUGS=true
   endif
 endif # OPENJDK
 
--- a/jdk/make/common/shared/Compiler-gcc.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Compiler-gcc.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -27,8 +27,6 @@
 # GCC Compiler settings
 #
 
-COMPILER_NAME=GCC
-
 ifeq ($(PLATFORM), windows)
 
   # Settings specific to Windows, pretty stale, hasn't been used
@@ -68,24 +66,6 @@
   else
     CXX            = $(COMPILER_PATH)g++
   endif
-  ifneq ("$(findstring sparc,$(ARCH))", "")
-    # sparc or sparcv9
-    REQUIRED_CC_VER = 4.0
-    REQUIRED_GCC_VER = 4.0.*
-  else
-    REQUIRED_CC_VER = 3.2
-    ifeq ($(ARCH_DATA_MODEL), 32)
-      REQUIRED_GCC_VER = 3.2.1*
-      REQUIRED_GCC_VER_INT = 3.2.1-7a
-    else
-      ifeq ($(ARCH), amd64)
-        REQUIRED_GCC_VER = 3.2.*
-      endif
-      ifeq ($(ARCH), ia64)
-        REQUIRED_GCC_VER = 2.9[56789].*
-      endif
-    endif
-  endif
   # Option used to create a shared library
   SHARED_LIBRARY_FLAG = -shared -mimpure-text
   SUN_COMP_VER := $(shell $(CC) --verbose 2>&1 )
@@ -98,21 +78,17 @@
   CC             = $(COMPILER_PATH)gcc
   CPP            = $(COMPILER_PATH)gcc -E
   CXX            = $(COMPILER_PATH)g++
-  REQUIRED_CC_VER = 3.2
 
   # Option used to create a shared library
   SHARED_LIBRARY_FLAG = -G
-  # But gcc is still needed no matter what on 32bit
-  ifeq ($(ARCH_DATA_MODEL), 32)
-    REQUIRED_GCC_VER = 2.95
-    GCC =$(GCC_COMPILER_PATH)gcc
-    _GCC_VER :=$(shell $(GCC) -dumpversion 2>&1 )
-    GCC_VER  :=$(call GetVersion,"$(_GCC_VER)")
-  endif
-
+  
 endif
 
 # Get gcc version
 _CC_VER :=$(shell $(CC) -dumpversion 2>&1 )
 CC_VER  :=$(call GetVersion,"$(_CC_VER)")
 
+# Name of compiler
+COMPILER_NAME = GCC$(call MajorVersion,$(CC_VER))
+COMPILER_VERSION = $(COMPILER_NAME)
+
--- a/jdk/make/common/shared/Compiler-msvc.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Compiler-msvc.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -41,8 +41,6 @@
   # Fill in unknown values
   COMPILER_NAME=Unknown MSVC Compiler
   COMPILER_VERSION=
-  REQUIRED_CC_VER=
-  REQUIRED_LINK_VER=
   
   # unset any GNU Make settings of MFLAGS and MAKEFLAGS which may mess up nmake
   NMAKE          = MFLAGS= MAKEFLAGS= $(COMPILER_PATH)nmake -nologo
@@ -56,8 +54,6 @@
     CC_MAJORVER :=$(call MajorVersion,$(CC_VER))
     ifeq ($(CC_MAJORVER), 13)
       # This should be: CC_VER=13.10.3077 LINK_VER=7.10.3077
-      REQUIRED_CC_VER = 13.10.3077
-      REQUIRED_LINK_VER = 7.10.3077
       COMPILER_NAME=Visual Studio .NET 2003 Professional C++
       COMPILER_VERSION=VS2003
       REBASE     = $(COMPILER_PATH)../../Common7/Tools/Bin/rebase
@@ -67,9 +63,6 @@
       endif
     endif
     ifeq ($(CC_MAJORVER), 14)
-      # This should be: CC_VER=14.00.50727.42 LINK_VER=8.00.50727.42
-      REQUIRED_CC_VER = 14.00.50727.42
-      REQUIRED_LINK_VER = 8.00.50727.42
       COMPILER_NAME=Visual Studio 8
       COMPILER_VERSION=VS2005
       REBASE     = $(COMPILER_PATH)../../Common8/Tools/Bin/rebase
@@ -80,9 +73,6 @@
       endif
     endif
     ifeq ($(CC_MAJORVER), 15)
-      # This should be: CC_VER=15.00.21022.08 LINK_VER=9.00.21022.08
-      REQUIRED_CC_VER = 15.00.21022.08
-      REQUIRED_LINK_VER = 9.00.21022.08
       COMPILER_NAME=Visual Studio 9
       COMPILER_VERSION=VS2008
       #rebase and midl moved out of Visual Studio into the SDK:
@@ -99,14 +89,6 @@
     CC_MAJORVER :=$(call MajorVersion,$(CC_VER))
     CC_MINORVER :=$(call MinorVersion,$(CC_VER))
     CC_MICROVER :=$(call MicroVersion,$(CC_VER))
-    ifeq ($(ARCH), ia64)
-      REQUIRED_CC_VER = 13.00.9337.7
-      REQUIRED_LINK_VER = 7.00.9337.7
-    endif
-    ifeq ($(ARCH), amd64)
-      REQUIRED_CC_VER = 14.00.40310.41
-      REQUIRED_LINK_VER = 8.00.40310.39
-    endif
     ifeq ($(CC_MAJORVER), 13)
       ifeq ($(ARCH), ia64)
         # This should be: CC_VER=13.00.9337.7 LINK_VER=7.00.9337.7
@@ -130,6 +112,12 @@
         endif
       endif
     endif
+    ifeq ($(CC_MAJORVER), 15)
+      COMPILER_NAME=Microsoft Windows SDK with Visual Studio 9 (6001.18000.367)
+      COMPILER_VERSION=VS2008
+      RC = $(MSSDK61)/Bin/X64/rc.exe
+      MT = $(MSSDK61)/Bin/X64/mt.exe
+    endif
     # This will cause problems if ALT_COMPILER_PATH is defined to ""
     # which is a directive to use the PATH.
     REBASE         = $(COMPILER_PATH)../REBASE
--- a/jdk/make/common/shared/Compiler-sun.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Compiler-sun.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -27,32 +27,20 @@
 # Sun Studio Compiler settings
 #
 
-COMPILER_NAME=Sun Studio
-
 # Sun Studio Compiler settings specific to Solaris
 ifeq ($(PLATFORM), solaris)
-  COMPILER_VERSION=SS12
-  REQUIRED_CC_VER=5.9
   CC             = $(COMPILER_PATH)cc
   CPP            = $(COMPILER_PATH)cc -E
   CXX            = $(COMPILER_PATH)CC
   LINT           = $(COMPILER_PATH)lint
   # Option used to create a shared library
   SHARED_LIBRARY_FLAG = -G
-  # But gcc is still needed no matter what on 32bit
-  ifeq ($(ARCH_DATA_MODEL), 32)
-    REQUIRED_GCC_VER = 2.95
-    GCC =$(GCC_COMPILER_PATH)gcc
-    _GCC_VER :=$(shell $(GCC) -dumpversion 2>&1 )
-    GCC_VER  :=$(call GetVersion,"$(_GCC_VER)")
-  endif
+  GCC =$(GCC_COMPILER_PATH)gcc
 endif
 
 # Sun Studio Compiler settings specific to Linux
 ifeq ($(PLATFORM), linux)
   # This has not been tested
-  COMPILER_VERSION=SS12
-  REQUIRED_CC_VER=5.9
   CC             = $(COMPILER_PATH)cc
   CPP            = $(COMPILER_PATH)cc -E
   CXX            = $(COMPILER_PATH)CC
@@ -74,6 +62,18 @@
 _CC_VER :=$(shell $(CC) -V 2>&1 | $(HEAD) -n 1)
 CC_VER  :=$(call GetVersion,"$(_CC_VER)")
 
+# Name of compilers being used
+COMPILER_VERSION-5.7  = SS10
+COMPILER_NAME-5.7     = Sun Studio 10
+COMPILER_VERSION-5.8  = SS11
+COMPILER_NAME-5.8     = Sun Studio 11
+COMPILER_VERSION-5.9  = SS12
+COMPILER_NAME-5.9     = Sun Studio 12
+COMPILER_VERSION-5.10 = SS13
+COMPILER_NAME-5.10    = Sun Studio 13
+COMPILER_VERSION      = $(COMPILER_VERSION-$(CC_VER))
+COMPILER_NAME         = $(COMPILER_NAME-$(CC_VER))
+
 # Arch specific settings (determines type of .o files and instruction set)
 #  Starting in SS12 (5.9), the arch options changed.
 #  The assembler /usr/ccs/bin/as wants older SS11 (5.8) style options.
--- a/jdk/make/common/shared/Compiler.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-#
-# Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-
-#
-# Compiler settings for all platforms and the default compiler for each.
-#
-
-# Windows uses Microsoft compilers by default
-ifeq ($(PLATFORM), windows)
-  override CC_VERSION = msvc
-endif
-
-# Solaris uses Sun Studio compilers by default
-ifeq ($(PLATFORM), solaris)
-  override CC_VERSION = sun
-endif
-
-# Linux uses GNU compilers by default
-ifeq ($(PLATFORM), linux)
-  override CC_VERSION = gcc
-endif
-
-# Get the compiler specific settings
-include $(JDK_MAKE_SHARED_DIR)/Compiler-$(CC_VERSION).gmk
-
--- a/jdk/make/common/shared/Defs-java.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Defs-java.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -59,7 +59,15 @@
     ADD_CLIENT_VM_OPTION = true
   endif
 endif
-JAVA_JVM_FLAGS =
+
+# Options for hotspot to turn off printing of options with fastdebug version
+#   and creating the hotspot.log file.
+JAVA_HOTSPOT_DISABLE_PRINT_VMOPTIONS = \
+   -XX:-PrintVMOptions -XX:+UnlockDiagnosticVMOptions -XX:-LogVMOutput
+
+# JVM options
+JAVA_JVM_FLAGS = $(JAVA_HOTSPOT_DISABLE_PRINT_VMOPTIONS)
+
 ifeq ($(ADD_CLIENT_VM_OPTION), true)
   JAVA_JVM_FLAGS += -client
 endif
@@ -129,6 +137,9 @@
 # Needed for javah
 JAVAHFLAGS += -bootclasspath $(CLASSBINDIR)
 
+# Needed for JAVADOC and BOOT_JAVACFLAGS
+NO_PROPRIETARY_API_WARNINGS = -XDignore.symbol.file=true
+
 # Langtools
 ifdef LANGTOOLS_DIST
   JAVAC_JAR   = $(LANGTOOLS_DIST)/bootstrap/lib/javac.jar
@@ -192,6 +203,8 @@
 BOOT_JAVACFLAGS  += -encoding ascii
 BOOT_JAR_JFLAGS += $(JAR_JFLAGS)
 
+BOOT_JAVACFLAGS  += $(NO_PROPRIETARY_API_WARNINGS)
+
 BOOT_JAVA_CMD      = $(BOOTDIR)/bin/java $(JAVA_TOOLS_FLAGS)
 BOOT_JAVAC_CMD     = $(BOOTDIR)/bin/javac $(JAVAC_JVM_FLAGS) $(BOOT_JAVACFLAGS)
 BOOT_JAR_CMD       = $(BOOTDIR)/bin/jar
--- a/jdk/make/common/shared/Defs-solaris.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Defs-solaris.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -91,14 +91,14 @@
 ifneq "$(origin ALT_COMPILER_PATH)" "undefined"
   COMPILER_PATH :=$(call PrefixPath,$(ALT_COMPILER_PATH))
 else
-  # Careful here, COMPILER_VERSION may not be defined yet (see Compiler.gmk)
+  # Careful here, REQUIRED_COMPILER_VERSION may not be defined yet (see Defs-versions.gmk)
   # If the place where we keep a set of Sun Studio compilers doesn't exist,
   #  try and use /opt/SUNWspro, the default location for the SS compilers.
   #  (DirExists checks for this path twice, an automount double check)
   _SUNSTUDIO_SET_ROOT=$(JDK_DEVTOOLS_DIR)/$(ARCH_FAMILY)/SUNWspro
   SUNSTUDIO_SET_ROOT:=$(call DirExists,$(_SUNSTUDIO_SET_ROOT),$(_SUNSTUDIO_SET_ROOT),)
   ifneq ($(SUNSTUDIO_SET_ROOT),)
-    COMPILER_PATH =$(SUNSTUDIO_SET_ROOT)/$(COMPILER_VERSION)/bin/
+    COMPILER_PATH =$(SUNSTUDIO_SET_ROOT)/$(REQUIRED_COMPILER_VERSION)/bin/
   else
     COMPILER_PATH =/opt/SUNWspro/bin/
   endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/common/shared/Defs-versions.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,199 @@
+#
+# Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Sun designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# WARNING: This file is shared with other workspaces.
+#
+
+# This file needs these set: CC_VERSION, PLATFORM, ARCH_FAMILY, and ARCH_DATA_MODEL.
+
+##########################################################################
+#
+# List of JDK official minimum, expected, or required versions:
+#
+# REQUIRED_ALSA_VERSION
+#   Linux only: The ALSA sound library version expected.
+#
+# REQUIRED_ANT_VER
+#   The minimum 'ant' version.
+#
+# REQUIRED_BOOT_VER
+#   The minimum boot jdk version.
+#
+# REQUIRED_CC_VER
+#   The primary C compiler version expected.
+#
+# REQUIRED_COMPILER_NAME
+#   The long descriptive name of the compiler we should use
+#
+# REQUIRED_COMPILER_VERSION
+#   The one word name that identifies the compilers being used.
+#
+# REQUIRED_CYGWIN_VER
+#   Windows only: If CYGWIN is used, the minimum CYGWIN version.
+#
+# REQUIRED_DXSDK_VER
+#   Windows only: The version of DirectX SDK expected.
+#
+# REQUIRED_FREE_SPACE
+#   The minimum disk space needed as determined by running 'du -sk' on a fully
+#   built workspace.
+#
+# REQUIRED_FREETYPE_VERSION
+#   If we are using freetype, the freetype version expected.
+#
+# REQUIRED_GCC_VER
+#   Solaris and Linux only. The required version of gcc/g++ for the plugin.
+#
+# REQUIRED_LINK_VER
+#   Windows only: The version of link.exe expected.
+#
+# REQUIRED_MAKE_VER
+#   The minimum version of GNU make.
+#
+# REQUIRED_MKS_VER
+#   Windows only: If MKS used instead of CYGWIN, the minimum version of MKS.
+#
+# REQUIRED_OS_VARIANT_NAME
+#   The OS variation name required.
+#     Solaris: Solaris or OpenSolaris
+#     Windows: Windows2000, WindowsXP, Windows2003, etc.
+#     Linux: Fedora, RedHat, SuSE, Ubuntu, etc.
+#
+# REQUIRED_OS_VARIANT_VERSION
+#   The version number associated with the above OS variant name.
+#     Solaris: output of uname -r
+#     Windows: 5.0 for Windows2000, 5.1 for WindowsXP, 5.2 for Windows2003, etc.
+#     Linux: number for the variant, e.g. 9 for Fedora 9
+#
+# REQUIRED_OS_VERSION
+#   The formal OS version number.
+#     Solaris & Windows: same as REQUIRED_OS_VARIANT_VERSION
+#     Linux: the kernel version, or output of uname -r
+#
+# REQUIRED_UNZIP_VER
+#   The minimum version of unzip.
+#
+# REQUIRED_ZIP_VER
+#   The minimum version of unzip.
+#
+###########
+#
+# Differences in the build platform from these versions may trigger warnings
+#   messages during the sanity checking when building the JDK.
+#
+# When building the OpenJDK most of these required or expected  versions are 
+#  ignored or allowed to vary widely to accomodate the many build situations
+#  of the OpenJDK.
+#
+##########################################################################
+
+# Solaris specific
+ifeq ($(PLATFORM), solaris)
+  REQUIRED_OS_VERSION         = 5.10
+  REQUIRED_OS_VARIANT_NAME    = Solaris
+  REQUIRED_OS_VARIANT_VERSION = $(REQUIRED_OS_VERSION)
+  ifeq ($(ARCH_FAMILY), sparc)
+    REQUIRED_FREE_SPACE       = 1300000
+  else
+    REQUIRED_FREE_SPACE       = 1040000
+  endif
+  REQUIRED_COMPILER_NAME      = Sun Studio 12
+  REQUIRED_COMPILER_VERSION   = SS12
+  ifeq ($(CC_VERSION),sun)
+    REQUIRED_CC_VER           = 5.9
+  endif
+  ifeq ($(CC_VERSION),gcc)
+    REQUIRED_CC_VER           = 3.4.3
+  endif
+  REQUIRED_GCC_VER            = 2.95.2
+endif
+
+# Linux specific
+ifeq ($(PLATFORM), linux)
+  REQUIRED_OS_VERSION         = 2.6
+  REQUIRED_OS_VARIANT_NAME    = Fedora
+  REQUIRED_OS_VARIANT_VERSION = 9
+  REQUIRED_FREE_SPACE         = 1460000
+  REQUIRED_ALSA_VERSION       = 0.9.1
+  REQUIRED_COMPILER_NAME      = GCC4
+  REQUIRED_COMPILER_VERSION   = GCC4
+  REQUIRED_GCC_VER            = 2.95
+  ifeq ($(CC_VERSION),gcc)
+    REQUIRED_CC_VER           = 4.3.0
+  endif
+  ifeq ($(CC_VERSION),sun)
+    REQUIRED_CC_VER           = 5.9
+  endif
+endif
+
+# Windows specific
+ifeq ($(PLATFORM), windows)
+  ifeq ($(ARCH_DATA_MODEL),64)
+    REQUIRED_OS_VERSION       = 5.2
+    REQUIRED_OS_VARIANT_NAME  = Windows2003
+  else
+    REQUIRED_OS_VERSION       = 5.1
+    REQUIRED_OS_VARIANT_NAME  = WindowsXP
+  endif
+  REQUIRED_OS_VARIANT_VERSION = $(REQUIRED_OS_VERSION)
+  REQUIRED_CYGWIN_VER         = 4.0
+  REQUIRED_MKS_VER            = 6.1
+  REQUIRED_FREE_SPACE         = 500000
+  REQUIRED_DXSDK_VER          = 0x0900
+  ifeq ($(CC_VERSION),msvc)
+    ifeq ($(ARCH_DATA_MODEL), 32)
+      REQUIRED_COMPILER_NAME    = Visual Studio 9
+      REQUIRED_COMPILER_VERSION = VS2008
+      REQUIRED_CC_VER           = 15.00.21022.08
+      REQUIRED_LINK_VER         = 9.00.21022.08
+    else
+      ifeq ($(ARCH), ia64)
+        REQUIRED_COMPILER_NAME    = Microsoft Platform SDK - November 2001 Edition
+        REQUIRED_COMPILER_VERSION = VS2003
+        REQUIRED_CC_VER           = 13.00.9337.7
+        REQUIRED_LINK_VER         = 7.00.9337.7
+      endif
+      ifeq ($(ARCH), amd64)
+        REQUIRED_COMPILER_NAME    = Microsoft Windows SDK with Visual Studio 9 (6001.18000.367)
+        REQUIRED_COMPILER_VERSION = VS2008
+        REQUIRED_CC_VER           = 15.00.21022.08
+        REQUIRED_LINK_VER         = 9.00.21022.08
+      endif
+    endif
+  endif
+  ifeq ($(CC_VERSION),gcc)
+    REQUIRED_CC_VER           = 3.4.3
+  endif
+endif
+
+# Generic
+REQUIRED_ANT_VER          = 1.6.3
+REQUIRED_BOOT_VER         = 1.5
+REQUIRED_FREETYPE_VERSION = 2.3.0
+REQUIRED_MAKE_VER         = 3.78
+REQUIRED_UNZIP_VER        = 5.12
+REQUIRED_ZIP_VER          = 2.2
+
--- a/jdk/make/common/shared/Defs-windows.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Defs-windows.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -136,10 +136,7 @@
 UNIXCOMMAND_PATH:=$(call AltCheckSpaces,UNIXCOMMAND_PATH)
 
 # Get version of MKS or CYGWIN
-ifdef USING_CYGWIN
-_CYGWIN_VER :=$(shell $(UNAME))
-CYGWIN_VER  :=$(call GetVersion,$(_CYGWIN_VER))
-else # MKS
+ifndef USING_CYGWIN
 _MKS_VER :=$(shell $(MKSINFO) 2>&1 | $(GREP) Release | $(TAIL) -1 | $(SED) -e 's@.*\(Release.*\)@\1@')
 MKS_VER  :=$(call GetVersion,$(_MKS_VER))
 # At this point, we can re-define FullPath to use DOSNAME_CMD
@@ -202,6 +199,7 @@
 endif
 ifeq ($(ARCH_DATA_MODEL), 32)
   _program_files     :=$(call FullPath,$(xPROGRAMFILES))
+  _program_files32   :=$(_program_files)
 else
   ifdef PROGRAMW6432
     xPROGRAMW6432    :="$(subst \,/,$(PROGRAMW6432))"
@@ -255,39 +253,51 @@
       _vs90tools     :=$(call FullPath,$(xVS90COMNTOOLS))
     endif
     ifneq ($(_vs90tools),)
-      _msvc_dir :=$(_vs90tools)/../../Vc
-      _redist_sdk   :=$(_msvc_dir)/../SDK/v3.5/Bin
-    endif
-    ifdef VS80COMNTOOLS  # /Common/Tools directory, use ../../Vc
-      xVS80COMNTOOLS :="$(subst \,/,$(VS80COMNTOOLS))"
-      _vs80tools     :=$(call FullPath,$(xVS80COMNTOOLS))
-    endif
-    ifneq ($(_vs80tools),)
-      _msvc_dir :=$(_vs80tools)/../../Vc
-      _redist_sdk   :=$(_msvc_dir)/../SDK/v2.0/Bin
-    endif
-    ifdef VS71COMNTOOLS  # /Common/Tools directory, use ../../Vc7
-      xVS71COMNTOOLS :="$(subst \,/,$(VS71COMNTOOLS))"
-      _vs71tools     :=$(call FullPath,$(xVS71COMNTOOLS))
-    endif
-    ifneq ($(_vs71tools),)
-      _msvc_dir :=$(_vs71tools)/../../Vc7
-      _redist_sdk    :=$(_vs71tools)/../..
+      _msvc_dir   :=$(_vs90tools)/../../Vc
+    else
+      ifdef VS80COMNTOOLS  # /Common/Tools directory, use ../../Vc
+        xVS80COMNTOOLS :="$(subst \,/,$(VS80COMNTOOLS))"
+        _vs80tools     :=$(call FullPath,$(xVS80COMNTOOLS))
+      endif
+      ifneq ($(_vs80tools),)
+        _msvc_dir   :=$(_vs80tools)/../../Vc
+      else
+        ifdef VS71COMNTOOLS  # /Common/Tools directory, use ../../Vc7
+          xVS71COMNTOOLS :="$(subst \,/,$(VS71COMNTOOLS))"
+          _vs71tools     :=$(call FullPath,$(xVS71COMNTOOLS))
+        endif
+        ifneq ($(_vs71tools),)
+          _msvc_dir   :=$(_vs71tools)/../../Vc7
+        endif
+      endif
     endif
   endif
   ifneq ($(_msvc_dir),)
     _compiler_bin :=$(_msvc_dir)/Bin
-    _ms_sdk       :=$(_msvc_dir)/PlatformSDK
+    # Assume PlatformSDK is in VS71 (will be empty if VS90)
+    _ms_sdk       :=$(call FullPath,$(_msvc_dir)/PlatformSDK)
+    # Assume VS90, then VS80, then VS71
+    _redist_sdk   :=$(call FullPath,$(_msvc_dir)/../SDK/v3.5/Bin)
+    ifeq ($(_redist_sdk),)
+      _redist_sdk   :=$(call FullPath,$(_msvc_dir)/../SDK/v2.0/Bin)
+      ifeq ($(_redist_sdk),)
+        _redist_sdk   :=$(call FullPath,$(_msvc_dir)/../SDK/v1.1/Bin)
+      endif
+    endif
   endif
 endif
 
 # The Microsoft Platform SDK installed by itself
 ifneq ($(_program_files),)
-  xPSDK  :="$(_program_files)/Microsoft Platform SDK"
-  _psdk  :=$(call FullPath,$(xPSDK))
+  _PSDK :="$(_program_files)/Microsoft SDKs/Windows/v6.1/"
+  _psdk :=$(call FullPath,$(xMSSDK61))
   ifeq ($(_psdk),)
-    xPSDK  :="$(_program_files)/Microsoft SDK"
-    _psdk :=$(call FullPath,$(xMSSDK))
+    xPSDK  :="$(_program_files)/Microsoft Platform SDK"
+    _psdk  :=$(call FullPath,$(xPSDK))
+    ifeq ($(_psdk),)
+      xPSDK  :="$(_program_files)/Microsoft SDK"
+      _psdk :=$(call FullPath,$(xMSSDK))
+    endif
   endif
 endif
 
@@ -308,13 +318,22 @@
 
 # Compilers for 64bit are from SDK
 ifeq ($(ARCH_DATA_MODEL), 64)
-  ifneq ($(_ms_sdk),)
-    ifeq ($(ARCH), ia64)
-      _compiler_bin :=$(_ms_sdk)/Bin/Win64
-    endif
-    ifeq ($(ARCH), amd64)
-      _compiler_bin :=$(_ms_sdk)/Bin/Win64/x86/$(ARCH)
-      _redist_sdk   :=$(_ms_sdk)/redist/win64/AMD64
+  xVS2008 :="$(_program_files32)/Microsoft Visual Studio 9.0/"
+  VS2008 :=$(call FullPath,$(xVS2008))
+  ifneq ($(VS2008),)
+    _compiler_bin :=$(VS2008)/VC/Bin/$(ARCH)
+    xMSSDK61      :="$(_program_files)/Microsoft SDKs/Windows/v6.1/"
+    MSSDK61       :=$(call FullPath,$(xMSSDK61))
+    _redist_sdk   :=$(VS2008)/VC/redist/x86/Microsoft.VC90.CRT
+  else
+    ifneq ($(_ms_sdk),)
+      ifeq ($(ARCH), ia64)
+        _compiler_bin :=$(_ms_sdk)/Bin/Win64
+      endif
+      ifeq ($(ARCH), amd64)
+        _compiler_bin :=$(_ms_sdk)/Bin/Win64/x86/$(ARCH)
+        _redist_sdk   :=$(_ms_sdk)/redist/win64/AMD64
+      endif
     endif
   endif
 endif
@@ -417,70 +436,39 @@
   _BOOTDIR2  =$(USRJDKINSTANCES_PATH)/jdk$(PREVIOUS_JDK_VERSION)
 endif
 
-# See if SDK area has a msvcrt.dll file, directory may exist w/o msvcr* files
-_REDIST_SDK_EXISTS := $(shell \
-	if [ -f "$(_redist_sdk)/msvcrt.dll" ]; then \
-	  echo "true"; \
-	else \
-	  echo "false"; \
-	fi)
-_REDISTNN_SDK_EXISTS := $(shell \
-	if [ -f "$(_redist_sdk)/$(MSVCRNN_DLL)" ]; then \
-	  echo "true"; \
-	else \
-	  echo "false"; \
-	fi)
+# 32 bit always needs 2 runtimes, 64 bit usually does too
 
-# 32 bit needs 2 runtimes
+# MSVCRT_DLL_PATH: location of msvcrt.dll that will be re-distributed
+ifdef ALT_MSVCRT_DLL_PATH
+  xALT_MSVCRT_DLL_PATH :="$(subst \,/,$(ALT_MSVCRT_DLL_PATH))"
+  MSVCRT_DLL_PATH      :=$(call FullPath,$(xALT_MSVCRT_DLL_PATH))
+else
+  MSVCRT_DLL_PATH :=$(call FullPath,$(_system_root)/system32/)
+endif
+MSVCRT_DLL_PATH:=$(call AltCheckSpaces,MSVCRT_DLL_PATH)
+MSVCRT_DLL_PATH:=$(call AltCheckValue,MSVCRT_DLL_PATH)
+
+# 32bit always needs the MSVCRNN runtime, 64bit does when using VS2008
 ifeq ($(ARCH_DATA_MODEL), 32)
-
-  # MSVCRT_DLL_PATH: location of msvcrt.dll that will be re-distributed
-  ifdef ALT_MSVCRT_DLL_PATH
-    xALT_MSVCRT_DLL_PATH :="$(subst \,/,$(ALT_MSVCRT_DLL_PATH))"
-    MSVCRT_DLL_PATH      :=$(call FullPath,$(xALT_MSVCRT_DLL_PATH))
+  _NEEDS_MSVCRNN = true
+else
+  ifeq ($(VS2008),)
+    _NEEDS_MSVCRNN = false
   else
-    ifeq ($(_REDIST_SDK_EXISTS), true)
-      xREDIST_DIR   :=$(_redist_sdk)
-    else
-      xREDIST_DIR   :=$(_system_root)/system32
-    endif
-    MSVCRT_DLL_PATH :=$(call FullPath,$(xREDIST_DIR))
+    _NEEDS_MSVCRNN = true
   endif
-  MSVCRT_DLL_PATH:=$(call AltCheckSpaces,MSVCRT_DLL_PATH)
-  MSVCRT_DLL_PATH:=$(call AltCheckValue,MSVCRT_DLL_PATH)
-  
+endif
+
+ifeq ($(_NEEDS_MSVCRNN), true)
   # MSVCRNN_DLL_PATH: location of msvcrnn.dll that will be re-distributed
   ifdef ALT_MSVCRNN_DLL_PATH
     xALT_MSVCRNN_DLL_PATH :="$(subst \,/,$(ALT_MSVCRNN_DLL_PATH))"
     MSVCRNN_DLL_PATH      :=$(call FullPath,$(xALT_MSVCRNN_DLL_PATH))
   else
-    ifeq ($(_REDISTNN_SDK_EXISTS), true)
-      xREDISTNN_DIR  :=$(_redist_sdk)
-    else
-      xREDISTNN_DIR  :=$(_system_root)/system32
-    endif
-    MSVCRNN_DLL_PATH :=$(call FullPath,$(xREDISTNN_DIR))
+    MSVCRNN_DLL_PATH :=$(_redist_sdk)
   endif
   MSVCRNN_DLL_PATH :=$(call AltCheckSpaces,MSVCRNN_DLL_PATH)
   MSVCRNN_DLL_PATH:=$(call AltCheckValue,MSVCRNN_DLL_PATH)
-  
-else
-
-  # MSVCRT_DLL_PATH: location of msvcrt.dll that will be re-distributed
-  ifdef ALT_MSVCRT_DLL_PATH
-    xALT_MSVCRT_DLL_PATH :="$(subst \,/,$(ALT_MSVCRT_DLL_PATH))"
-    MSVCRT_DLL_PATH      :=$(call FullPath,$(xALT_MSVCRT_DLL_PATH))
-  else
-    ifeq ($(_REDIST_SDK_EXISTS), true)
-      xREDIST_DIR   :=$(_redist_sdk)
-    else
-      xREDIST_DIR   :=$(_system_root)/SysWOW64
-    endif
-    MSVCRT_DLL_PATH  :=$(call FullPath,$(xREDIST_DIR))
-  endif
-  MSVCRT_DLL_PATH:=$(call AltCheckSpaces,MSVCRT_DLL_PATH)
-  MSVCRT_DLL_PATH:=$(call AltCheckValue,MSVCRT_DLL_PATH)
-  
 endif
 
 # DXSDK_PATH: path to Microsoft DirectX SDK Include and Lib
@@ -539,7 +527,7 @@
   xALT_INSTALL_MSIVAL2 :="$(subst \,/,$(ALT_INSTALL_MSIVAL2))"
   INSTALL_MSIVAL2      :=$(call FullPath,$(xALT_INSTALL_MSIVAL2))
 else
-  INSTALL_MSIVAL2      :=$(_program_files)/MsiVal2
+  INSTALL_MSIVAL2      :=$(_program_files32)/MsiVal2
 endif
 INSTALL_MSIVAL2:=$(call AltCheckSpaces,INSTALL_MSIVAL2)
 
--- a/jdk/make/common/shared/Defs.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Defs.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -116,9 +116,9 @@
   fi)
 endef
 
-# Given a line of text, get the major.minor version number from it
+# Given a line of text, get the version number from it
 define GetVersion
-$(shell echo $1 | sed -e 's@[^1-9]*\([1-9][0-9]*\.[0-9][0-9]*\).*@\1@' )
+$(shell echo $1 | sed -e 's@[^0-9]*\([0-9][0-9]*\.[0-9][.0-9]*\).*@\1@' )
 endef
 
 # Given a major.minor.micro version, return the major, minor, or micro number
@@ -133,26 +133,26 @@
 endef
 
 # Macro that returns missing, same, newer, or older $1=version $2=required
-#  (currently does not check the micro number)
 define CheckVersions
 $(shell \
   if [ "$1" = "" -o "$2" = "" ]; then \
     echo missing; \
+  elif [ "$1" = "$2" ]; then \
+    echo same; \
+  elif [ $(call MajorVersion,$1) -lt $(call MajorVersion,$2) ] ; then \
+    echo older; \
+  elif [ $(call MajorVersion,$1) -gt $(call MajorVersion,$2) ] ; then \
+    echo newer; \
+  elif [ $(call MinorVersion,$1) -lt $(call MinorVersion,$2) ]; then \
+    echo older; \
+  elif [ $(call MinorVersion,$1) -gt $(call MinorVersion,$2) ]; then \
+    echo newer; \
+  elif [ $(call MicroVersion,$1) -lt $(call MicroVersion,$2) ]; then \
+    echo older; \
+  elif [ $(call MicroVersion,$1) -gt $(call MicroVersion,$2) ]; then \
+    echo newer; \
   else \
-    if [ "$1" = "$2" ]; then \
-      echo same; \
-    else \
-      if [ $(call MajorVersion,$1) -lt $(call MajorVersion,$2) ] ; then \
-        echo older; \
-      else \
-	if [ $(call MajorVersion,$1) -eq $(call MajorVersion,$2) -a \
-	     $(call MinorVersion,$1) -lt $(call MinorVersion,$2) ]; then \
-          echo older; \
-        else \
-          echo newer; \
-        fi; \
-      fi; \
-    fi; \
+    echo same; \
   fi)
 endef
 
@@ -558,6 +558,24 @@
   COPYRIGHT_YEAR = $(shell $(DATE) '+%Y')
 endif
 
-# Get shared compiler settings
-include $(JDK_MAKE_SHARED_DIR)/Compiler.gmk
+# Windows uses Microsoft compilers by default
+ifeq ($(PLATFORM), windows)
+  override CC_VERSION = msvc
+endif
+
+# Solaris uses Sun Studio compilers by default
+ifeq ($(PLATFORM), solaris)
+  override CC_VERSION = sun
+endif
 
+# Linux uses GNU compilers by default
+ifeq ($(PLATFORM), linux)
+  override CC_VERSION = gcc
+endif
+
+# Get the REQUIRED versions (needs CC_VERSION set)
+include $(JDK_MAKE_SHARED_DIR)/Defs-versions.gmk
+
+# Get the compiler specific settings
+include $(JDK_MAKE_SHARED_DIR)/Compiler-$(CC_VERSION).gmk
+
--- a/jdk/make/common/shared/Platform.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Platform.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -51,9 +51,6 @@
 #     USER                        login name of user (minus blanks)
 #     PLATFORM                    windows, solaris, or linux
 #     VARIANT                     OPT or DBG, OPT is the default
-#     OS_NAME                     solaris, linux, or nt
-#     OS_VERSION                  specific version of os, 5.10, 2.4.9-e.3, etc.
-#     OS_VENDOR                   company name
 #     TEMP_DISK                   /tmp or C:/temp
 #     ARCH_DATA_MODEL             32 or 64
 #     ARCH                        sparc, sparcv9, i586, amd64, or ia64
@@ -72,29 +69,11 @@
 #     ISA_DIR                     solaris only: /sparcv9 or /amd64
 #     LIBARCH32                   solaris only: sparc or i386
 #     LIBARCH64                   solaris only: sparcv9 or amd64
-#     REQUIRED_WINDOWS_VERSION    windows only: specific version of windows 
 #     USING_CYGWIN                windows only: true or false
-#     WINDOWS_NT_VERSION_STRING   windows only: long version name
-#     REQUIRED_OS_VERSION         required OS version, e.g. 5.10, 2.4
-#     REQUIRED_FREE_SPACE         minimum disk space needed for outputdir
 #     ISHIELD_TEMP_MIN            windows only: minimum disk space in temp area
-#     REQUIRED_ZIP_VER            required version of zip
-#     REQUIRED_UNZIP_VER          required version of unzip
-#     REQUIRED_DXSDK_VER          windows only: required version of DirectX
-#     LINUX_VERSION_INFO          linux only: location of linux release file
-#     REQUIRED_LINUX_VER          linux only: required version of linux
-#     REQUIRED_LINUX_FULLVER      linux only: required full version of linux
-#     REQUIRED_ALSA_VERSION       linux only: required version of ALSA
-#     REQUIRED_FREETYPE_VERSION   openjdk only: required version of freetype 
 
 SYSTEM_UNAME := $(shell uname)
 
-# Normal boot jdk is previous release, but a hard requirement is a 1.5 boot
-REQUIRED_BOOT_VER = 1.5
-
-# If we are using freetype, this is the required version
-REQUIRED_FREETYPE_VERSION=2.3.0
-
 #
 # Prune out all known SCM (Source Code Management) directories
 # so they will not be included when copying directory trees
@@ -113,8 +92,6 @@
 # Platform settings specific to Solaris
 ifeq ($(SYSTEM_UNAME), SunOS)
   PLATFORM = solaris
-  OS_NAME = solaris
-  OS_VERSION := $(shell uname -r)
   # Solaris sparc build can be either 32-bit or 64-bit.
   #   Default to 32, but allow explicit setting to 32 or 64.
   ifndef ARCH_DATA_MODEL
@@ -166,16 +143,6 @@
   endif
   # Suffix for file bundles used in previous release
   BUNDLE_FILE_SUFFIX=.tar
-  OS_VENDOR = Sun Microsystems
-  # Required Solaris version
-  REQUIRED_OS_VERSION = 5.10
-  # Minimum disk space needed as determined by running 'du -sk' on 
-  #    a fully built workspace.
-  ifeq ($(ARCH_FAMILY), sparc)
-    REQUIRED_FREE_SPACE=1300000
-  else
-    REQUIRED_FREE_SPACE=1040000
-  endif
   # How much RAM does this machine have:
   MB_OF_MEMORY=$(shell /etc/prtconf | fgrep 'Memory size:' | expand | cut -d' ' -f3)
 endif
@@ -183,8 +150,6 @@
 # Platform settings specific to Linux
 ifeq ($(SYSTEM_UNAME), Linux)
   PLATFORM = linux
-  OS_NAME = linux
-  OS_VERSION := $(shell uname -r)
   # Arch and OS name/version
   mach := $(shell uname -m)
   archExpr = case "$(mach)" in \
@@ -242,32 +207,6 @@
 
   # Suffix for file bundles used in previous release
   BUNDLE_FILE_SUFFIX=.tar.gz
-  # Minimum disk space needed as determined by running 'du -sk' on 
-  #    a fully built workspace.
-  REQUIRED_FREE_SPACE=1460000
-  LINUX_VERSION_INFO = /etc/redhat-release
-  OS_VENDOR = Red Hat
-  ifeq ($(ARCH_DATA_MODEL), 32)
-    REQUIRED_LINUX_VER = Advanced Server
-    REQUIRED_LINUX_FULLVER = Advanced Server release 2.1AS
-    REQUIRED_OS_VERSION = 2.4.9-e.3
-  else
-    ifeq ($(ARCH), amd64)
-      LINUX_VERSION_INFO = /etc/SuSE-release
-      OS_VENDOR = SuSE Enterprise
-      REQUIRED_LINUX_VER = 8.1
-      REQUIRED_LINUX_FULLVER = $(REQUIRED_LINUX_VER) SLSE AMD64
-      REQUIRED_OS_VERSION = 2.4.19-SMP
-    else
-      REQUIRED_LINUX_VER = Advanced Server
-      REQUIRED_LINUX_FULLVER = Advanced Server release 2.1AS 64 bit
-      REQUIRED_OS_VERSION = 2.4.19-SMP
-    endif
-  endif
-  ifneq ($(ARCH), ia64)
-    # ALSA 0.9.1 and above
-    REQUIRED_ALSA_VERSION = ^((0[.]9[.][1-9])|(1[.]0[.][0-9]))[0-9]*
-  endif
   # How much RAM does this machine have:
   MB_OF_MEMORY := $(shell free -m | fgrep Mem: | awk '{print $$2;}' )
 endif
@@ -275,34 +214,34 @@
 # Windows with and without CYGWIN will be slightly different
 ifeq ($(SYSTEM_UNAME), Windows_NT)
   PLATFORM = windows
-  OS_VERSION := $(shell uname -r)
-  WINDOWS_NT_VERSION_STRING=Windows_NT
-  REQUIRED_MKS_VER=6.1
 endif
 ifneq (,$(findstring CYGWIN,$(SYSTEM_UNAME)))
   PLATFORM = windows
-  OS_VERSION := 5
   USING_CYGWIN = true
   export USING_CYGWIN
-  WINDOWS_NT_VERSION_STRING=CYGWIN_NT
-  REQUIRED_CYGWIN_VER=4.0
 endif
 
 # Platform settings specific to Windows
 ifeq ($(PLATFORM), windows)
-  OS_NAME = nt
-  REQUIRED_OS_VERSION=5
   # Windows builds default to the appropriate for the underlaying
   # architecture.
   # Temporary disk area
   TEMP_DISK=C:/temp
   # GNU Make or MKS overrides $(PROCESSOR_ARCHITECTURE) to always
   # return "x86". Use the first word of $(PROCESSOR_IDENTIFIER) instead.
+  PROC_ARCH:=$(word 1, $(PROCESSOR_IDENTIFIER))
+  PROC_ARCH:=$(subst x86,X86,$(PROC_ARCH))
+  PROC_ARCH:=$(subst Intel64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst em64t,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst EM64T,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst amd64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst AMD64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst ia64,IA64,$(PROC_ARCH))
   ifndef ARCH_DATA_MODEL
-    ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)),ia64)
+    ifeq ($(PROC_ARCH),IA64)
       ARCH_DATA_MODEL=64
     else
-      ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)),AMD64)
+      ifeq ($(PROC_ARCH),X64)
         ARCH_DATA_MODEL=64
       else
         ARCH_DATA_MODEL=32
@@ -314,18 +253,17 @@
     # If the user wants to perform a cross compile build then they must
     # - set ARCH_DATA_MODEL=64 and either
     #      + set ARCH to ia64 or amd64, or
-    REQUIRED_WINDOWS_VERSION=Server 2003 Enterprise x64 Edition
-    ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)), AMD64)
+    ifeq ($(PROC_ARCH),X64)
       ARCH=amd64
     else
-      ARCH=ia64
+      ifeq ($(PROC_ARCH),IA64)
+        ARCH=ia64
+      endif
     endif
     LIBARCH=$(ARCH)
     # Value of Java os.arch property
     ARCHPROP=$(LIBARCH)
   else
-    REQUIRED_WINDOWS_VERSION=2000 or Unknown
-    #REQUIRED_WINDOWS_VERSION=XP Professional
     # LIBARCH is used to preserve the jre/lib/i386 directory name for 32-bit intel
     ARCH=i586
     LIBARCH=i386
@@ -364,14 +302,9 @@
   ARCH_VM_SUBDIR=jre/bin
   # Suffix for file bundles used in previous release
   BUNDLE_FILE_SUFFIX=.tar
-  # Minimum disk space needed as determined by running 'du -sk' on 
-  #    a fully built workspace.
-  REQUIRED_FREE_SPACE=500000
   # ISHIELD_TEMP_MIN is the difference of an empty C:\TEMP vs. one after a
   #     bundles build on windows.
   ISHIELD_TEMP_MIN=250000
-  REQUIRED_DXSDK_VER = 0x0900
-  OS_VENDOR = Microsoft
   # How much RAM does this machine have:
   ifeq ($(JDK_HAS_MEM_INFO),)
     ifeq ($(USING_CYGWIN),true)
@@ -410,10 +343,6 @@
   endif
 endif
 
-REQUIRED_ZIP_VER = 2.2
-REQUIRED_UNZIP_VER = 5.12
-REQUIRED_MAKE_VER = 3.78
-
 # Unix type settings (same for all unix platforms)
 ifneq ($(PLATFORM), windows)
   # Temporary disk area
--- a/jdk/make/common/shared/Sanity-Settings.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Sanity-Settings.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -97,7 +97,7 @@
 endif
 ifeq ($(PLATFORM),windows)
   ALL_SETTINGS+=$(call addAltSetting,MSVCRT_DLL_PATH)
-  ifeq ($(ARCH_DATA_MODEL), 32)
+  ifneq ($(MSVCRNN_DLL),)
     ALL_SETTINGS+=$(call addAltSetting,MSVCRNN_DLL_PATH)
   endif
   ALL_SETTINGS+=$(call addAltSetting,MSDEVTOOLS_PATH)
@@ -167,8 +167,6 @@
 ifeq ($(PLATFORM),windows)
   ALL_SETTINGS+=$(call addRequiredSetting,PROCESSOR_ARCHITECTURE)
   ALL_SETTINGS+=$(call addRequiredSetting,PROCESSOR_IDENTIFIER)
-  ALL_SETTINGS+=$(call addRequiredSetting,WINDOWS_VERSION)
-  ALL_SETTINGS+=$(call addRequiredSetting,WINDOWS_NT_VERSION_STRING)
   ifdef USING_CYGWIN
     ALL_SETTINGS+=$(call addRequiredSetting,USING_CYGWIN)
     ALL_SETTINGS+=$(call addRequiredVersionSetting,CYGWIN_VER)
@@ -179,13 +177,11 @@
   endif
 endif
 ifeq ($(PLATFORM),linux)
-  ALL_SETTINGS+=$(call addRequiredSetting,LINUX_VERSION)
-  ifneq ($(ARCH), ia64)
-    ALL_SETTINGS+=$(call addRequiredSetting,ALSA_VERSION)
-  endif
+  ALL_SETTINGS+=$(call addRequiredSetting,ALSA_VERSION)
 endif
 ALL_SETTINGS+=$(call addRequiredVersionSetting,OS_VERSION)
-ALL_SETTINGS+=$(call addRequiredSetting,OS_NAME)
+ALL_SETTINGS+=$(call addOptionalSetting,OS_VARIANT_NAME)
+ALL_SETTINGS+=$(call addOptionalSetting,OS_VARIANT_VERSION)
 ALL_SETTINGS+=$(call addRequiredSetting,TEMP_FREE_SPACE)
 ALL_SETTINGS+=$(call addRequiredSetting,FREE_SPACE)
 ALL_SETTINGS+=$(call addRequiredSetting,MB_OF_MEMORY)
@@ -249,6 +245,7 @@
   ALL_SETTINGS+=$(call addAltSetting,FREETYPE_HEADERS_PATH)
   ALL_SETTINGS+=$(call addAltSetting,FREETYPE_LIB_PATH)
   ALL_SETTINGS+=$(call addHeading,OPENJDK Import Binary Plug Settings)
+  ALL_SETTINGS+=$(call addOptionalSetting,IMPORT_BINARY_PLUGS)
   ALL_SETTINGS+=$(call addAltSetting,BINARY_PLUGS_JARFILE)
   ALL_SETTINGS+=$(call addAltSetting,BINARY_PLUGS_PATH)
   ALL_SETTINGS+=$(call addAltSetting,BUILD_BINARY_PLUGS_PATH)
--- a/jdk/make/common/shared/Sanity.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/common/shared/Sanity.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -38,60 +38,106 @@
 SANITY_FILES =  $(ERROR_FILE) $(WARNING_FILE) $(MESSAGE_FILE)
 
 # How to say "The Release Engineering people use this"
-THE_OFFICIAL_USES=The official $(PLATFORM) builds use
+THE_OFFICIAL_USES=The official builds on $(PLATFORM) use
 
 # How to say "You are using:"
 YOU_ARE_USING=You appear to be using
 
+# Error message
+define SanityError
+$(ECHO) "ERROR: $1\n" >> $(ERROR_FILE)
+endef
+
+# Warning message
+define SanityWarning
+$(ECHO) "WARNING: $1\n" >> $(WARNING_FILE)
+endef
+
+# Official version error message: name version required_version
+define OfficialErrorMessage
+$(call SanityError,\
+$(THE_OFFICIAL_USES) $1 $3. Your $1 $(if $2,undefined,$2) will not work.)
+endef
+
+# Official version warning message: name version required_version
+define OfficialWarningMessage
+$(call SanityWarning,\
+$(THE_OFFICIAL_USES) $1 $3. $(YOU_ARE_USING) $1 $2.)
+endef
+
+
 # Settings and rules to validate the JDK build environment.
 
 ifeq ($(PLATFORM), solaris)
   FREE_SPACE := $(shell $(DF) -b $(OUTPUTDIR) | $(TAIL) -1 | $(NAWK) '{print $$2;}')
   TEMP_FREE_SPACE := $(shell $(DF) -b $(TEMP_DISK) | $(TAIL) -1 | $(NAWK) '{print $$2;}')
+  # What kind of system we are using (Variations are Solaris and OpenSolaris)
+  OS_VERSION := $(shell uname -r)
+  OS_VARIANT_NAME := $(strip $(shell head -1 /etc/release | awk '{print $$1;}') )
+  OS_VARIANT_VERSION := $(OS_VERSION)
   REQ_PATCH_LIST = $(JDK_TOPDIR)/make/PatchList.solaris
   ifeq ($(ARCH_FAMILY), sparc)
     PATCH_POSITION = $$4
   else
     PATCH_POSITION = $$6
   endif
+  ifndef OPENJDK
+    _GCC_VER :=$(shell $(GCC) -dumpversion 2>&1 )
+    GCC_VER  :=$(call GetVersion,"$(_GCC_VER)")
+  endif
 endif
 
 ifeq ($(PLATFORM), linux)
   FREE_SPACE := $(shell $(DF) --sync -kP $(OUTPUTDIR) | $(TAIL) -1 | $(NAWK) '{print $$4;}')
   TEMP_FREE_SPACE := $(shell $(DF) --sync -kP $(TEMP_DISK) | $(TAIL) -1 | $(NAWK) '{print $$4;}')
-  ifeq ($(ARCH), amd64)
-    LINUX_VERSION := $(shell \
-        if [ -r "$(LINUX_VERSION_INFO)" ] ; then \
-          $(CAT) $(LINUX_VERSION_INFO) | $(TAIL) -1 | $(NAWK) '{ print $$3; }';\
-        else \
-          $(ECHO) "Unknown linux"; \
-        fi )
-  else
-    LINUX_VERSION := $(shell \
-        if [ -r "$(LINUX_VERSION_INFO)" ] ; then \
-          $(NAWK) '{ print $$4" "$$5; }' $(LINUX_VERSION_INFO) ; \
-        else \
-          $(ECHO) "Unknown linux"; \
-        fi )
-  endif
-  ifneq ($(ARCH), ia64)
-    # dummy program that outputs ALSA's version (created in target sane-alsa-versioncheck)
-    ALSA_VERSION_CHECK = $(TEMPDIR)/alsaversioncheck
-    ALSA_VERSION = `if [ -f "$(ALSA_VERSION_CHECK)" ] ; then $(ALSA_VERSION_CHECK) ; fi`
-  endif
+  # What kind of system we are using (Variation is the Linux vendor)
+  OS_VERSION := $(shell uname -r)
+  OS_VARIANT_NAME := $(shell \
+    if [ -f /etc/fedora-release ] ; then \
+      echo "Fedora"; \
+    elif [ -f /etc/redhat-release ] ; then \
+      echo "RedHat"; \
+    elif [ -f /etc/SuSE-release ] ; then \
+      echo "SuSE"; \
+    else \
+      echo "Unknown"; \
+    fi)
+  OS_VARIANT_VERSION := $(shell \
+    if [ "$(OS_VARIANT_NAME)" = "Fedora" ] ; then \
+      $(CAT) /etc/fedora-release | $(HEAD) -1 | $(NAWK) '{ print $$3; }' ; \
+    fi)
+  ALSA_INCLUDE=/usr/include/alsa/version.h
+  ALSA_LIBRARY=/usr/lib/libasound.so
+  _ALSA_VERSION := $(shell $(EGREP) SND_LIB_VERSION_STR $(ALSA_INCLUDE) | \
+           $(SED) -e 's@.*\"\(.*\)\".*@\1@' )
+  ALSA_VERSION := $(call GetVersion,$(_ALSA_VERSION))
 endif
 
 ifeq ($(PLATFORM), windows)
   FREE_SPACE := $(shell $(DF) -kP $(OUTPUTDIR) | $(TAIL) -1 | $(NAWK) '{print $$4;}')
   TEMP_FREE_SPACE := $(shell $(DF) -kP $(TEMP_DISK) | $(TAIL) -1 | $(NAWK) '{print $$4;}')
-  # Localized systeminfo has localized labels, but not localized values.
-  _WINDOWS_VERSION := \
-    $(shell systeminfo 2> $(DEV_NULL) | grep 'Microsoft' | grep 'Windows' | \
-	 cut -d':' -f2)
-  ifeq ($(_WINDOWS_VERSION),)
-    _WINDOWS_VERSION := Windows 2000 or Unknown (no systeminfo utility)
+  # Windows 2000 is 5.0, Windows XP is 5.1, Windows 2003 is 5.2
+  #    Assume 5.0 (Windows 2000) if systeminfo does not help
+  WINDOWS_MAPPING-5.0 := Windows2000
+  WINDOWS_MAPPING-5.1 := WindowsXP
+  WINDOWS_MAPPING-5.2 := Windows2003
+  # What kind of system we are using (Variation is the common name)
+  _OS_VERSION := \
+    $(shell systeminfo 2> $(DEV_NULL) | \
+            egrep '^OS Version:' | \
+            awk '{print $$3;}' )
+  ifeq ($(_OS_VERSION),)
+    OS_VERSION = 5.0
+  else
+    OS_VERSION = $(call MajorVersion,$(_OS_VERSION)).$(call MinorVersion,$(_OS_VERSION))
   endif
-  WINDOWS_VERSION := $(strip $(_WINDOWS_VERSION))
+  OS_VARIANT_NAME := $(WINDOWS_MAPPING-$(OS_VERSION))
+  OS_VARIANT_VERSION := $(OS_VERSION)
+  ifdef USING_CYGWIN
+    # CYGWIN version
+    _CYGWIN_VER := $(SYSTEM_UNAME)
+    CYGWIN_VER  :=$(call GetVersion,$(_CYGWIN_VER))
+  endif
   DXSDK_VER := $(shell $(EGREP) DIRECT3D_VERSION $(DXSDK_INCLUDE_PATH)/d3d9.h 2>&1 | \
     $(EGREP) "\#define" | $(NAWK) '{print $$3}')
 endif
@@ -106,7 +152,6 @@
 UNZIP_VER  :=$(call GetVersion,"$(_UNZIP_VER)")
 BOOT_VER   :=$(call GetVersion,"$(_BOOT_VER)")
 
-REQUIRED_ANT_VER := 1.6.3
 _ANT_VER:=$(shell $(ANT) -version 2>&1 )
 ANT_VER:=$(call GetVersion,"$(_ANT_VER)")
 
@@ -167,7 +212,6 @@
 	sane-compiler \
 	sane-link \
 	sane-cacerts \
-	sane-alsa-versioncheck \
 	sane-alsa-headers \
 	sane-ant_version \
 	sane-zip_version \
@@ -239,35 +283,29 @@
 #         generate a fatal sanity error, and a warning about the official
 #         build platform just becomes clutter.
 ######################################################
-OS_CHECK :=$(call CheckVersions,$(OS_VERSION),$(REQUIRED_OS_VERSION))
+ifndef OPENJDK
+  OS_VERSION_CHECK := \
+    $(call CheckVersions,$(OS_VERSION),$(REQUIRED_OS_VERSION))
+  ifeq ($(OS_VARIANT_NAME),$(REQUIRED_OS_VARIANT_NAME))
+    OS_VARIANT_VERSION_CHECK := \
+      $(call CheckVersions,$(OS_VARIANT_VERSION),$(REQUIRED_OS_VARIANT_VERSION))
+  endif
+endif
 sane-os_version:: sane-arch_data_model sane-memory_check sane-locale sane-os_patch_level
 ifndef OPENJDK
-	@if [ "$(OS_CHECK)" = "missing" ]; then \
-	  $(ECHO) "ERROR: The $(PLATFORM) OS version is undefined (Try: uname -r). \n" \
-	    "" >> $(ERROR_FILE) ; \
-	fi
-	@if [ "$(OS_CHECK)" != "same" ]; then \
-	  $(ECHO) "WARNING: $(THE_OFFICIAL_USES) OS version $(REQUIRED_OS_VERSION). \n" \
-	    "        $(YOU_ARE_USING) OS version $(OS_VERSION). \n" \
-	    "" >> $(WARNING_FILE) ; \
-	fi
-  ifeq ($(PLATFORM), windows)
-	@if [ "$(findstring $(REQUIRED_WINDOWS_VERSION),$(WINDOWS_VERSION))" = "" ]; then \
-	    $(ECHO) "WARNING: $(YOU_ARE_USING) an unknown version of Windows. \n" \
-	      "        The required version is $(REQUIRED_WINDOWS_VERSION). \n" \
-	      "        $(YOU_ARE_USING) $(WINDOWS_VERSION) \n" \
-	      "" >> $(WARNING_FILE) ; \
-	fi
-  endif # windows
-  ifeq ($(PLATFORM), linux)
-	@if [ `$(ECHO) "$(LINUX_VERSION)" | $(EGREP) -c '$(REQUIRED_LINUX_VER)'` -ne 1 ]; then \
-	  $(ECHO) "WARNING: The build is being done on Linux $(LINUX_VERSION). \n" \
-	    "        $(THE_OFFICIAL_USES) Linux $(REQUIRED_LINUX_VER), \n" \
-	    "        specifically Linux $(REQUIRED_LINUX_FULLVER). \n" \
-	    "        The version found was '$(OS_VERSION)'. \n" \
-	    "" >> $(WARNING_FILE) ; \
-	fi
-  endif # linux
+  ifneq ($(OS_VARIANT_NAME),$(REQUIRED_OS_VARIANT_NAME))
+    ifeq ($(OS_VERSION_CHECK),missing)
+	@$(call OfficialErrorMessage,OS version,$(OS_VERSION),$(REQUIRED_OS_VERSION))
+    endif
+    ifneq ($(OS_VERSION_CHECK),same)
+	@$(call OfficialWarningMessage,OS version,$(OS_VERSION),$(REQUIRED_OS_VERSION))
+    endif
+	@$(call OfficialWarningMessage,OS variant,$(OS_VARIANT_NAME),$(REQUIRED_OS_VARIANT_NAME))
+  else
+    ifneq ($(OS_VARIANT_VERSION_CHECK),same)
+	@$(call OfficialWarningMessage,$(OS_VARIANT_NAME) version,$(OS_VARIANT_VERSION),$(REQUIRED_OS_VARIANT_VERSION))
+    endif
+  endif
 endif # OPENJDK
 
 ifeq ($(PLATFORM), windows)
@@ -308,16 +346,12 @@
   CYGWIN_CHECK :=$(call CheckVersions,$(CYGWIN_VER),$(REQUIRED_CYGWIN_VER))
 sane-cygwin:
   ifdef USING_CYGWIN
-	@if [ "$(CYGWIN_CHECK)" = "missing" ]; then \
-	  $(ECHO) "ERROR: The CYGWIN version is undefined. \n" \
-	    "      $(THE_OFFICIAL_USES) CYGWIN $(REQUIRED_CYGWIN_VER). \n" \
-	    "" >> $(ERROR_FILE) ; \
-	fi
-	@if [ "$(CYGWIN_CHECK)" = "older" ]; then \
-	  $(ECHO) "ERROR: The build cannot be done on CYGWIN $(CYGWIN_VER). \n" \
-	    "      Use CYGWIN $(REQUIRED_CYGWIN_VER) or higher. \n" \
-	    "" >> $(ERROR_FILE) ; \
-	fi
+    ifeq ($(CYGWIN_CHECK),missing)
+	@$(call OfficialErrorMessage,CYGWIN version,$(CYGWIN_VER),$(REQUIRED_CYGWIN_VER))
+    endif
+    ifeq ($(CYGWIN_CHECK),older)
+	@$(call OfficialWarningMessage,CYGWIN version,$(CYGWIN_VER),$(REQUIRED_CYGWIN_VER))
+    endif
   endif
 endif
 
@@ -345,16 +379,12 @@
     MKS_CHECK :=$(call CheckVersions,$(MKS_VER),$(REQUIRED_MKS_VER))
 sane-mks:
   ifndef USING_CYGWIN
-	@if [ "$(MKS_CHECK)" = "missing" ]; then \
-	  $(ECHO) "ERROR: The MKS version is undefined. \n" \
-	    "      $(THE_OFFICIAL_USES) MKS $(REQUIRED_MKS_VER). \n" \
-	    "" >> $(ERROR_FILE) ; \
-	fi
-	@if [ "$(MKS_CHECK)" = "older" ]; then \
-	  $(ECHO) "ERROR: The build cannot be done on MKS $(MKS_VER). \n" \
-	    "      Use MKS $(REQUIRED_MKS_VER) or higher. \n" \
-	    "" >> $(ERROR_FILE) ; \
-	fi
+    ifeq ($(MKS_CHECK),missing)
+	@$(call OfficialErrorMessage,MKS version,$(MKS_VER),$(REQUIRED_MKS_VER))
+    endif
+    ifeq ($(MKS_CHECK),older)
+	@$(call OfficialErrorMessage,MKS version,$(MKS_VER),$(REQUIRED_MKS_VER))
+    endif
   endif
 endif
 
@@ -472,13 +502,15 @@
 ######################################################
 ifdef OPENJDK
 sane-binary-plugs:
+  ifeq ($(IMPORT_BINARY_PLUGS),true)
 	@if [ ! -d "$(BINARY_PLUGS_PATH)" ]; then \
-	  $(ECHO) "ERROR: Can't locate pre-built libraries. \n" \
+	  $(ECHO) "WARNING: Can't locate pre-built libraries. \n" \
 	    "      Please check your access to \n" \
 	    "          $(BINARY_PLUGS_PATH) \n" \
 	    "      and/or check your value of ALT_BINARY_PLUGS_PATH. \n" \
-	   "" >> $(ERROR_FILE); \
+	   "" >> $(WARNING_FILE); \
 	fi
+  endif
 endif
 
 ######################################################
@@ -834,7 +866,7 @@
 	    "      and/or check your value of ALT_MSVCRT_DLL_PATH. \n" \
 	    "" >> $(ERROR_FILE) ; \
 	fi
-  ifeq ($(ARCH_DATA_MODEL), 32)
+  ifneq ($(MSVCRNN_DLL),)
 	@if [ ! -r "$(MSVCRNN_DLL_PATH)/$(MSVCRNN_DLL)" ]; then \
 	  $(ECHO) "ERROR: You do not have access to $(MSVCRNN_DLL). \n" \
 	    "      Please check your access to \n" \
@@ -1284,8 +1316,8 @@
 	fi
 	@if [ "$(LINK_CHECK)" != "same" ]; then \
 	  $(ECHO) "WARNING: To build Java 2 SDK $(JDK_VERSION) you need : \n" \
-	    "      $(COMPILER_VERSION) - link.exe version \"$(REQUIRED_LINK_VER)\" \n" \
-	      "      Specifically the $(COMPILER_NAME) link.exe. \n " \
+	    "      $(REQUIRED_COMPILER_VERSION) - link.exe version \"$(REQUIRED_LINK_VER)\" \n" \
+	      "      Specifically the $(REQUIRED_COMPILER_NAME) link.exe. \n " \
 	    "      $(YOU_ARE_USING) Linker version \"$(LINK_VER)\" \n" \
 	    "" >> $(WARNING_FILE) ; \
 	fi
@@ -1295,11 +1327,6 @@
 # Check the compiler version(s)
 ######################################################
 CC_CHECK  :=$(call CheckVersions,$(CC_VER),$(REQUIRED_CC_VER))
-ifeq ($(PLATFORM), solaris)
-  ifeq ($(ARCH_DATA_MODEL), 32)
-    GCC_CHECK :=$(call CheckVersions,$(GCC_VER),$(REQUIRED_GCC_VER))
-  endif
-endif
 sane-compiler: sane-link
 	@if [ "$(CC_CHECK)" = "missing" ]; then \
 	  $(ECHO) "ERROR: The Compiler version is undefined. \n" \
@@ -1307,69 +1334,36 @@
 	fi
 ifndef OPENJDK
 	@if [ "$(CC_CHECK)" != "same" ]; then \
-	      $(ECHO) "WARNING: The $(PLATFORM) compiler is not version $(COMPILER_VERSION) $(REQUIRED_CC_VER) \n" \
-	      "      Specifically the $(COMPILER_NAME) compiler. \n " \
-	      "      $(YOU_ARE_USING) compiler version: $(CC_VER) \n" \
+	      $(ECHO) "WARNING: The $(PLATFORM) compiler is not version $(REQUIRED_COMPILER_VERSION) $(REQUIRED_CC_VER) \n" \
+	      "      Specifically the $(REQUIRED_COMPILER_NAME) compiler. \n " \
+	      "      $(YOU_ARE_USING) $(COMPILER_VERSION): $(CC_VER) \n" \
 	      "      The compiler was obtained from the following location: \n" \
 	      "          $(COMPILER_PATH) \n" \
 	      "" >> $(WARNING_FILE) ; \
          fi
-  ifdef GCC_CHECK
-	  @if [ "$(GCC_CHECK)" != "same" ]; then \
-	      $(ECHO) "WARNING: The $(PLATFORM) GCC compiler must be version $(REQUIRED_GCC_VER) \n" \
-	      "      $(YOU_ARE_USING) compiler version: $(GCC_VER) \n" \
-	      "      The compiler was obtained from the following location: \n" \
-	      "          $(GCC_COMPILER_PATH) \n" \
-	      "      Please change your compiler. \n" \
-	      "" >> $(WARNING_FILE) ; \
-	  fi
-  endif
-  ifeq ($(PLATFORM), windows)
-    ifeq ($(ARCH_DATA_MODEL), 64)
-      ifneq ($(COMPILER_VERSION), VS2005)
-	@$(ECHO) "WARNING: Should be using VS2005 compiler on 64bit platform. \n" \
-	    "" >> $(WARNING_FILE)
-      endif
-    endif
-  endif
 endif
 
 ######################################################
 # Check that ALSA headers and libs are installed and 
 # that the header has the right version. We only
-# need /usr/include/alsa/*.h and /usr/lib/libasound.so
+# need /usr/include/alsa/version.h and /usr/lib/libasound.so
 ######################################################
 
-ifdef ALSA_VERSION_CHECK
-$(ALSA_VERSION_CHECK): $(ALSA_VERSION_CHECK).c
-	@$(prep-target)
-	@$(CC) -lasound -o $@ $<
-
-$(ALSA_VERSION_CHECK).c:
-	@$(prep-target)
-	@$(ECHO) "#include <alsa/asoundlib.h>\n" \
-		 "#include <stdio.h>\n" \
-		 "int main(int argc, char** argv) {\n" \
-		 "  printf(\"%s\", SND_LIB_VERSION_STR);\n" \
-		 "  return 0;\n" \
-		 "}\n" \
-                    > $@
+ifdef REQUIRED_ALSA_VERSION
+  ALSA_CHECK := $(call CheckVersions,$(ALSA_VERSION),$(REQUIRED_ALSA_VERSION))
 endif
-
-sane-alsa-versioncheck: $(ALSA_VERSION_CHECK)
-sane-alsa-headers: sane-alsa-versioncheck
-ifdef ALSA_VERSION_CHECK
-	@if [ -f "$(ALSA_VERSION_CHECK)" ]; then \
-	  if [ `$(ALSA_VERSION_CHECK) | $(EGREP) -c '$(REQUIRED_ALSA_VERSION)'` -ne 1 ] ; then \
-	    $(ECHO) "ERROR: The ALSA version must be 0.9.1 or higher. \n" \
-	      "      You have the following ALSA version installed: $(ALSA_VERSION) \n" \
+sane-alsa-headers:
+ifdef REQUIRED_ALSA_VERSION
+        if [ "$(ALSA_CHECK)" != "same" -a "$(ALSA_CHECK)" != "newer"  ] ; then \
+	    $(ECHO) "ERROR: The ALSA version must be $(REQUIRED_ALSA_VERSION) or higher. \n" \
+	      "      You have the following ALSA version installed: $${alsa_version) \n" \
 	      "      Please reinstall ALSA (drivers and lib). You can download \n" \
 	      "      the source distribution from http://www.alsa-project.org \n" \
 	      "      or go to http://www.freshrpms.net/docs/alsa/ for precompiled RPM packages. \n" \
 	      "" >> $(ERROR_FILE) ; \
 	  fi \
 	else \
-	  $(ECHO) "ERROR: You seem to not have installed ALSA 0.9.1 or higher. \n" \
+	  $(ECHO) "ERROR: You seem to not have installed ALSA $(REQUIRED_ALSA_VERSION) or higher. \n" \
 	  "      Please install ALSA (drivers and lib). You can download the \n" \
 	  "      source distribution from http://www.alsa-project.org or go to \n" \
 	  "      http://www.freshrpms.net/docs/alsa/ for precompiled RPM packages. \n" \
@@ -1384,7 +1378,7 @@
 ######################################################
 # dump out the variable settings...
 ######################################################
-sane-settings:: sane-alsa-versioncheck
+sane-settings::
 	@$(ECHO)  >> $(MESSAGE_FILE)
 	@$(ECHO) $(ALL_SETTINGS)  >> $(MESSAGE_FILE)
 	@$(ECHO)  >> $(MESSAGE_FILE)
@@ -1453,8 +1447,8 @@
 ifeq ($(PLATFORM), solaris)
   ifndef OPENJDK
     @if [ -r $(GCC_COMPILER_PATH) ]; then \
-	  if [ ! "$(GCC_VER)" = 2.95.2 ]; then \
-	    $(ECHO) "ERROR: The Solaris GCC compiler version must be 2.95.2. \n" \
+	  if [ ! "$(GCC_VER)" = $(REQUIRED_GCC_VERSION) ]; then \
+	    $(ECHO) "ERROR: The Solaris GCC compiler version must be $(REQUIRED_GCC_VERSION). \n" \
 	      "      You are using the following compiler version: $(GCC_VER) \n" \
 	      "      The compiler was obtained from the following location: \n" \
 	      "          $(GCC_COMPILER_PATH) \n" \
--- a/jdk/make/docs/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/docs/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -45,6 +45,7 @@
 DOCSTMPDIR          = $(TEMPDIR)/doctmp
 
 COMMON_JAVADOCFLAGS =					\
+		$(NO_PROPRIETARY_API_WARNINGS)		\
 		-source 1.5				\
 		-quiet					\
                 -use					\
@@ -203,6 +204,9 @@
 JDI_HEADER      = "Java Debug Interface"
 # JDI_PKGS is located in NON_CORE_PKGS.gmk
 
+# Variables used by security components
+SECURITYAPI_JAVADOCBOTTOM = '<font size="-1"><a href="http://bugs.sun.com/services/bugreport/index.jsp">Report a bug or request a feature.</a><br>Copyright $(THIS_YEAR) Sun Microsystems, Inc. All Rights Reserved. Use is subject to license terms.</font>'
+
 #
 # Variables used by JAAS target
 #
@@ -220,6 +224,7 @@
                    -windowtitle $(JAAS_WINDOWTITLE)              \
                    -doctitle $(JAAS_DOCTITLE)                    \
                    -header $(JAAS_JAVADOCHEADER)                 \
+                   -bottom $(SECURITYAPI_JAVADOCBOTTOM)                      \
                    -linkoffline ../../../../../api $(DOCSDIR)/api/	 \
                    -overview $(TOPDIR)/src/share/classes/com/sun/security/auth/jaas-overview.html
 JAAS_WINDOWTITLE = "Java Authentication and Authorization Service "
@@ -242,6 +247,7 @@
                    -windowtitle $(JGSS_WINDOWTITLE)             \
                    -doctitle $(JGSS_DOCTITLE)                   \
                    -header $(JGSS_JAVADOCHEADER)                \
+                   -bottom $(SECURITYAPI_JAVADOCBOTTOM)                      \
                    -linkoffline ../../../../../api $(DOCSDIR)/api/ \
                    -overview $(JGSS_SOURCEPATH)/com/sun/security/jgss/jgss-overview.html
 
@@ -265,6 +271,7 @@
                    -windowtitle $(SMARTCARDIO_WINDOWTITLE)             \
                    -doctitle $(SMARTCARDIO_DOCTITLE)                   \
                    -header $(SMARTCARDIO_JAVADOCHEADER)                \
+                   -bottom $(SECURITYAPI_JAVADOCBOTTOM)                      \
                    -linkoffline ../../../../../api $(DOCSDIR)/api/
 
 SMARTCARDIO_WINDOWTITLE = "Java Smart Card I/O"
--- a/jdk/make/java/fdlibm/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/java/fdlibm/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -45,6 +45,7 @@
 ifeq ($(PLATFORM),windows)
   # Turn all optimizations off
   OPTIMIZATION_LEVEL = NONE
+  FASTDEBUG_OPTIMIZATION_LEVEL = NONE
   OTHER_CFLAGS =
   CPPFLAGS_DBG += -DLOGGING
 endif
@@ -56,6 +57,7 @@
 ifeq ($(PLATFORM),linux)
   # Turn all optimizations off
   OPTIMIZATION_LEVEL = NONE
+  FASTDEBUG_OPTIMIZATION_LEVEL = NONE
 endif
 
 #
--- a/jdk/make/java/java/FILES_java.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/java/java/FILES_java.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -449,7 +449,6 @@
     sun/misc/Service.java \
     sun/misc/JavaLangAccess.java \
     sun/misc/JavaIOAccess.java \
-    sun/misc/JavaIODeleteOnExitAccess.java \
     sun/misc/JavaIOFileDescriptorAccess.java \
     sun/misc/JavaNioAccess.java
 
--- a/jdk/make/java/management/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/java/management/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -46,6 +46,8 @@
 #
 include FILES_c.gmk
 
+# We don't need snmp here.
+AUTO_JAVA_PRUNE = snmp
 AUTO_FILES_JAVA_DIRS = java/lang/management com/sun/management sun/management
 
 include Exportedfiles.gmk
--- a/jdk/make/java/nio/FILES_java.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/java/nio/FILES_java.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -220,6 +220,8 @@
 	sun/nio/ch/Util.java \
 	\
 	sun/nio/cs/AbstractCharsetProvider.java \
+	sun/nio/cs/ArrayDecoder.java \
+	sun/nio/cs/ArrayEncoder.java \
 	sun/nio/cs/FastCharsetProvider.java \
 	sun/nio/cs/HistoricallyNamedCharset.java \
 	sun/nio/cs/ISO_8859_1.java \
--- a/jdk/make/java/redist/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/java/redist/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -251,9 +251,11 @@
 #
 ifdef OPENJDK
 
-include $(BUILDDIR)/common/internal/BinaryPlugs.gmk
+  ifeq ($(IMPORT_BINARY_PLUGS),true)
+    include $(BUILDDIR)/common/internal/BinaryPlugs.gmk
 
-build: import-binary-plugs
+    build: import-binary-plugs
+  endif
 
 else # !OPENJDK
 
--- a/jdk/make/javax/management/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/javax/management/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -35,6 +35,7 @@
 #
 # Files to compile
 #
+AUTO_JAVA_PRUNE = snmp
 AUTO_FILES_JAVA_DIRS = javax/management com/sun/jmx com/sun/management/jmx 
 
 #
--- a/jdk/make/javax/swing/beaninfo/SwingBeans.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/javax/swing/beaninfo/SwingBeans.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -47,7 +47,7 @@
 LOCAL_JAVADOC   = $(JAVADOC_CMD) $(JAVADOCFLAGS)
 # get the absolute path to the jar command.
 PREFIX          = 1.2
-JAVADOCFLAGS    = $(LANGUAGE_VERSION)
+JAVADOCFLAGS    = $(NO_PROPRIETARY_API_WARNINGS) $(LANGUAGE_VERSION)
 SWINGPKG        = javax/swing
 LOCAL_JAVAC_FLAGS = $(OTHER_JAVACFLAGS)
 
--- a/jdk/make/jdk_generic_profile.sh	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/jdk_generic_profile.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -174,7 +174,8 @@
    
   # Check CYGWIN (should have already been done)
   #   Assumption here is that you are in a shell window via cygwin.
-  if [ "$(echo ${PROCESSOR_IDENTIFIER} | fgrep AMD64)" != "" ] ; then
+  proc_arch=`echo "$(PROCESSOR_IDENTIFIER)" | expand | cut -d' ' -f1 | sed -e 's@x86@X86@g' -e 's@Intel64@X64@g' -e 's@em64t@X64@g' -e 's@EM64T@X64@g' -e 's@amd64@X64@g' -e 's@AMD64@X64@g' -e 's@ia64@IA64@g'`
+  if [ "${proc_arch}" = "X64" ] ; then
     windows_arch=amd64
   else
     windows_arch=i586
--- a/jdk/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,363 +0,0 @@
-#!echo "This is not a shell script"
-#############################################################################
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-#############################################################################
-#
-# JPRT shell configuration for building.
-#
-# Input environment variables:
-#    ALT_BOOTDIR
-#    ALT_SLASH_JAVA
-#    ALT_JDK_IMPORT_PATH
-#    OPENJDK
-#    Windows Only:
-#      PATH
-#      VS71COMNTOOLS
-#      PROCESSOR_IDENTIFIER
-#      ROOTDIR
-#
-# Output variable settings:
-#    make            Full path to GNU make
-#    compiler_path   Path to compiler bin directory
-#    compiler_name   Unique name of this compiler
-#
-# Output environment variables:
-#    PATH
-#    ALT_COMPILER_PATH
-#    OPENJDK only:
-#      ALT_CLOSED_JDK_IMPORT_PATH
-#      ALT_JDK_DEVTOOLS_DIR
-#    Windows Only:
-#      ALT_MSDEVTOOLS_PATH
-#      ALT_DEVTOOLS_PATH (To avoid the C:/UTILS default)
-#      LIB
-#      INCLUDE
-#
-# After JDK6, most settings will be found via ALT_SLASH_JAVA or
-#   by way of other system environment variables. If this was JDK5
-#   or an older JDK, you might need to export more ALT_* variables.
-#
-# On Windows AMD64, if MSSDK is not set, assumes Platform SDK is installed at:
-#          C:/Program Files/Microsoft Platform SDK
-#
-#############################################################################
-
-#############################################################################
-# Error
-error() # message
-{
-  echo "ERROR: $1"
-  exit 6
-}
-# Directory must exist
-dirMustExist() # dir name
-{
-  if [ ! -d "$1" ] ; then
-    error "Directory for $2 does not exist: $1"
-  fi
-}
-# File must exist
-fileMustExist() # dir name
-{
-  if [ ! -f "$1" ] ; then
-    error "File for $2 does not exist: $1"
-  fi
-}
-#############################################################################
-
-# Should be set by JPRT as the 3 basic inputs
-bootdir="${ALT_BOOTDIR}"
-slashjava="${ALT_SLASH_JAVA}"
-jdk_import="${ALT_JDK_IMPORT_PATH}"
-
-# The /java/devtools items
-jdk_devtools="${slashjava}/devtools"
-share="${jdk_devtools}/share"
-
-# Needed for langtools, maybe other parts of the build
-ANT_HOME="${share}/ant/latest"
-export ANT_HOME
-
-# The 3 bin directories in common to all platforms
-sharebin="${share}/bin"
-antbin="${ANT_HOME}/bin"
-
-# Check input
-dirMustExist "${bootdir}"         ALT_BOOTDIR
-dirMustExist "${slashjava}"       ALT_SLASH_JAVA
-dirMustExist "${jdk_import}"      ALT_JDK_IMPORT_PATH
-dirMustExist "${ANT_HOME}"        ANT_HOME
-
-# Use the JDK import for now (FIXME: use the binary plugs?)
-if [ "${OPENJDK}" = true ] ; then
-  ALT_CLOSED_JDK_IMPORT_PATH="${jdk_import}"
-  export ALT_CLOSED_JDK_IMPORT_PATH
-fi
-
-# Uses 'uname -s', but only expect SunOS or Linux, assume Windows otherwise.
-osname=`uname -s`
-if [ "${osname}" = SunOS ] ; then
-   
-    # SOLARIS: Sparc or X86
-    osarch=`uname -p`
-    if [ "${osarch}" = sparc ] ; then
-	solaris_arch=sparc
-    else
-	solaris_arch=i386
-    fi
-
-    # Get the compilers into path (make sure it matches ALT setting)
-    if [ "${JPRT_SOLARIS_COMPILER_NAME}" != "" ] ; then
-        compiler_name=${JPRT_SOLARIS_COMPILER_NAME}
-    else
-	compiler_name=SS12
-    fi
-    compiler_path=${jdk_devtools}/${solaris_arch}/SUNWspro/${compiler_name}/bin
-    ALT_COMPILER_PATH="${compiler_path}"
-    export ALT_COMPILER_PATH
-    dirMustExist "${compiler_path}" ALT_COMPILER_PATH
-    path4sdk=${compiler_path}:${sharebin}:${antbin}
-
-    # Add basic solaris system paths
-    path4sdk=${path4sdk}:/usr/ccs/bin:/usr/ccs/lib:/usr/bin:/bin:/usr/sfw/bin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Find GNU make
-    make=/usr/sfw/bin/gmake
-    if [ ! -f ${make} ] ; then
-	make=/opt/sfw/bin/gmake
-	if [ ! -f ${make} ] ; then
-	    make=${jdk_devtools}/${solaris_arch}/bin/gnumake
-        fi 
-    fi
-    fileMustExist "${make}" make
-
-    # File creation mask
-    umask 002
-
-elif [ "${osname}" = Linux ] ; then
-   
-    # LINUX: X86, AMD64
-    osarch=`uname -m`
-    if [ "${osarch}" = i686 ] ; then
-	linux_arch=i586
-    elif [ "${osarch}" = x86_64 ] ; then
-	linux_arch=amd64
-    fi
-
-    # Get the compilers into path (make sure it matches ALT setting)
-    compiler_path=/usr/bin
-    compiler_name=usr_bin
-    ALT_COMPILER_PATH="${compiler_path}"
-    export ALT_COMPILER_PATH
-    dirMustExist "${compiler_path}" ALT_COMPILER_PATH
-    path4sdk=${compiler_path}:${sharebin}:${antbin}
-    
-    # Add basic paths
-    path4sdk=${path4sdk}:/usr/bin:/bin:/usr/sbin:/sbin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-    
-    # Find GNU make
-    make=/usr/bin/make
-    fileMustExist "${make}" make
-
-    umask 002
-   
-    # Linux platform may be old, use motif files from the devtools area
-    if [ "${OPENJDK}" = true ] ; then
-      ALT_JDK_DEVTOOLS_DIR="${jdk_devtools}"
-      export ALT_JDK_DEVTOOLS_DIR
-    fi
-
-
-else
-
-    # Windows: Differs on CYGWIN vs. MKS, and the compiler available.
-    #   Also, blanks in pathnames gives GNU make headaches, so anything placed
-    #   in any ALT_* variable should be the short windows dosname.
-   
-    # WINDOWS: Install and use MKS or CYGWIN (should have already been done)
-    #   Assumption here is that you are in a shell window via MKS or cygwin.
-    #   MKS install should have defined the environment variable ROOTDIR.
-    #   We also need to figure out which one we have: X86, AMD64
-    if [ "`echo ${PROCESSOR_IDENTIFIER} | fgrep AMD64`" != "" ] ; then
-	windows_arch=amd64
-    else
-	windows_arch=i586
-    fi
-    
-    # We need to determine if we are running a CYGWIN shell or an MKS shell
-    #    (if uname isn't available, then it will be unix_toolset=unknown)
-    unix_toolset=unknown
-    if [ "`uname -a | fgrep Cygwin`" = "" -a -d "${ROOTDIR}" ] ; then
-        # We kind of assume ROOTDIR is where MKS is and it's ok
-        unix_toolset=MKS
-        mkshome=`dosname -s "${ROOTDIR}"`
-	# Utility to convert to short pathnames without spaces
-	dosname="${mkshome}/mksnt/dosname -s"
-        # Most unix utilities are in the mksnt directory of ROOTDIR
-        unixcommand_path="${mkshome}/mksnt"
-        path4sdk="${sharebin};${antbin};${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-	devtools_path="${jdk_devtools}/win32/bin"
-	path4sdk="${devtools_path};${path4sdk}"
-	# Normally this need not be set, but on Windows it's default is C:/UTILS
-        ALT_DEVTOOLS_PATH="${devtools_path}"
-	export ALT_DEVTOOLS_PATH
-        dirMustExist "${devtools_path}" ALT_DEVTOOLS_PATH
-        # Find GNU make
-        make="${devtools_path}/gnumake.exe"
-        fileMustExist "${make}" make
-    elif [ "`uname -a | fgrep Cygwin`" != "" -a -f /bin/cygpath ] ; then
-        # For CYGWIN, uname will have "Cygwin" in it, and /bin/cygpath should exist
-        unix_toolset=CYGWIN
-	# Utility to convert to short pathnames without spaces
-	dosname="/usr/bin/cygpath -a -m -s"
-        # Most unix utilities are in the /usr/bin
-        unixcommand_path="/usr/bin"
-        path4sdk="${sharebin};${antbin};${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-        # Find GNU make
-        make="${unixcommand_path}/make.exe"
-        fileMustExist "${make}" make
-    else
-      echo "WARNING: Cannot figure out if this is MKS or CYGWIN"
-    fi
-
-    # WINDOWS: Compiler setup (nasty part)
-    #   NOTE: You can use vcvars32.bat to set PATH, LIB, and INCLUDE.
-    #   NOTE: CYGWIN has a link.exe too, make sure the compilers are first
-    if [ "${windows_arch}" = i586 ] ; then
-        # 32bit Windows compiler settings
-        # VisualStudio .NET 2003 VC++ 7.1 (VS71COMNTOOLS should be defined)
-        vs_root=`${dosname} "${VS71COMNTOOLS}/../.."`
-        # Fill in PATH, LIB, and INCLUDE (unset all others to make sure)
-        msdev_root="${vs_root}/Common7/Tools"
-        msdevtools_path="${msdev_root}/bin"
-        vc7_root="${vs_root}/Vc7"
-        compiler_path="${vc7_root}/bin"
-        compiler_name=VS2003
-        platform_sdk="${vc7_root}/PlatformSDK"
-        # LIB and INCLUDE must use ; as a separator
-        include4sdk="${vc7_root}/atlmfc/include"
-        include4sdk="${include4sdk};${vc7_root}/include"
-        include4sdk="${include4sdk};${platform_sdk}/include/prerelease"
-        include4sdk="${include4sdk};${platform_sdk}/include"
-        include4sdk="${include4sdk};${vs_root}/SDK/v1.1/include"
-        lib4sdk="${vc7_root}/atlmfc/lib"
-        lib4sdk="${lib4sdk};${vc7_root}/lib"
-        lib4sdk="${lib4sdk};${platform_sdk}/lib/prerelease"
-        lib4sdk="${lib4sdk};${platform_sdk}/lib"
-        lib4sdk="${lib4sdk};${vs_root}/SDK/v1.1/lib"
-        # Search path and DLL locating path
-        #   WARNING: CYGWIN has a link.exe too, make sure compilers are first
-        path4sdk="${vs_root}/Common7/Tools/bin;${path4sdk}"
-	path4sdk="${vs_root}/SDK/v1.1/bin;${path4sdk}"
-        path4sdk="${vs_root}/Common7/Tools;${path4sdk}"
-	path4sdk="${vs_root}/Common7/Tools/bin/prerelease;${path4sdk}"
-        path4sdk="${vs_root}/Common7/IDE;${path4sdk}"
-	path4sdk="${compiler_path};${path4sdk}"
-    elif [ "${windows_arch}" = amd64 ] ; then
-        # AMD64 64bit Windows compiler settings
-	if [ "${MSSDK}" != "" ] ; then
-	    platform_sdk="${MSSDK}"
-	else
-	    platform_sdk=`${dosname} "C:/Program Files/Microsoft Platform SDK/"`
-	fi
-	compiler_path="${platform_sdk}/Bin/win64/x86/AMD64"
-        compiler_name=VS2005_PSDK
-	msdevtools_path="${platform_sdk}/Bin"
-        # LIB and INCLUDE must use ; as a separator
-        include4sdk="${platform_sdk}/Include"
-	include4sdk="${include4sdk};${platform_sdk}/Include/crt/sys"
-	include4sdk="${include4sdk};${platform_sdk}/Include/mfc"
-	include4sdk="${include4sdk};${platform_sdk}/Include/atl"
-	include4sdk="${include4sdk};${platform_sdk}/Include/crt"
-        lib4sdk="${platform_sdk}/Lib/AMD64"
-        lib4sdk="${lib4sdk};${platform_sdk}/Lib/AMD64/atlmfc"
-        # Search path and DLL locating path
-        #   WARNING: CYGWIN has a link.exe too, make sure compilers are first
-        path4sdk="${platform_sdk}/bin;${path4sdk}"
-        path4sdk="${compiler_path};${path4sdk}"
-    fi
-    # Export LIB and INCLUDE
-    unset lib
-    unset Lib
-    LIB="${lib4sdk}"
-    export LIB
-    unset include
-    unset Include
-    INCLUDE="${include4sdk}"
-    export INCLUDE
-    # Set the ALT variable
-    ALT_COMPILER_PATH=`${dosname} "${compiler_path}"`
-    export ALT_COMPILER_PATH
-    dirMustExist "${compiler_path}" ALT_COMPILER_PATH
-    ALT_MSDEVTOOLS_PATH=`${dosname} "${msdevtools_path}"`
-    export ALT_MSDEVTOOLS_PATH
-    dirMustExist "${msdevtools_path}" ALT_MSDEVTOOLS_PATH
-    
-    # WINDOWS: Get the previous JDK to be used to bootstrap the build
-    path4sdk="${bootdir}/bin;${path4sdk}"
-
-    # Turn all \\ into /, remove duplicates and trailing /
-    slash_path="`echo ${path4sdk} | sed -e 's@\\\\@/@g' -e 's@//@/@g' -e 's@/$@@' -e 's@/;@;@g'`"
-    
-    # For windows, it's hard to know where the system is, so we just add this
-    #    to PATH.
-    path4sdk="${slash_path};${PATH}"
-    
-    # Convert path4sdk to cygwin style
-    if [ "${unix_toolset}" = CYGWIN ] ; then
-	path4sdk="`/usr/bin/cygpath -p ${path4sdk}`"
-    fi
-
-    # Set special windows ALT variables
-    ALT_ISHIELDDIR="C:/ishield802"
-    export ALT_ISHIELDDIR
-
-    # Sponsors binaries
-    ALT_SPONSOR1DIR=C:/sponsor_binaries
-    export ALT_SPONSOR1DIR
-    ALT_SPONSOR2DIR=C:/sponsor_binaries 
-    export ALT_SPONSOR2DIR
-
-fi
-
-# Export PATH setting
-PATH="${path4sdk}"
-export PATH
-
-# Things we need to unset
-unset LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH_32
-unset LD_LIBRARY_PATH_64
-unset JAVA_HOME
-
--- a/jdk/make/jprt.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/jprt.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -53,6 +53,19 @@
 
 # Standard list of jprt test targets for this workspace
 jprt.test.targets=*-*-*-jvm98
+jprt.regression.test.targets=  \
+   *-*-*-java/lang,            \
+   *-*-*-java/security,        \
+   *-*-*-java/text,            \
+   *-*-*-java/util
+
+#jprt.regression.test.targets=   \
+#   *-*-*-java/awt,       \
+#   *-*-*-java/beans,     \
+#   *-*-*-java/io,        \
+#   *-*-*-java/net,       \
+#   *-*-*-java/nio,       \
+#   *-*-*-java/rmi,       \
 
 # Directories needed to build
 jprt.bundle.exclude.src.dirs=build
--- a/jdk/make/sun/awt/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/sun/awt/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -339,8 +339,7 @@
 
 FONTCONFIGS_SRC = $(PLATFORM_SRC)/classes/sun/awt/windows
 _FONTCONFIGS = \
-        fontconfig.properties \
-        fontconfig.98.properties 
+        fontconfig.properties
 
 FONTCONFIGS_SRC_PREFIX =
 
--- a/jdk/make/sun/management/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/sun/management/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -35,7 +35,16 @@
 
 all build:: properties aclfile jmxremotefiles
 
-SUBDIRS = snmp jmxremote
+# When building the openjdk, build snmp only if importing binary plugs,
+ifdef OPENJDK
+  ifeq ($(IMPORT_BINARY_PLUGS),true)
+    SUBDIRS = snmp
+  endif
+else
+  SUBDIRS = snmp
+endif
+SUBDIRS += jmxremote
+ 
 all build clean clobber::
 	$(SUBDIRS-loop)
 
--- a/jdk/make/sun/xawt/mapfile-vers	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/make/sun/xawt/mapfile-vers	Fri Apr 10 13:05:12 2009 -0700
@@ -304,12 +304,14 @@
         Java_java_awt_FileDialog_initIDs;
         Java_sun_awt_X11_XWindow_initIDs;
 
+        Java_sun_java2d_opengl_OGLContext_getOGLIdString;
         Java_sun_java2d_opengl_OGLMaskFill_maskFill;
         Java_sun_java2d_opengl_OGLRenderer_drawPoly;
         Java_sun_java2d_opengl_OGLRenderQueue_flushBuffer;
         Java_sun_java2d_opengl_OGLSurfaceData_initTexture;
         Java_sun_java2d_opengl_OGLSurfaceData_initFBObject;
         Java_sun_java2d_opengl_OGLSurfaceData_initFlipBackbuffer;
+        Java_sun_java2d_opengl_OGLSurfaceData_getTextureID;
         Java_sun_java2d_opengl_OGLSurfaceData_getTextureTarget;
         Java_sun_java2d_opengl_OGLTextRenderer_drawGlyphList;
         Java_sun_java2d_opengl_GLXGraphicsConfig_getGLXConfigInfo;
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java	Fri Apr 10 13:05:12 2009 -0700
@@ -153,7 +153,7 @@
         node.setAttribute("imageWidth", Integer.toString(imageWidth));
         node.setAttribute("imageHeight", Integer.toString(imageHeight));
         node.setAttribute("interlaceFlag",
-                          interlaceFlag ? "true" : "false");
+                          interlaceFlag ? "TRUE" : "FALSE");
         root.appendChild(node);
 
         // Local color table
@@ -185,9 +185,9 @@
         node.setAttribute("disposalMethod",
                           disposalMethodNames[disposalMethod]);
         node.setAttribute("userInputFlag",
-                          userInputFlag ? "true" : "false");
+                          userInputFlag ? "TRUE" : "FALSE");
         node.setAttribute("transparentColorFlag",
-                          transparentColorFlag ? "true" : "false");
+                          transparentColorFlag ? "TRUE" : "FALSE");
         node.setAttribute("delayTime",
                           Integer.toString(delayTime));
         node.setAttribute("transparentColorIndex",
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -55,6 +55,7 @@
 import org.w3c.dom.NodeList;
 import com.sun.imageio.plugins.common.LZWCompressor;
 import com.sun.imageio.plugins.common.PaletteBuilder;
+import sun.awt.image.ByteComponentRaster;
 
 public class GIFImageWriter extends ImageWriter {
     private static final boolean DEBUG = false; // XXX false for release!
@@ -905,10 +906,18 @@
         LZWCompressor compressor =
             new LZWCompressor(stream, initCodeSize, false);
 
+        /* At this moment we know that input image is indexed image.
+         * We can directly copy data iff:
+         *   - no subsampling required (periodX = 1, periodY = 0)
+         *   - we can access data directly (image is non-tiled,
+         *     i.e. image data are in single block)
+         *   - we can calculate offset in data buffer (next 3 lines)
+         */
         boolean isOptimizedCase =
             periodX == 1 && periodY == 1 &&
+            image.getNumXTiles() == 1 && image.getNumYTiles() == 1 &&
             sampleModel instanceof ComponentSampleModel &&
-            image.getNumXTiles() == 1 && image.getNumYTiles() == 1 &&
+            image.getTile(0, 0) instanceof ByteComponentRaster &&
             image.getTile(0, 0).getDataBuffer() instanceof DataBufferByte;
 
         int numRowsWritten = 0;
@@ -921,11 +930,14 @@
             if (DEBUG) System.out.println("Writing interlaced");
 
             if (isOptimizedCase) {
-                Raster tile = image.getTile(0, 0);
+                ByteComponentRaster tile =
+                    (ByteComponentRaster)image.getTile(0, 0);
                 byte[] data = ((DataBufferByte)tile.getDataBuffer()).getData();
                 ComponentSampleModel csm =
                     (ComponentSampleModel)tile.getSampleModel();
                 int offset = csm.getOffset(sourceXOffset, sourceYOffset, 0);
+                // take into account the raster data offset
+                offset += tile.getDataOffset(0);
                 int lineStride = csm.getScanlineStride();
 
                 writeRowsOpt(data, offset, lineStride, compressor,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFMetadata.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFMetadata.java	Fri Apr 10 13:05:12 2009 -0700
@@ -158,13 +158,10 @@
             }
         }
         String value = attr.getNodeValue();
-        // XXX Should be able to use equals() here instead of
-        // equalsIgnoreCase() but some boolean attributes are incorrectly
-        // set to "true" or "false" by the J2SE core metadata classes
-        // getAsTree() method (which are duplicated above). See bug 5082756.
-        if (value.equalsIgnoreCase("TRUE")) {
+        // Allow lower case booleans for backward compatibility, #5082756
+        if (value.equals("TRUE") || value.equals("true")) {
             return true;
-        } else if (value.equalsIgnoreCase("FALSE")) {
+        } else if (value.equals("FALSE") || value.equals("false")) {
             return false;
         } else {
             fatal(node, "Attribute " + name + " must be 'TRUE' or 'FALSE'!");
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFStreamMetadata.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFStreamMetadata.java	Fri Apr 10 13:05:12 2009 -0700
@@ -202,7 +202,7 @@
         compression_node.appendChild(node);
 
         node = new IIOMetadataNode("Lossless");
-        node.setAttribute("value", "true");
+        node.setAttribute("value", "TRUE");
         compression_node.appendChild(node);
 
         // NumProgressiveScans not in stream
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1003,7 +1003,7 @@
                                                3,
                                                new int [] {0, 1, 2},
                                                null);
-            ColorModel cm = new ComponentColorModel(JPEG.sRGB,
+            ColorModel cm = new ComponentColorModel(JPEG.JCS.sRGB,
                                                     false,
                                                     false,
                                                     ColorModel.OPAQUE,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEG.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEG.java	Fri Apr 10 13:05:12 2009 -0700
@@ -208,15 +208,24 @@
 
     public static final int [] bOffsRGB = { 2, 1, 0 };
 
-    protected static final ColorSpace sRGB =
-        ColorSpace.getInstance(ColorSpace.CS_sRGB);
-    protected static ColorSpace YCC = null;  // Can't be final
+    /* These are kept in the inner class to avoid static initialization
+     * of the CMM class until someone actually needs it.
+     * (e.g. do not init CMM on the request for jpeg mime types)
+     */
+    public static class JCS {
+        public static final ColorSpace sRGB =
+            ColorSpace.getInstance(ColorSpace.CS_sRGB);
+        public static final ColorSpace YCC;
 
-    static {
-        try {
-            YCC = ColorSpace.getInstance(ColorSpace.CS_PYCC);
-        } catch (IllegalArgumentException e) {
-            // PYCC.pf may not always be installed
+        static {
+            ColorSpace cs = null;
+            try {
+                cs = ColorSpace.getInstance(ColorSpace.CS_PYCC);
+            } catch (IllegalArgumentException e) {
+                // PYCC.pf may not always be installed
+            } finally {
+                YCC = cs;
+            }
         }
     }
 
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Fri Apr 10 13:05:12 2009 -0700
@@ -228,31 +228,31 @@
             (BufferedImage.TYPE_BYTE_GRAY);
         defaultTypes[JPEG.JCS_RGB] =
             ImageTypeSpecifier.createInterleaved
-            (JPEG.sRGB,
+            (JPEG.JCS.sRGB,
              JPEG.bOffsRGB,
              DataBuffer.TYPE_BYTE,
              false,
              false);
         defaultTypes[JPEG.JCS_RGBA] =
             ImageTypeSpecifier.createPacked
-            (JPEG.sRGB,
+            (JPEG.JCS.sRGB,
              0xff000000,
              0x00ff0000,
              0x0000ff00,
              0x000000ff,
              DataBuffer.TYPE_INT,
              false);
-        if (JPEG.YCC != null) {
+        if (JPEG.JCS.YCC != null) {
             defaultTypes[JPEG.JCS_YCC] =
                 ImageTypeSpecifier.createInterleaved
-                (JPEG.YCC,
+                (JPEG.JCS.YCC,
                  JPEG.bandOffsets[2],
                  DataBuffer.TYPE_BYTE,
                  false,
                  false);
             defaultTypes[JPEG.JCS_YCCA] =
                 ImageTypeSpecifier.createInterleaved
-                (JPEG.YCC,
+                (JPEG.JCS.YCC,
                  JPEG.bandOffsets[3],
                  DataBuffer.TYPE_BYTE,
                  true,
@@ -774,7 +774,7 @@
         case JPEG.JCS_RGB:
             list.add(raw);
             list.add(getImageType(JPEG.JCS_GRAYSCALE));
-            if (JPEG.YCC != null) {
+            if (JPEG.JCS.YCC != null) {
                 list.add(getImageType(JPEG.JCS_YCC));
             }
             break;
@@ -811,7 +811,7 @@
             }
 
             list.add(getImageType(JPEG.JCS_GRAYSCALE));
-            if (JPEG.YCC != null) { // Might be null if PYCC.pf not installed
+            if (JPEG.JCS.YCC != null) { // Might be null if PYCC.pf not installed
                 list.add(getImageType(JPEG.JCS_YCC));
             }
             break;
@@ -893,7 +893,7 @@
                        (!cs.isCS_sRGB()) &&
                        (cm.getNumComponents() == numComponents)) {
                 // Target isn't sRGB, so convert from sRGB to the target
-                convert = new ColorConvertOp(JPEG.sRGB, cs, null);
+                convert = new ColorConvertOp(JPEG.JCS.sRGB, cs, null);
             } else if (csType != ColorSpace.TYPE_RGB) {
                 throw new IIOException("Incompatible color conversion");
             }
@@ -906,18 +906,18 @@
             }
             break;
         case JPEG.JCS_YCC:
-            if (JPEG.YCC == null) { // We can't do YCC at all
+            if (JPEG.JCS.YCC == null) { // We can't do YCC at all
                 throw new IIOException("Incompatible color conversion");
             }
-            if ((cs != JPEG.YCC) &&
+            if ((cs != JPEG.JCS.YCC) &&
                 (cm.getNumComponents() == numComponents)) {
-                convert = new ColorConvertOp(JPEG.YCC, cs, null);
+                convert = new ColorConvertOp(JPEG.JCS.YCC, cs, null);
             }
             break;
         case JPEG.JCS_YCCA:
             // No conversions available; image must be YCCA
-            if ((JPEG.YCC == null) || // We can't do YCC at all
-                (cs != JPEG.YCC) ||
+            if ((JPEG.JCS.YCC == null) || // We can't do YCC at all
+                (cs != JPEG.JCS.YCC) ||
                 (cm.getNumComponents() != numComponents)) {
                 throw new IIOException("Incompatible color conversion");
             }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java	Fri Apr 10 13:05:12 2009 -0700
@@ -39,8 +39,6 @@
     private static String [] writerSpiNames =
         {"com.sun.imageio.plugins.jpeg.JPEGImageWriterSpi"};
 
-    private boolean registered = false;
-
     public JPEGImageReaderSpi() {
         super(JPEG.vendor,
               JPEG.version,
@@ -61,26 +59,6 @@
               );
     }
 
-    public void onRegistration(ServiceRegistry registry,
-                               Class<?> category) {
-        if (registered) {
-            return;
-        }
-        try {
-            java.security.AccessController.doPrivileged(
-                new sun.security.action.LoadLibraryAction("jpeg"));
-            // Stuff it all into one lib for first pass
-            //java.security.AccessController.doPrivileged(
-            //new sun.security.action.LoadLibraryAction("imageioIJG"));
-        } catch (Throwable e) { // Fail on any Throwable
-            // if it can't be loaded, deregister and return
-            registry.deregisterServiceProvider(this);
-            return;
-        }
-
-        registered = true;
-    }
-
     public String getDescription(Locale locale) {
         return "Standard JPEG Image Reader";
     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -812,13 +812,13 @@
                             }
                             break;
                         case ColorSpace.TYPE_3CLR:
-                            if (cs == JPEG.YCC) {
+                            if (cs == JPEG.JCS.YCC) {
                                 if (!alpha) {
                                     if (jfif != null) {
                                         convertTosRGB = true;
                                         convertOp =
                                         new ColorConvertOp(cs,
-                                                           JPEG.sRGB,
+                                                           JPEG.JCS.sRGB,
                                                            null);
                                         outCsType = JPEG.JCS_YCbCr;
                                     } else if (adobe != null) {
@@ -1494,7 +1494,7 @@
                 }
                 break;
             case ColorSpace.TYPE_3CLR:
-                if (cs == JPEG.YCC) {
+                if (cs == JPEG.JCS.YCC) {
                     if (alpha) {
                         retval = JPEG.JCS_YCCA;
                     } else {
@@ -1533,7 +1533,7 @@
                 }
                 break;
             case ColorSpace.TYPE_3CLR:
-                if (cs == JPEG.YCC) {
+                if (cs == JPEG.JCS.YCC) {
                     if (alpha) {
                         retval = JPEG.JCS_YCCA;
                     } else {
@@ -1579,7 +1579,7 @@
                 }
                 break;
             case ColorSpace.TYPE_3CLR:
-                if (cs == JPEG.YCC) {
+                if (cs == JPEG.JCS.YCC) {
                     if (alpha) {
                         retval = JPEG.JCS_YCCA;
                     } else {
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java	Fri Apr 10 13:05:12 2009 -0700
@@ -42,8 +42,6 @@
     private static String [] readerSpiNames =
         {"com.sun.imageio.plugins.jpeg.JPEGImageReaderSpi"};
 
-    private boolean registered = false;
-
     public JPEGImageWriterSpi() {
         super(JPEG.vendor,
               JPEG.version,
@@ -68,23 +66,6 @@
         return "Standard JPEG Image Writer";
     }
 
-    public void onRegistration(ServiceRegistry registry,
-                               Class<?> category) {
-        if (registered) {
-            return;
-        }
-        try {
-            java.security.AccessController.doPrivileged(
-                new sun.security.action.LoadLibraryAction("jpeg"));
-        } catch (Throwable e) { // Fail on any Throwable
-            // if it can't be loaded, deregister and return
-            registry.deregisterServiceProvider(this);
-            return;
-        }
-
-        registered = true;
-    }
-
     public boolean isFormatLossless() {
         return false;
     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java	Fri Apr 10 13:05:12 2009 -0700
@@ -490,7 +490,7 @@
                 }
                 break;
             case ColorSpace.TYPE_3CLR:
-                if (cs == JPEG.YCC) {
+                if (cs == JPEG.JCS.YCC) {
                     wantJFIF = false;
                     componentIDs[0] = (byte) 'Y';
                     componentIDs[1] = (byte) 'C';
@@ -955,7 +955,7 @@
 
         // Lossless - false
         IIOMetadataNode lossless = new IIOMetadataNode("Lossless");
-        lossless.setAttribute("value", "false");
+        lossless.setAttribute("value", "FALSE");
         compression.appendChild(lossless);
 
         // NumProgressiveScans - count sos segments
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java	Fri Apr 10 13:05:12 2009 -0700
@@ -37,6 +37,7 @@
 import java.io.BufferedInputStream;
 import java.io.ByteArrayInputStream;
 import java.io.DataInputStream;
+import java.io.EOFException;
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.SequenceInputStream;
@@ -59,7 +60,7 @@
 import java.io.ByteArrayOutputStream;
 import sun.awt.image.ByteInterleavedRaster;
 
-class PNGImageDataEnumeration implements Enumeration {
+class PNGImageDataEnumeration implements Enumeration<InputStream> {
 
     boolean firstTime = true;
     ImageInputStream stream;
@@ -72,7 +73,7 @@
         int type = stream.readInt(); // skip chunk type
     }
 
-    public Object nextElement() {
+    public InputStream nextElement() {
         try {
             firstTime = false;
             ImageInputStream iis = new SubImageInputStream(stream, length);
@@ -207,25 +208,17 @@
         resetStreamSettings();
     }
 
-    private String readNullTerminatedString(String charset) throws IOException {
+    private String readNullTerminatedString(String charset, int maxLen) throws IOException {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         int b;
-        while ((b = stream.read()) != 0) {
+        int count = 0;
+        while ((maxLen > count++) && ((b = stream.read()) != 0)) {
+            if (b == -1) throw new EOFException();
             baos.write(b);
         }
         return new String(baos.toByteArray(), charset);
     }
 
-    private String readNullTerminatedString() throws IOException {
-        StringBuilder b = new StringBuilder();
-        int c;
-
-        while ((c = stream.read()) != 0) {
-            b.append((char)c);
-        }
-        return b.toString();
-    }
-
     private void readHeader() throws IIOException {
         if (gotHeader) {
             return;
@@ -434,7 +427,7 @@
     }
 
     private void parse_iCCP_chunk(int chunkLength) throws IOException {
-        String keyword = readNullTerminatedString();
+        String keyword = readNullTerminatedString("ISO-8859-1", 80);
         metadata.iCCP_profileName = keyword;
 
         metadata.iCCP_compressionMethod = stream.readUnsignedByte();
@@ -450,7 +443,7 @@
     private void parse_iTXt_chunk(int chunkLength) throws IOException {
         long chunkStart = stream.getStreamPosition();
 
-        String keyword = readNullTerminatedString();
+        String keyword = readNullTerminatedString("ISO-8859-1", 80);
         metadata.iTXt_keyword.add(keyword);
 
         int compressionFlag = stream.readUnsignedByte();
@@ -459,15 +452,17 @@
         int compressionMethod = stream.readUnsignedByte();
         metadata.iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
 
-        String languageTag = readNullTerminatedString("UTF8");
+        String languageTag = readNullTerminatedString("UTF8", 80);
         metadata.iTXt_languageTag.add(languageTag);
 
+        long pos = stream.getStreamPosition();
+        int maxLen = (int)(chunkStart + chunkLength - pos);
         String translatedKeyword =
-            readNullTerminatedString("UTF8");
+            readNullTerminatedString("UTF8", maxLen);
         metadata.iTXt_translatedKeyword.add(translatedKeyword);
 
         String text;
-        long pos = stream.getStreamPosition();
+        pos = stream.getStreamPosition();
         byte[] b = new byte[(int)(chunkStart + chunkLength - pos)];
         stream.readFully(b);
 
@@ -511,7 +506,7 @@
 
     private void parse_sPLT_chunk(int chunkLength)
         throws IOException, IIOException {
-        metadata.sPLT_paletteName = readNullTerminatedString();
+        metadata.sPLT_paletteName = readNullTerminatedString("ISO-8859-1", 80);
         chunkLength -= metadata.sPLT_paletteName.length() + 1;
 
         int sampleDepth = stream.readUnsignedByte();
@@ -554,12 +549,12 @@
     }
 
     private void parse_tEXt_chunk(int chunkLength) throws IOException {
-        String keyword = readNullTerminatedString();
+        String keyword = readNullTerminatedString("ISO-8859-1", 80);
         metadata.tEXt_keyword.add(keyword);
 
         byte[] b = new byte[chunkLength - keyword.length() - 1];
         stream.readFully(b);
-        metadata.tEXt_text.add(new String(b));
+        metadata.tEXt_text.add(new String(b, "ISO-8859-1"));
     }
 
     private void parse_tIME_chunk() throws IOException {
@@ -640,7 +635,7 @@
     }
 
     private void parse_zTXt_chunk(int chunkLength) throws IOException {
-        String keyword = readNullTerminatedString();
+        String keyword = readNullTerminatedString("ISO-8859-1", 80);
         metadata.zTXt_keyword.add(keyword);
 
         int method = stream.readUnsignedByte();
@@ -648,7 +643,7 @@
 
         byte[] b = new byte[chunkLength - keyword.length() - 2];
         stream.readFully(b);
-        metadata.zTXt_text.add(new String(inflate(b)));
+        metadata.zTXt_text.add(new String(inflate(b), "ISO-8859-1"));
     }
 
     private void readMetadata() throws IIOException {
@@ -1263,7 +1258,7 @@
         try {
             stream.seek(imageStartPosition);
 
-            Enumeration e = new PNGImageDataEnumeration(stream);
+            Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
             InputStream is = new SequenceInputStream(e);
 
            /* InflaterInputStream uses an Inflater instance which consumes
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -674,13 +674,8 @@
     private byte[] deflate(byte[] b) throws IOException {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         DeflaterOutputStream dos = new DeflaterOutputStream(baos);
-
-        int len = b.length;
-        for (int i = 0; i < len; i++) {
-            dos.write((int)(0xff & b[i]));
-        }
+        dos.write(b);
         dos.close();
-
         return baos.toByteArray();
     }
 
@@ -736,7 +731,7 @@
             cs.writeByte(compressionMethod);
 
             String text = (String)textIter.next();
-            cs.write(deflate(text.getBytes()));
+            cs.write(deflate(text.getBytes("ISO-8859-1")));
             cs.finish();
         }
     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGMetadata.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGMetadata.java	Fri Apr 10 13:05:12 2009 -0700
@@ -211,8 +211,8 @@
     public int sRGB_renderingIntent;
 
     // tEXt chunk
-    public ArrayList tEXt_keyword = new ArrayList(); // 1-79 char Strings
-    public ArrayList tEXt_text = new ArrayList(); // Strings
+    public ArrayList<String> tEXt_keyword = new ArrayList<String>(); // 1-79 characters
+    public ArrayList<String> tEXt_text = new ArrayList<String>();
 
     // tIME chunk
     public boolean tIME_present;
@@ -235,13 +235,13 @@
     public int tRNS_blue;
 
     // zTXt chunk
-    public ArrayList zTXt_keyword = new ArrayList(); // Strings
-    public ArrayList zTXt_compressionMethod = new ArrayList(); // Integers
-    public ArrayList zTXt_text = new ArrayList(); // Strings
+    public ArrayList<String> zTXt_keyword = new ArrayList<String>();
+    public ArrayList<Integer> zTXt_compressionMethod = new ArrayList<Integer>();
+    public ArrayList<String> zTXt_text = new ArrayList<String>();
 
     // Unknown chunks
-    public ArrayList unknownChunkType = new ArrayList(); // Strings
-    public ArrayList unknownChunkData = new ArrayList(); // byte arrays
+    public ArrayList<String> unknownChunkType = new ArrayList<String>();
+    public ArrayList<byte[]> unknownChunkData = new ArrayList<byte[]>();
 
     public PNGMetadata() {
         super(true,
@@ -426,21 +426,14 @@
         return false;
     }
 
-    private ArrayList cloneBytesArrayList(ArrayList in) {
+    private ArrayList<byte[]> cloneBytesArrayList(ArrayList<byte[]> in) {
         if (in == null) {
             return null;
         } else {
-            ArrayList list = new ArrayList(in.size());
-            Iterator iter = in.iterator();
-            while (iter.hasNext()) {
-                Object o = iter.next();
-                if (o == null) {
-                    list.add(null);
-                } else {
-                    list.add(((byte[])o).clone());
-                }
+            ArrayList<byte[]> list = new ArrayList<byte[]>(in.size());
+            for (byte[] b: in) {
+                list.add((b == null) ? null : (byte[])b.clone());
             }
-
             return list;
         }
     }
@@ -600,7 +593,7 @@
                 IIOMetadataNode iTXt_node = new IIOMetadataNode("iTXtEntry");
                 iTXt_node.setAttribute("keyword", iTXt_keyword.get(i));
                 iTXt_node.setAttribute("compressionFlag",
-                        iTXt_compressionFlag.get(i) ? "1" : "0");
+                        iTXt_compressionFlag.get(i) ? "TRUE" : "FALSE");
                 iTXt_node.setAttribute("compressionMethod",
                         iTXt_compressionMethod.get(i).toString());
                 iTXt_node.setAttribute("languageTag",
@@ -832,7 +825,7 @@
         }
 
         node = new IIOMetadataNode("BlackIsZero");
-        node.setAttribute("value", "true");
+        node.setAttribute("value", "TRUE");
         chroma_node.appendChild(node);
 
         if (PLTE_present) {
@@ -894,7 +887,7 @@
         compression_node.appendChild(node);
 
         node = new IIOMetadataNode("Lossless");
-        node.setAttribute("value", "true");
+        node.setAttribute("value", "TRUE");
         compression_node.appendChild(node);
 
         node = new IIOMetadataNode("NumProgressiveScans");
@@ -1040,7 +1033,7 @@
             node.setAttribute("language",
                               iTXt_languageTag.get(i));
             if (iTXt_compressionFlag.get(i)) {
-                node.setAttribute("compression", "deflate");
+                node.setAttribute("compression", "zip");
             } else {
                 node.setAttribute("compression", "none");
             }
@@ -1052,7 +1045,7 @@
             node = new IIOMetadataNode("TextEntry");
             node.setAttribute("keyword", (String)zTXt_keyword.get(i));
             node.setAttribute("value", (String)zTXt_text.get(i));
-            node.setAttribute("compression", "deflate");
+            node.setAttribute("compression", "zip");
 
             text_node.appendChild(node);
         }
@@ -1162,12 +1155,13 @@
             }
         }
         String value = attr.getNodeValue();
-        if (value.equals("true")) {
+        // Allow lower case booleans for backward compatibility, #5082756
+        if (value.equals("TRUE") || value.equals("true")) {
             return true;
-        } else if (value.equals("false")) {
+        } else if (value.equals("FALSE") || value.equals("false")) {
             return false;
         } else {
-            fatal(node, "Attribute " + name + " must be 'true' or 'false'!");
+            fatal(node, "Attribute " + name + " must be 'TRUE' or 'FALSE'!");
             return false;
         }
     }
@@ -1421,26 +1415,30 @@
                     }
 
                     String keyword = getAttribute(iTXt_node, "keyword");
-                    iTXt_keyword.add(keyword);
+                    if (isValidKeyword(keyword)) {
+                        iTXt_keyword.add(keyword);
 
-                    boolean compressionFlag =
-                        getBooleanAttribute(iTXt_node, "compressionFlag");
-                    iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag));
+                        boolean compressionFlag =
+                            getBooleanAttribute(iTXt_node, "compressionFlag");
+                        iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag));
 
-                    String compressionMethod =
-                        getAttribute(iTXt_node, "compressionMethod");
-                    iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
+                        String compressionMethod =
+                            getAttribute(iTXt_node, "compressionMethod");
+                        iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
 
-                    String languageTag =
-                        getAttribute(iTXt_node, "languageTag");
-                    iTXt_languageTag.add(languageTag);
+                        String languageTag =
+                            getAttribute(iTXt_node, "languageTag");
+                        iTXt_languageTag.add(languageTag);
 
-                    String translatedKeyword =
-                        getAttribute(iTXt_node, "translatedKeyword");
-                    iTXt_translatedKeyword.add(translatedKeyword);
+                        String translatedKeyword =
+                            getAttribute(iTXt_node, "translatedKeyword");
+                        iTXt_translatedKeyword.add(translatedKeyword);
 
-                    String text = getAttribute(iTXt_node, "text");
-                    iTXt_text.add(text);
+                        String text = getAttribute(iTXt_node, "text");
+                        iTXt_text.add(text);
+
+                    }
+                    // silently skip invalid text entry
 
                     iTXt_node = iTXt_node.getNextSibling();
                 }
@@ -1692,11 +1690,45 @@
         }
     }
 
-    private boolean isISOLatin(String s) {
+    /*
+     * Accrding to PNG spec, keywords are restricted to 1 to 79 bytes
+     * in length. Keywords shall contain only printable Latin-1 characters
+     * and spaces; To reduce the chances for human misreading of a keyword,
+     * leading spaces, trailing spaces, and consecutive spaces are not
+     * permitted in keywords.
+     *
+     * See: http://www.w3.org/TR/PNG/#11keywords
+     */
+    private boolean isValidKeyword(String s) {
+        int len = s.length();
+        if (len < 1 || len >= 80) {
+            return false;
+        }
+        if (s.startsWith(" ") || s.endsWith(" ") || s.contains("  ")) {
+            return false;
+        }
+        return isISOLatin(s, false);
+    }
+
+    /*
+     * According to PNG spec, keyword shall contain only printable
+     * Latin-1 [ISO-8859-1] characters and spaces; that is, only
+     * character codes 32-126 and 161-255 decimal are allowed.
+     * For Latin-1 value fields the 0x10 (linefeed) control
+     * character is aloowed too.
+     *
+     * See: http://www.w3.org/TR/PNG/#11keywords
+     */
+    private boolean isISOLatin(String s, boolean isLineFeedAllowed) {
         int len = s.length();
         for (int i = 0; i < len; i++) {
-            if (s.charAt(i) > 255) {
-                return false;
+            char c = s.charAt(i);
+            if (c < 32 || c > 255 || (c > 126 && c < 161)) {
+                // not printable. Check whether this is an allowed
+                // control char
+                if (!isLineFeedAllowed || c != 0x10) {
+                    return false;
+                }
             }
         }
         return true;
@@ -1929,19 +1961,22 @@
                 while (child != null) {
                     String childName = child.getNodeName();
                     if (childName.equals("TextEntry")) {
-                        String keyword = getAttribute(child, "keyword");
+                        String keyword =
+                            getAttribute(child, "keyword", "", false);
                         String value = getAttribute(child, "value");
-                        String encoding = getAttribute(child, "encoding");
-                        String language = getAttribute(child, "language");
+                        String language =
+                            getAttribute(child, "language", "", false);
                         String compression =
-                            getAttribute(child, "compression");
+                            getAttribute(child, "compression", "none", false);
 
-                        if (isISOLatin(value)) {
+                        if (!isValidKeyword(keyword)) {
+                            // Just ignore this node, PNG requires keywords
+                        } else if (isISOLatin(value, true)) {
                             if (compression.equals("zip")) {
                                 // Use a zTXt node
                                 zTXt_keyword.add(keyword);
                                 zTXt_text.add(value);
-                                zTXt_compressionMethod.add(new Integer(0));
+                                zTXt_compressionMethod.add(Integer.valueOf(0));
                             } else {
                                 // Use a tEXt node
                                 tEXt_keyword.add(keyword);
@@ -1998,14 +2033,14 @@
         sBIT_present = false;
         sPLT_present = false;
         sRGB_present = false;
-        tEXt_keyword = new ArrayList();
-        tEXt_text = new ArrayList();
+        tEXt_keyword = new ArrayList<String>();
+        tEXt_text = new ArrayList<String>();
         tIME_present = false;
         tRNS_present = false;
-        zTXt_keyword = new ArrayList();
-        zTXt_compressionMethod = new ArrayList();
-        zTXt_text = new ArrayList();
-        unknownChunkType = new ArrayList();
-        unknownChunkData = new ArrayList();
+        zTXt_keyword = new ArrayList<String>();
+        zTXt_compressionMethod = new ArrayList<Integer>();
+        zTXt_text = new ArrayList<String>();
+        unknownChunkType = new ArrayList<String>();
+        unknownChunkData = new ArrayList<byte[]>();
     }
 }
--- a/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java	Fri Apr 10 13:05:12 2009 -0700
@@ -94,6 +94,10 @@
                                  tgn != null;
                                  tg = tgn, tgn = tg.getParent());
                             streamCloser = new Thread(tg, streamCloserRunnable);
+                            /* Set context class loader to null in order to avoid
+                             * keeping a strong reference to an application classloader.
+                             */
+                            streamCloser.setContextClassLoader(null);
                             Runtime.getRuntime().addShutdownHook(streamCloser);
                             return null;
                         }
--- a/jdk/src/share/classes/com/sun/servicetag/resources/register.html	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/servicetag/resources/register.html	Fri Apr 10 13:05:12 2009 -0700
@@ -68,7 +68,7 @@
           <table width="708" border="0" cellspacing="0" cellpadding="3">
             <tr valign="top">
               <td width="126" height="35">
-              <form name="form1" method="post" action="@@REGISTRATION_URL@@" enctype="text/xml">
+              <form name="form1" method="post" action="@@REGISTRATION_URL@@">
                 <input type="hidden" name="servicetag_payload" value="@@REGISTRATION_PAYLOAD@@">
                 <input type="submit" name="Submit"border="0" class="buttonblue" onmouseover="this.style.color='#fbe249';" onmouseout="this.style.color='#FFF';"  value="Register My JDK">
               </form></td>
--- a/jdk/src/share/classes/com/sun/servicetag/resources/register_ja.html	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/servicetag/resources/register_ja.html	Fri Apr 10 13:05:12 2009 -0700
@@ -62,7 +62,7 @@
           <p class="style1">å¿…è¦ã«ãªã‚‹ã®ã¯ã€Sun 開発者å‘ã‘ãƒãƒƒãƒˆãƒ¯ãƒ¼ã‚¯ã‚¢ã‚«ã‚¦ãƒ³ãƒˆã¾ãŸã¯ãã®ä»–ã® Sun オンラインアカウントã ã‘ã§ã™ã€‚ ã¾ã ã‚¢ã‚«ã‚¦ãƒ³ãƒˆãŒãªã„å ´åˆã¯ã€ã‚¢ã‚«ã‚¦ãƒ³ãƒˆã®ä½œæˆãŒæ±‚ã‚られã¾ã™ã€‚ </p>
           <table width="708" border="0" cellspacing="0" cellpadding="3">
             <tr valign="top">
-              <td width="126" height="35"><form name="form1" method="post" action="@@REGISTRATION_URL@@" enctype="text/xml">
+              <td width="126" height="35"><form name="form1" method="post" action="@@REGISTRATION_URL@@">
 			  <input type="hidden" name="servicetag_payload" value="@@REGISTRATION_PAYLOAD@@">
                 <input type="submit" name="Submit"border="0" class="buttonblue" onmouseover="this.style.color='#fbe249';" onmouseout="this.style.color='#FFF';"  value="JDK 製å“登録">
               </form></td>
--- a/jdk/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html	Fri Apr 10 13:05:12 2009 -0700
@@ -63,7 +63,7 @@
 <p class="style1">您需è¦å…·æœ‰ Sun å¼€å‘者网络或其他 Sun è”机å¸æˆ·ã€‚如果您没有,系统将æ示您创建一个。 </p>
           <table width="708" border="0" cellspacing="0" cellpadding="3">
             <tr valign="top">
-              <td width="126" height="35"><form name="form1" method="post" action="@@REGISTRATION_URL@@" enctype="text/xml">
+              <td width="126" height="35"><form name="form1" method="post" action="@@REGISTRATION_URL@@">
 			  <input type="hidden" name="servicetag_payload" value="@@REGISTRATION_PAYLOAD@@">
 <input type="submit" name="Submit"border="0" class="buttonblue" onmouseover="this.style.color='#fbe249';" onmouseout="this.style.color='#FFF';"  value="注册我的 JDK">
               </form></td>
--- a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java	Fri Apr 10 13:05:12 2009 -0700
@@ -356,6 +356,9 @@
      * @since 1.5
      */
     public void preferLocaleFonts() {
+        if (!(this instanceof SunGraphicsEnvironment)) {
+            return;
+        }
         sun.font.FontManager.preferLocaleFonts();
     }
 
@@ -376,6 +379,9 @@
      * @since 1.5
      */
     public void preferProportionalFonts() {
+        if (!(this instanceof SunGraphicsEnvironment)) {
+            return;
+        }
         sun.font.FontManager.preferProportionalFonts();
     }
 
--- a/jdk/src/share/classes/java/awt/color/ICC_Profile.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/awt/color/ICC_Profile.java	Fri Apr 10 13:05:12 2009 -0700
@@ -737,7 +737,7 @@
     ICC_Profile(ProfileDeferralInfo pdi) {
         this.deferralInfo = pdi;
         this.profileActivator = new ProfileActivator() {
-            public void activate() {
+            public void activate() throws ProfileDataException {
                 activateDeferredProfile();
             }
         };
@@ -830,20 +830,16 @@
         case ColorSpace.CS_sRGB:
             synchronized(ICC_Profile.class) {
                 if (sRGBprofile == null) {
-                    try {
-                        /*
-                         * Deferral is only used for standard profiles.
-                         * Enabling the appropriate access privileges is handled
-                         * at a lower level.
-                         */
-                        sRGBprofile = getDeferredInstance(
-                            new ProfileDeferralInfo("sRGB.pf",
-                                                    ColorSpace.TYPE_RGB,
-                                                    3, CLASS_DISPLAY));
-                    } catch (IOException e) {
-                        throw new IllegalArgumentException(
-                              "Can't load standard profile: sRGB.pf");
-                    }
+                    /*
+                     * Deferral is only used for standard profiles.
+                     * Enabling the appropriate access privileges is handled
+                     * at a lower level.
+                     */
+                    ProfileDeferralInfo pInfo =
+                        new ProfileDeferralInfo("sRGB.pf",
+                                                ColorSpace.TYPE_RGB, 3,
+                                                CLASS_DISPLAY);
+                    sRGBprofile = getDeferredInstance(pInfo);
                 }
                 thisProfile = sRGBprofile;
             }
@@ -853,7 +849,11 @@
         case ColorSpace.CS_CIEXYZ:
             synchronized(ICC_Profile.class) {
                 if (XYZprofile == null) {
-                    XYZprofile = getStandardProfile("CIEXYZ.pf");
+                    ProfileDeferralInfo pInfo =
+                        new ProfileDeferralInfo("CIEXYZ.pf",
+                                                ColorSpace.TYPE_XYZ, 3,
+                                                CLASS_DISPLAY);
+                    XYZprofile = getDeferredInstance(pInfo);
                 }
                 thisProfile = XYZprofile;
             }
@@ -863,7 +863,11 @@
         case ColorSpace.CS_PYCC:
             synchronized(ICC_Profile.class) {
                 if (PYCCprofile == null) {
-                    PYCCprofile = getStandardProfile("PYCC.pf");
+                    ProfileDeferralInfo pInfo =
+                        new ProfileDeferralInfo("PYCC.pf",
+                                                ColorSpace.TYPE_3CLR, 3,
+                                                CLASS_DISPLAY);
+                    PYCCprofile = getDeferredInstance(pInfo);
                 }
                 thisProfile = PYCCprofile;
             }
@@ -873,7 +877,11 @@
         case ColorSpace.CS_GRAY:
             synchronized(ICC_Profile.class) {
                 if (GRAYprofile == null) {
-                    GRAYprofile = getStandardProfile("GRAY.pf");
+                    ProfileDeferralInfo pInfo =
+                        new ProfileDeferralInfo("GRAY.pf",
+                                                ColorSpace.TYPE_GRAY, 1,
+                                                CLASS_DISPLAY);
+                    GRAYprofile = getDeferredInstance(pInfo);
                 }
                 thisProfile = GRAYprofile;
             }
@@ -883,7 +891,11 @@
         case ColorSpace.CS_LINEAR_RGB:
             synchronized(ICC_Profile.class) {
                 if (LINEAR_RGBprofile == null) {
-                    LINEAR_RGBprofile = getStandardProfile("LINEAR_RGB.pf");
+                    ProfileDeferralInfo pInfo =
+                        new ProfileDeferralInfo("LINEAR_RGB.pf",
+                                                ColorSpace.TYPE_RGB, 3,
+                                                CLASS_DISPLAY);
+                    LINEAR_RGBprofile = getDeferredInstance(pInfo);
                 }
                 thisProfile = LINEAR_RGBprofile;
             }
@@ -1047,9 +1059,7 @@
      * code will take care of access privileges.
      * @see activateDeferredProfile()
      */
-    static ICC_Profile getDeferredInstance(ProfileDeferralInfo pdi)
-        throws IOException {
-
+    static ICC_Profile getDeferredInstance(ProfileDeferralInfo pdi) {
         if (!ProfileDeferralMgr.deferring) {
             return getStandardProfile(pdi.filename);
         }
@@ -1063,33 +1073,37 @@
     }
 
 
-    void activateDeferredProfile() {
-    byte profileData[];
-    FileInputStream fis;
-    String fileName = deferralInfo.filename;
+    void activateDeferredProfile() throws ProfileDataException {
+        byte profileData[];
+        FileInputStream fis;
+        String fileName = deferralInfo.filename;
 
         profileActivator = null;
         deferralInfo = null;
         if ((fis = openProfile(fileName)) == null) {
-            throw new IllegalArgumentException("Cannot open file " + fileName);
+            throw new ProfileDataException("Cannot open file " + fileName);
         }
         try {
             profileData = getProfileDataFromStream(fis);
             fis.close();    /* close the file */
         }
         catch (IOException e) {
-            throw new IllegalArgumentException("Invalid ICC Profile Data" +
-                fileName);
+            ProfileDataException pde = new
+                ProfileDataException("Invalid ICC Profile Data" + fileName);
+            pde.initCause(e);
+            throw pde;
         }
         if (profileData == null) {
-            throw new IllegalArgumentException("Invalid ICC Profile Data" +
+            throw new ProfileDataException("Invalid ICC Profile Data" +
                 fileName);
         }
         try {
             ID = CMSManager.getModule().loadProfile(profileData);
         } catch (CMMException c) {
-            throw new IllegalArgumentException("Invalid ICC Profile Data" +
-                fileName);
+            ProfileDataException pde = new
+                ProfileDataException("Invalid ICC Profile Data" + fileName);
+            pde.initCause(c);
+            throw pde;
         }
     }
 
--- a/jdk/src/share/classes/java/io/Console.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/io/Console.java	Fri Apr 10 13:05:12 2009 -0700
@@ -503,6 +503,21 @@
 
     // Set up JavaIOAccess in SharedSecrets
     static {
+
+        // Add a shutdown hook to restore console's echo state should
+        // it be necessary.
+        sun.misc.SharedSecrets.getJavaLangAccess()
+            .registerShutdownHook(0 /* shutdown hook invocation order */,
+                new Runnable() {
+                    public void run() {
+                        try {
+                            if (echoOff) {
+                                echo(true);
+                            }
+                        } catch (IOException x) { }
+                    }
+                });
+
         sun.misc.SharedSecrets.setJavaIOAccess(new sun.misc.JavaIOAccess() {
             public Console console() {
                 if (istty()) {
@@ -513,20 +528,6 @@
                 return null;
             }
 
-            // Add a shutdown hook to restore console's echo state should
-            // it be necessary.
-            public Runnable consoleRestoreHook() {
-                return new Runnable() {
-                    public void run() {
-                        try {
-                            if (echoOff) {
-                                echo(true);
-                            }
-                        } catch (IOException x) {}
-                    }
-                };
-            }
-
             public Charset charset() {
                 // This method is called in sun.security.util.Password,
                 // cons already exists when this method is called
--- a/jdk/src/share/classes/java/io/DeleteOnExitHook.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/io/DeleteOnExitHook.java	Fri Apr 10 13:05:12 2009 -0700
@@ -34,17 +34,18 @@
  */
 
 class DeleteOnExitHook {
-    private static DeleteOnExitHook instance = null;
+    static {
+         sun.misc.SharedSecrets.getJavaLangAccess()
+             .registerShutdownHook(2 /* Shutdown hook invocation order */,
+                 new Runnable() {
+                     public void run() {
+                        runHooks();
+                     }
+                 });
+    }
 
     private static LinkedHashSet<String> files = new LinkedHashSet<String>();
 
-    static DeleteOnExitHook hook() {
-        if (instance == null)
-            instance = new DeleteOnExitHook();
-
-        return instance;
-    }
-
     private DeleteOnExitHook() {}
 
     static synchronized void add(String file) {
@@ -54,7 +55,7 @@
         files.add(file);
     }
 
-    void run() {
+    static void runHooks() {
         LinkedHashSet<String> theFiles;
 
         synchronized (DeleteOnExitHook.class) {
--- a/jdk/src/share/classes/java/io/File.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/io/File.java	Fri Apr 10 13:05:12 2009 -0700
@@ -2147,18 +2147,6 @@
     /** use serialVersionUID from JDK 1.0.2 for interoperability */
     private static final long serialVersionUID = 301077366599181567L;
 
-    // Set up JavaIODeleteOnExitAccess in SharedSecrets
-    // Added here as DeleteOnExitHook is package-private and SharedSecrets cannot easily access it.
-    static {
-        sun.misc.SharedSecrets.setJavaIODeleteOnExitAccess(
-            new sun.misc.JavaIODeleteOnExitAccess() {
-                public void run() {
-                    DeleteOnExitHook.hook().run();
-                }
-            }
-        );
-    }
-
     // -- Integration with java.nio.file --
 
     private volatile transient Path filePath;
--- a/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java	Fri Apr 10 13:05:12 2009 -0700
@@ -34,19 +34,19 @@
  * @see java.lang.Runtime#removeShutdownHook
  */
 
-class ApplicationShutdownHooks implements Runnable {
-    private static ApplicationShutdownHooks instance = null;
+class ApplicationShutdownHooks {
+    static {
+        Shutdown.add(1 /* shutdown hook invocation order */,
+            new Runnable() {
+                public void run() {
+                    runHooks();
+                }
+            });
+    }
 
     /* The set of registered hooks */
     private static IdentityHashMap<Thread, Thread> hooks = new IdentityHashMap<Thread, Thread>();
 
-    static synchronized ApplicationShutdownHooks hook() {
-        if (instance == null)
-            instance = new ApplicationShutdownHooks();
-
-        return instance;
-    }
-
     private ApplicationShutdownHooks() {}
 
     /* Add a new shutdown hook.  Checks the shutdown state and the hook itself,
@@ -82,7 +82,7 @@
      * to run in. Hooks are run concurrently and this method waits for
      * them to finish.
      */
-    public void run() {
+    static void runHooks() {
         Collection<Thread> threads;
         synchronized(ApplicationShutdownHooks.class) {
             threads = hooks.keySet();
--- a/jdk/src/share/classes/java/lang/Class.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/Class.java	Fri Apr 10 13:05:12 2009 -0700
@@ -3059,14 +3059,12 @@
     }
 
 
-    private static Annotation[] EMPTY_ANNOTATIONS_ARRAY = new Annotation[0];
-
     /**
      * @since 1.5
      */
     public Annotation[] getAnnotations() {
         initAnnotationsIfNecessary();
-        return annotations.values().toArray(EMPTY_ANNOTATIONS_ARRAY);
+        return AnnotationParser.toArray(annotations);
     }
 
     /**
@@ -3074,7 +3072,7 @@
      */
     public Annotation[] getDeclaredAnnotations()  {
         initAnnotationsIfNecessary();
-        return declaredAnnotations.values().toArray(EMPTY_ANNOTATIONS_ARRAY);
+        return AnnotationParser.toArray(declaredAnnotations);
     }
 
     // Annotations cache
--- a/jdk/src/share/classes/java/lang/Shutdown.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/Shutdown.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,8 +25,6 @@
 
 package java.lang;
 
-import java.util.ArrayList;
-
 
 /**
  * Package-private utility class containing data structures and logic
@@ -47,8 +45,13 @@
     /* Should we run all finalizers upon exit? */
     private static boolean runFinalizersOnExit = false;
 
-    /* The set of registered, wrapped hooks, or null if there aren't any */
-    private static ArrayList<Runnable> hooks = new ArrayList<Runnable>();
+    // The system shutdown hooks are registered with a predefined slot.
+    // The list of shutdown hooks is as follows:
+    // (0) Console restore hook
+    // (1) Application hooks
+    // (2) DeleteOnExit hook
+    private static final int MAX_SYSTEM_HOOKS = 10;
+    private static final Runnable[] hooks = new Runnable[MAX_SYSTEM_HOOKS];
 
     /* The preceding static fields are protected by this lock */
     private static class Lock { };
@@ -68,33 +71,18 @@
     /* Add a new shutdown hook.  Checks the shutdown state and the hook itself,
      * but does not do any security checks.
      */
-    static void add(Runnable hook) {
+    static void add(int slot, Runnable hook) {
         synchronized (lock) {
             if (state > RUNNING)
                 throw new IllegalStateException("Shutdown in progress");
 
-            hooks.add(hook);
+            if (hooks[slot] != null)
+                throw new InternalError("Shutdown hook at slot " + slot + " already registered");
+
+            hooks[slot] = hook;
         }
     }
 
-
-    /* Remove a previously-registered hook.  Like the add method, this method
-     * does not do any security checks.
-     */
-    static boolean remove(Runnable hook) {
-        synchronized (lock) {
-            if (state > RUNNING)
-                throw new IllegalStateException("Shutdown in progress");
-            if (hook == null) throw new NullPointerException();
-            if (hooks == null) {
-                return false;
-            } else {
-                return hooks.remove(hook);
-            }
-        }
-    }
-
-
     /* Run all registered shutdown hooks
      */
     private static void runHooks() {
@@ -103,7 +91,7 @@
          */
         for (Runnable hook : hooks) {
             try {
-                hook.run();
+                if (hook != null) hook.run();
             } catch(Throwable t) {
                 if (t instanceof ThreadDeath) {
                     ThreadDeath td = (ThreadDeath)t;
--- a/jdk/src/share/classes/java/lang/StringCoding.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/StringCoding.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,13 +25,10 @@
 
 package java.lang;
 
-import java.io.CharConversionException;
 import java.io.UnsupportedEncodingException;
 import java.lang.ref.SoftReference;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
 import java.nio.charset.Charset;
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CharsetEncoder;
@@ -39,11 +36,12 @@
 import java.nio.charset.CoderResult;
 import java.nio.charset.CodingErrorAction;
 import java.nio.charset.IllegalCharsetNameException;
-import java.nio.charset.MalformedInputException;
 import java.nio.charset.UnsupportedCharsetException;
 import java.util.Arrays;
 import sun.misc.MessageUtils;
 import sun.nio.cs.HistoricallyNamedCharset;
+import sun.nio.cs.ArrayDecoder;
+import sun.nio.cs.ArrayEncoder;
 
 /**
  * Utility class for string encoding and decoding.
@@ -74,10 +72,8 @@
 
     // Trim the given byte array to the given length
     //
-    private static byte[] safeTrim(byte[] ba, int len, Charset cs) {
-        if (len == ba.length
-            && (System.getSecurityManager() == null
-                || cs.getClass().getClassLoader0() == null))
+    private static byte[] safeTrim(byte[] ba, int len, Charset cs, boolean isTrusted) {
+        if (len == ba.length && (isTrusted || System.getSecurityManager() == null))
             return ba;
         else
             return Arrays.copyOf(ba, len);
@@ -85,10 +81,9 @@
 
     // Trim the given char array to the given length
     //
-    private static char[] safeTrim(char[] ca, int len, Charset cs) {
-        if (len == ca.length
-            && (System.getSecurityManager() == null
-                || cs.getClass().getClassLoader0() == null))
+    private static char[] safeTrim(char[] ca, int len,
+                                   Charset cs, boolean isTrusted) {
+        if (len == ca.length && (isTrusted || System.getSecurityManager() == null))
             return ca;
         else
             return Arrays.copyOf(ca, len);
@@ -128,6 +123,7 @@
         private final String requestedCharsetName;
         private final Charset cs;
         private final CharsetDecoder cd;
+        private final boolean isTrusted;
 
         private StringDecoder(Charset cs, String rcn) {
             this.requestedCharsetName = rcn;
@@ -135,6 +131,7 @@
             this.cd = cs.newDecoder()
                 .onMalformedInput(CodingErrorAction.REPLACE)
                 .onUnmappableCharacter(CodingErrorAction.REPLACE);
+            this.isTrusted = (cs.getClass().getClassLoader0() == null);
         }
 
         String charsetName() {
@@ -152,24 +149,28 @@
             char[] ca = new char[en];
             if (len == 0)
                 return ca;
-            cd.reset();
-            ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
-            CharBuffer cb = CharBuffer.wrap(ca);
-            try {
-                CoderResult cr = cd.decode(bb, cb, true);
-                if (!cr.isUnderflow())
-                    cr.throwException();
-                cr = cd.flush(cb);
-                if (!cr.isUnderflow())
-                    cr.throwException();
-            } catch (CharacterCodingException x) {
-                // Substitution is always enabled,
-                // so this shouldn't happen
-                throw new Error(x);
+            if (cd instanceof ArrayDecoder) {
+                int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
+                return safeTrim(ca, clen, cs, isTrusted);
+            } else {
+                cd.reset();
+                ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
+                CharBuffer cb = CharBuffer.wrap(ca);
+                try {
+                    CoderResult cr = cd.decode(bb, cb, true);
+                    if (!cr.isUnderflow())
+                        cr.throwException();
+                    cr = cd.flush(cb);
+                    if (!cr.isUnderflow())
+                        cr.throwException();
+                } catch (CharacterCodingException x) {
+                    // Substitution is always enabled,
+                    // so this shouldn't happen
+                    throw new Error(x);
+                }
+                return safeTrim(ca, cb.position(), cs, isTrusted);
             }
-            return safeTrim(ca, cb.position(), cs);
         }
-
     }
 
     static char[] decode(String charsetName, byte[] ba, int off, int len)
@@ -193,8 +194,57 @@
     }
 
     static char[] decode(Charset cs, byte[] ba, int off, int len) {
-        StringDecoder sd = new StringDecoder(cs, cs.name());
-        return sd.decode(Arrays.copyOfRange(ba, off, off + len), 0, len);
+        // (1)We never cache the "external" cs, the only benefit of creating
+        // an additional StringDe/Encoder object to wrap it is to share the
+        // de/encode() method. These SD/E objects are short-lifed, the young-gen
+        // gc should be able to take care of them well. But the best approash
+        // is still not to generate them if not really necessary.
+        // (2)The defensive copy of the input byte/char[] has a big performance
+        // impact, as well as the outgoing result byte/char[]. Need to do the
+        // optimization check of (sm==null && classLoader0==null) for both.
+        // (3)getClass().getClassLoader0() is expensive
+        // (4)There might be a timing gap in isTrusted setting. getClassLoader0()
+        // is only chcked (and then isTrusted gets set) when (SM==null). It is
+        // possible that the SM==null for now but then SM is NOT null later
+        // when safeTrim() is invoked...the "safe" way to do is to redundant
+        // check (... && (isTrusted || SM == null || getClassLoader0())) in trim
+        // but it then can be argued that the SM is null when the opertaion
+        // is started...
+        CharsetDecoder cd = cs.newDecoder();
+        int en = scale(len, cd.maxCharsPerByte());
+        char[] ca = new char[en];
+        if (len == 0)
+            return ca;
+        boolean isTrusted = false;
+        if (System.getSecurityManager() != null) {
+            if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
+                ba =  Arrays.copyOfRange(ba, off, off + len);
+                off = 0;
+            }
+        }
+        if (cd instanceof ArrayDecoder) {
+            int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
+            return safeTrim(ca, clen, cs, isTrusted);
+        } else {
+            cd.onMalformedInput(CodingErrorAction.REPLACE)
+              .onUnmappableCharacter(CodingErrorAction.REPLACE)
+              .reset();
+            ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
+            CharBuffer cb = CharBuffer.wrap(ca);
+            try {
+                CoderResult cr = cd.decode(bb, cb, true);
+                if (!cr.isUnderflow())
+                    cr.throwException();
+                cr = cd.flush(cb);
+                if (!cr.isUnderflow())
+                    cr.throwException();
+            } catch (CharacterCodingException x) {
+                // Substitution is always enabled,
+                // so this shouldn't happen
+                throw new Error(x);
+            }
+            return safeTrim(ca, cb.position(), cs, isTrusted);
+        }
     }
 
     static char[] decode(byte[] ba, int off, int len) {
@@ -218,14 +268,12 @@
         }
     }
 
-
-
-
     // -- Encoding --
     private static class StringEncoder {
         private Charset cs;
         private CharsetEncoder ce;
         private final String requestedCharsetName;
+        private final boolean isTrusted;
 
         private StringEncoder(Charset cs, String rcn) {
             this.requestedCharsetName = rcn;
@@ -233,6 +281,7 @@
             this.ce = cs.newEncoder()
                 .onMalformedInput(CodingErrorAction.REPLACE)
                 .onUnmappableCharacter(CodingErrorAction.REPLACE);
+            this.isTrusted = (cs.getClass().getClassLoader0() == null);
         }
 
         String charsetName() {
@@ -250,23 +299,27 @@
             byte[] ba = new byte[en];
             if (len == 0)
                 return ba;
-
-            ce.reset();
-            ByteBuffer bb = ByteBuffer.wrap(ba);
-            CharBuffer cb = CharBuffer.wrap(ca, off, len);
-            try {
-                CoderResult cr = ce.encode(cb, bb, true);
-                if (!cr.isUnderflow())
-                    cr.throwException();
-                cr = ce.flush(bb);
-                if (!cr.isUnderflow())
-                    cr.throwException();
-            } catch (CharacterCodingException x) {
-                // Substitution is always enabled,
-                // so this shouldn't happen
-                throw new Error(x);
+            if (ce instanceof ArrayEncoder) {
+                int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
+                return safeTrim(ba, blen, cs, isTrusted);
+            } else {
+                ce.reset();
+                ByteBuffer bb = ByteBuffer.wrap(ba);
+                CharBuffer cb = CharBuffer.wrap(ca, off, len);
+                try {
+                    CoderResult cr = ce.encode(cb, bb, true);
+                    if (!cr.isUnderflow())
+                        cr.throwException();
+                    cr = ce.flush(bb);
+                    if (!cr.isUnderflow())
+                        cr.throwException();
+                } catch (CharacterCodingException x) {
+                    // Substitution is always enabled,
+                    // so this shouldn't happen
+                    throw new Error(x);
+                }
+                return safeTrim(ba, bb.position(), cs, isTrusted);
             }
-            return safeTrim(ba, bb.position(), cs);
         }
     }
 
@@ -291,8 +344,39 @@
     }
 
     static byte[] encode(Charset cs, char[] ca, int off, int len) {
-        StringEncoder se = new StringEncoder(cs, cs.name());
-        return se.encode(Arrays.copyOfRange(ca, off, off + len), 0, len);
+        CharsetEncoder ce = cs.newEncoder();
+        int en = scale(len, ce.maxBytesPerChar());
+        byte[] ba = new byte[en];
+        if (len == 0)
+            return ba;
+        boolean isTrusted = false;
+        if (System.getSecurityManager() != null) {
+            if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
+                ca =  Arrays.copyOfRange(ca, off, off + len);
+                off = 0;
+            }
+        }
+        if (ce instanceof ArrayEncoder) {
+            int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
+            return safeTrim(ba, blen, cs, isTrusted);
+        } else {
+            ce.onMalformedInput(CodingErrorAction.REPLACE)
+              .onUnmappableCharacter(CodingErrorAction.REPLACE)
+              .reset();
+            ByteBuffer bb = ByteBuffer.wrap(ba);
+            CharBuffer cb = CharBuffer.wrap(ca, off, len);
+            try {
+                CoderResult cr = ce.encode(cb, bb, true);
+                if (!cr.isUnderflow())
+                    cr.throwException();
+                cr = ce.flush(bb);
+                if (!cr.isUnderflow())
+                    cr.throwException();
+            } catch (CharacterCodingException x) {
+                throw new Error(x);
+            }
+            return safeTrim(ba, bb.position(), cs, isTrusted);
+        }
     }
 
     static byte[] encode(char[] ca, int off, int len) {
--- a/jdk/src/share/classes/java/lang/System.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/System.java	Fri Apr 10 13:05:12 2009 -0700
@@ -34,7 +34,6 @@
 import java.nio.channels.Channel;
 import java.nio.channels.spi.SelectorProvider;
 import sun.nio.ch.Interruptible;
-import sun.net.InetAddressCachePolicy;
 import sun.reflect.Reflection;
 import sun.security.util.SecurityConstants;
 import sun.reflect.annotation.AnnotationType;
@@ -310,7 +309,6 @@
         }
 
         security = s;
-        InetAddressCachePolicy.setIfNotSet(InetAddressCachePolicy.FOREVER);
     }
 
     /**
@@ -1121,14 +1119,6 @@
         // Setup Java signal handlers for HUP, TERM, and INT (where available).
         Terminator.setup();
 
-        // The order in with the hooks are added here is important as it
-        // determines the order in which they are run.
-        // (1)Console restore hook needs to be called first.
-        // (2)Application hooks must be run before calling deleteOnExitHook.
-        Shutdown.add(sun.misc.SharedSecrets.getJavaIOAccess().consoleRestoreHook());
-        Shutdown.add(ApplicationShutdownHooks.hook());
-        Shutdown.add(sun.misc.SharedSecrets.getJavaIODeleteOnExitAccess());
-
         // Initialize any miscellenous operating system settings that need to be
         // set for the class libraries. Currently this is no-op everywhere except
         // for Windows where the process-wide error mode is set before the java.io
@@ -1174,6 +1164,9 @@
             public void blockedOn(Thread t, Interruptible b) {
                 t.blockedOn(b);
             }
+            public void registerShutdownHook(int slot, Runnable r) {
+                Shutdown.add(slot, r);
+            }
         });
     }
 
--- a/jdk/src/share/classes/java/lang/Thread.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/Thread.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1994-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1994-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/lang/reflect/Constructor.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Constructor.java	Fri Apr 10 13:05:12 2009 -0700
@@ -626,13 +626,11 @@
         return (T) declaredAnnotations().get(annotationClass);
     }
 
-    private static final Annotation[] EMPTY_ANNOTATION_ARRAY=new Annotation[0];
-
     /**
      * @since 1.5
      */
     public Annotation[] getDeclaredAnnotations()  {
-        return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY);
+        return AnnotationParser.toArray(declaredAnnotations());
     }
 
     private transient Map<Class, Annotation> declaredAnnotations;
--- a/jdk/src/share/classes/java/lang/reflect/Field.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Field.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1018,13 +1018,11 @@
         return (T) declaredAnnotations().get(annotationClass);
     }
 
-    private static final Annotation[] EMPTY_ANNOTATION_ARRAY=new Annotation[0];
-
     /**
      * @since 1.5
      */
     public Annotation[] getDeclaredAnnotations()  {
-        return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY);
+        return AnnotationParser.toArray(declaredAnnotations());
     }
 
     private transient Map<Class, Annotation> declaredAnnotations;
--- a/jdk/src/share/classes/java/lang/reflect/Method.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Method.java	Fri Apr 10 13:05:12 2009 -0700
@@ -705,13 +705,11 @@
         return (T) declaredAnnotations().get(annotationClass);
     }
 
-    private static final Annotation[] EMPTY_ANNOTATION_ARRAY=new Annotation[0];
-
     /**
      * @since 1.5
      */
     public Annotation[] getDeclaredAnnotations()  {
-        return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY);
+        return AnnotationParser.toArray(declaredAnnotations());
     }
 
     private transient Map<Class, Annotation> declaredAnnotations;
--- a/jdk/src/share/classes/java/net/SocketPermission.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/net/SocketPermission.java	Fri Apr 10 13:05:12 2009 -0700
@@ -113,7 +113,6 @@
  * <p>Similarly, if the following permission:
  *
  * <pre>
- *   p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept");
  *   p2 = new SocketPermission("localhost:1024-", "accept,connect,listen");
  * </pre>
  *
--- a/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java	Fri Apr 10 13:05:12 2009 -0700
@@ -5,7 +5,7 @@
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Sun designates this
- * particular file as subject to the "Classname" exception as provided
+ * particular file as subject to the "Classpath" exception as provided
  * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
--- a/jdk/src/share/classes/java/security/Permission.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/security/Permission.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -214,18 +214,18 @@
     /**
      * Returns a string describing this Permission.  The convention is to
      * specify the class name, the permission name, and the actions in
-     * the following format: '("ClassName" "name" "actions")'.
+     * the following format: '("ClassName" "name" "actions")', or
+     * '("ClassName" "name")' if actions list is null or empty.
      *
      * @return information about this Permission.
      */
-
     public String toString() {
         String actions = getActions();
         if ((actions == null) || (actions.length() == 0)) { // OPTIONAL
-            return "(" + getClass().getName() + " " + name + ")";
+            return "(\"" + getClass().getName() + "\" \"" + name + "\")";
         } else {
-            return "(" + getClass().getName() + " " + name + " " +
-                actions + ")";
+            return "(\"" + getClass().getName() + "\" \"" + name +
+                 "\" \"" + actions + "\")";
         }
     }
 }
--- a/jdk/src/share/classes/java/util/ArrayList.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/ArrayList.java	Fri Apr 10 13:05:12 2009 -0700
@@ -179,7 +179,6 @@
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
-            Object oldData[] = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
             if (newCapacity < minCapacity)
                 newCapacity = minCapacity;
--- a/jdk/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1222,8 +1222,10 @@
         // The correctness of this depends on head being initialized
         // before tail and on head.next being accurate if the current
         // thread is first in queue.
-        Node h, s;
-        return (h = head) != tail &&
+        Node t = tail; // Read fields in reverse initialization order
+        Node h = head;
+        Node s;
+        return h != t &&
             ((s = h.next) == null || s.thread != Thread.currentThread());
     }
 
--- a/jdk/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1445,8 +1445,10 @@
         // The correctness of this depends on head being initialized
         // before tail and on head.next being accurate if the current
         // thread is first in queue.
-        Node h, s;
-        return (h = head) != tail &&
+        Node t = tail; // Read fields in reverse initialization order
+        Node h = head;
+        Node s;
+        return h != t &&
             ((s = h.next) == null || s.thread != Thread.currentThread());
     }
 
--- a/jdk/src/share/classes/java/util/logging/LogManager.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java	Fri Apr 10 13:05:12 2009 -0700
@@ -215,6 +215,14 @@
     // This private class is used as a shutdown hook.
     // It does a "reset" to close all open handlers.
     private class Cleaner extends Thread {
+
+        private Cleaner() {
+            /* Set context class loader to null in order to avoid
+             * keeping a strong reference to an application classloader.
+             */
+            this.setContextClassLoader(null);
+        }
+
         public void run() {
             // This is to ensure the LogManager.<clinit> is completed
             // before synchronized block. Otherwise deadlocks are possible.
--- a/jdk/src/share/classes/java/util/regex/Matcher.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/regex/Matcher.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/regex/Pattern.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/java/util/regex/Pattern.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2567,7 +2567,8 @@
                 break;
             case '<':   // (?<xxx)  look behind
                 ch = read();
-                if (Character.isLetter(ch)) {     // named captured group
+                if (ASCII.isLower(ch) || ASCII.isUpper(ch) || ASCII.isDigit(ch)) {
+                    // named captured group
                     String name = groupname(ch);
                     if (namedGroups().containsKey(name))
                         throw error("Named capturing group <" + name
--- a/jdk/src/share/classes/javax/imageio/ImageTypeSpecifier.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/javax/imageio/ImageTypeSpecifier.java	Fri Apr 10 13:05:12 2009 -0700
@@ -67,126 +67,13 @@
      * <code>BufferedImage</code> types.
      */
     private static ImageTypeSpecifier[] BISpecifier;
-
+    private static ColorSpace sRGB;
     // Initialize the standard specifiers
     static {
-        ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+        sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
 
         BISpecifier =
             new ImageTypeSpecifier[BufferedImage.TYPE_BYTE_INDEXED + 1];
-
-        BISpecifier[BufferedImage.TYPE_CUSTOM] = null;
-
-        BISpecifier[BufferedImage.TYPE_INT_RGB] =
-            createPacked(sRGB,
-                         0x00ff0000,
-                         0x0000ff00,
-                         0x000000ff,
-                         0x0,
-                         DataBuffer.TYPE_INT,
-                         false);
-
-        BISpecifier[BufferedImage.TYPE_INT_ARGB] =
-            createPacked(sRGB,
-                         0x00ff0000,
-                         0x0000ff00,
-                         0x000000ff,
-                         0xff000000,
-                         DataBuffer.TYPE_INT,
-                         false);
-
-        BISpecifier[BufferedImage.TYPE_INT_ARGB_PRE] =
-            createPacked(sRGB,
-                         0x00ff0000,
-                         0x0000ff00,
-                         0x000000ff,
-                         0xff000000,
-                         DataBuffer.TYPE_INT,
-                         true);
-
-        BISpecifier[BufferedImage.TYPE_INT_BGR] =
-            createPacked(sRGB,
-                         0x000000ff,
-                         0x0000ff00,
-                         0x00ff0000,
-                         0x0,
-                         DataBuffer.TYPE_INT,
-                         false);
-
-        int[] bOffsRGB = { 2, 1, 0 };
-        BISpecifier[BufferedImage.TYPE_3BYTE_BGR] =
-            createInterleaved(sRGB,
-                              bOffsRGB,
-                              DataBuffer.TYPE_BYTE,
-                              false,
-                              false);
-
-        int[] bOffsABGR = { 3, 2, 1, 0 };
-        BISpecifier[BufferedImage.TYPE_4BYTE_ABGR] =
-            createInterleaved(sRGB,
-                              bOffsABGR,
-                              DataBuffer.TYPE_BYTE,
-                              true,
-                              false);
-
-        BISpecifier[BufferedImage.TYPE_4BYTE_ABGR_PRE] =
-            createInterleaved(sRGB,
-                              bOffsABGR,
-                              DataBuffer.TYPE_BYTE,
-                              true,
-                              true);
-
-        BISpecifier[BufferedImage.TYPE_USHORT_565_RGB] =
-            createPacked(sRGB,
-                         0xF800,
-                         0x07E0,
-                         0x001F,
-                         0x0,
-                         DataBuffer.TYPE_USHORT,
-                         false);
-
-        BISpecifier[BufferedImage.TYPE_USHORT_555_RGB] =
-            createPacked(sRGB,
-                         0x7C00,
-                         0x03E0,
-                         0x001F,
-                         0x0,
-                         DataBuffer.TYPE_USHORT,
-                         false);
-
-        BISpecifier[BufferedImage.TYPE_BYTE_GRAY] =
-            createGrayscale(8,
-                            DataBuffer.TYPE_BYTE,
-                            false);
-
-        BISpecifier[BufferedImage.TYPE_USHORT_GRAY] =
-            createGrayscale(16,
-                            DataBuffer.TYPE_USHORT,
-                            false);
-
-        BISpecifier[BufferedImage.TYPE_BYTE_BINARY] =
-            createGrayscale(1,
-                            DataBuffer.TYPE_BYTE,
-                            false);
-
-        BufferedImage bi =
-            new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_INDEXED);
-        IndexColorModel icm = (IndexColorModel)bi.getColorModel();
-        int mapSize = icm.getMapSize();
-        byte[] redLUT = new byte[mapSize];
-        byte[] greenLUT = new byte[mapSize];
-        byte[] blueLUT = new byte[mapSize];
-        byte[] alphaLUT = new byte[mapSize];
-
-        icm.getReds(redLUT);
-        icm.getGreens(greenLUT);
-        icm.getBlues(blueLUT);
-        icm.getAlphas(alphaLUT);
-
-        BISpecifier[BufferedImage.TYPE_BYTE_INDEXED] =
-            createIndexed(redLUT, greenLUT, blueLUT, alphaLUT,
-                          8,
-                          DataBuffer.TYPE_BYTE);
     }
 
     /**
@@ -1011,7 +898,7 @@
         ImageTypeSpecifier createFromBufferedImageType(int bufferedImageType) {
         if (bufferedImageType >= BufferedImage.TYPE_INT_RGB &&
             bufferedImageType <= BufferedImage.TYPE_BYTE_INDEXED) {
-            return BISpecifier[bufferedImageType];
+            return getSpecifier(bufferedImageType);
         } else if (bufferedImageType == BufferedImage.TYPE_CUSTOM) {
             throw new IllegalArgumentException("Cannot create from TYPE_CUSTOM!");
         } else {
@@ -1041,7 +928,7 @@
         if (image instanceof BufferedImage) {
             int bufferedImageType = ((BufferedImage)image).getType();
             if (bufferedImageType != BufferedImage.TYPE_CUSTOM) {
-                return BISpecifier[bufferedImageType];
+                return getSpecifier(bufferedImageType);
             }
         }
 
@@ -1225,4 +1112,130 @@
     public int hashCode() {
         return (9 * colorModel.hashCode()) + (14 * sampleModel.hashCode());
     }
+
+    private static ImageTypeSpecifier getSpecifier(int type) {
+        if (BISpecifier[type] == null) {
+            BISpecifier[type] = createSpecifier(type);
+        }
+        return BISpecifier[type];
+    }
+
+    private static ImageTypeSpecifier createSpecifier(int type) {
+        switch(type) {
+          case BufferedImage.TYPE_INT_RGB:
+              return createPacked(sRGB,
+                                  0x00ff0000,
+                                  0x0000ff00,
+                                  0x000000ff,
+                                  0x0,
+                                  DataBuffer.TYPE_INT,
+                                  false);
+
+          case BufferedImage.TYPE_INT_ARGB:
+              return createPacked(sRGB,
+                                  0x00ff0000,
+                                  0x0000ff00,
+                                  0x000000ff,
+                                  0xff000000,
+                                  DataBuffer.TYPE_INT,
+                                  false);
+
+          case BufferedImage.TYPE_INT_ARGB_PRE:
+              return createPacked(sRGB,
+                                  0x00ff0000,
+                                  0x0000ff00,
+                                  0x000000ff,
+                                  0xff000000,
+                                  DataBuffer.TYPE_INT,
+                                  true);
+
+          case BufferedImage.TYPE_INT_BGR:
+              return createPacked(sRGB,
+                                  0x000000ff,
+                                  0x0000ff00,
+                                  0x00ff0000,
+                                  0x0,
+                                  DataBuffer.TYPE_INT,
+                                  false);
+
+          case BufferedImage.TYPE_3BYTE_BGR:
+              return createInterleaved(sRGB,
+                                       new int[] { 2, 1, 0 },
+                                       DataBuffer.TYPE_BYTE,
+                                       false,
+                                       false);
+
+          case BufferedImage.TYPE_4BYTE_ABGR:
+              return createInterleaved(sRGB,
+                                       new int[] { 3, 2, 1, 0 },
+                                       DataBuffer.TYPE_BYTE,
+                                       true,
+                                       false);
+
+          case BufferedImage.TYPE_4BYTE_ABGR_PRE:
+              return createInterleaved(sRGB,
+                                       new int[] { 3, 2, 1, 0 },
+                                       DataBuffer.TYPE_BYTE,
+                                       true,
+                                       true);
+
+          case BufferedImage.TYPE_USHORT_565_RGB:
+              return createPacked(sRGB,
+                                  0xF800,
+                                  0x07E0,
+                                  0x001F,
+                                  0x0,
+                                  DataBuffer.TYPE_USHORT,
+                                  false);
+
+          case BufferedImage.TYPE_USHORT_555_RGB:
+              return createPacked(sRGB,
+                                  0x7C00,
+                                  0x03E0,
+                                  0x001F,
+                                  0x0,
+                                  DataBuffer.TYPE_USHORT,
+                                  false);
+
+          case BufferedImage.TYPE_BYTE_GRAY:
+            return createGrayscale(8,
+                                   DataBuffer.TYPE_BYTE,
+                                   false);
+
+          case BufferedImage.TYPE_USHORT_GRAY:
+            return createGrayscale(16,
+                                   DataBuffer.TYPE_USHORT,
+                                   false);
+
+          case BufferedImage.TYPE_BYTE_BINARY:
+              return createGrayscale(1,
+                                     DataBuffer.TYPE_BYTE,
+                                     false);
+
+          case BufferedImage.TYPE_BYTE_INDEXED:
+          {
+
+              BufferedImage bi =
+                  new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_INDEXED);
+              IndexColorModel icm = (IndexColorModel)bi.getColorModel();
+              int mapSize = icm.getMapSize();
+              byte[] redLUT = new byte[mapSize];
+              byte[] greenLUT = new byte[mapSize];
+              byte[] blueLUT = new byte[mapSize];
+              byte[] alphaLUT = new byte[mapSize];
+
+              icm.getReds(redLUT);
+              icm.getGreens(greenLUT);
+              icm.getBlues(blueLUT);
+              icm.getAlphas(alphaLUT);
+
+              return createIndexed(redLUT, greenLUT, blueLUT, alphaLUT,
+                                   8,
+                                   DataBuffer.TYPE_BYTE);
+          }
+          default:
+              throw new IllegalArgumentException("Invalid BufferedImage type!");
+        }
+    }
+
 }
--- a/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataFormat.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataFormat.java	Fri Apr 10 13:05:12 2009 -0700
@@ -242,8 +242,12 @@
 
     /**
      * A constant returned by <code>getAttributeDataType</code>
-     * indicating that the value of an attribute is one of 'true' or
-     * 'false'.
+     * indicating that the value of an attribute is one of the boolean
+     * values 'true' or 'false'.
+     * Attribute values of type DATATYPE_BOOLEAN should be marked as
+     * enumerations, and the permitted values should be the string
+     * literal values "TRUE" or "FALSE", although a plugin may also
+     * recognise lower or mixed case equivalents.
      */
     int DATATYPE_BOOLEAN = 1;
 
--- a/jdk/src/share/classes/sun/awt/FontConfiguration.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/awt/FontConfiguration.java	Fri Apr 10 13:05:12 2009 -0700
@@ -98,7 +98,7 @@
         if (!inited) {
             this.preferLocaleFonts = false;
             this.preferPropFonts = false;
-            fontConfig = this;      /* static initialization */
+            setFontConfiguration();
             readFontConfigFile(fontConfigFile);
             initFontConfig();
             inited = true;
@@ -1244,6 +1244,10 @@
         return fontConfig;
     }
 
+    protected void setFontConfiguration() {
+        fontConfig = this;      /* static initialization */
+    }
+
     //////////////////////////////////////////////////////////////////////
     // FontConfig data tables and the index constants in binary file    //
     //////////////////////////////////////////////////////////////////////
--- a/jdk/src/share/classes/sun/font/FileFontStrike.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/font/FileFontStrike.java	Fri Apr 10 13:05:12 2009 -0700
@@ -26,6 +26,7 @@
 package sun.font;
 
 import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
 import java.awt.Font;
 import java.awt.GraphicsEnvironment;
 import java.awt.Rectangle;
@@ -842,8 +843,36 @@
         return fileFont.getGlyphOutlineBounds(pScalerContext, glyphCode);
     }
 
+    private
+        WeakReference<ConcurrentHashMap<Integer,GeneralPath>> outlineMapRef;
+
     GeneralPath getGlyphOutline(int glyphCode, float x, float y) {
-        return fileFont.getGlyphOutline(pScalerContext, glyphCode, x, y);
+
+        GeneralPath gp = null;
+        ConcurrentHashMap<Integer, GeneralPath> outlineMap = null;
+
+        if (outlineMapRef != null) {
+            outlineMap = outlineMapRef.get();
+            if (outlineMap != null) {
+                gp = (GeneralPath)outlineMap.get(glyphCode);
+            }
+        }
+
+        if (gp == null) {
+            gp = fileFont.getGlyphOutline(pScalerContext, glyphCode, 0, 0);
+            if (outlineMap == null) {
+                outlineMap = new ConcurrentHashMap<Integer, GeneralPath>();
+                outlineMapRef =
+                   new WeakReference
+                       <ConcurrentHashMap<Integer,GeneralPath>>(outlineMap);
+            }
+            outlineMap.put(glyphCode, gp);
+        }
+        gp = (GeneralPath)gp.clone(); // mutable!
+        if (x != 0f || y != 0f) {
+            gp.transform(AffineTransform.getTranslateInstance(x, y));
+        }
+        return gp;
     }
 
     GeneralPath getGlyphVectorOutline(int[] glyphs, float x, float y) {
--- a/jdk/src/share/classes/sun/font/FontManager.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/font/FontManager.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1601,18 +1601,27 @@
     /* Path may be absolute or a base file name relative to one of
      * the platform font directories
      */
-    private static String getPathName(String s) {
+    private static String getPathName(final String s) {
         File f = new File(s);
         if (f.isAbsolute()) {
             return s;
         } else if (pathDirs.length==1) {
             return pathDirs[0] + File.separator + s;
         } else {
-            for (int p=0; p<pathDirs.length; p++) {
-                f = new File(pathDirs[p] + File.separator + s);
-                if (f.exists()) {
-                    return f.getAbsolutePath();
-                }
+            String path = java.security.AccessController.doPrivileged(
+                 new java.security.PrivilegedAction<String>() {
+                     public String run() {
+                         for (int p=0; p<pathDirs.length; p++) {
+                             File f = new File(pathDirs[p] +File.separator+ s);
+                             if (f.exists()) {
+                                 return f.getAbsolutePath();
+                             }
+                         }
+                         return null;
+                     }
+                });
+            if (path != null) {
+                return path;
             }
         }
         return s; // shouldn't happen, but harmless
--- a/jdk/src/share/classes/sun/font/GlyphLayout.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/font/GlyphLayout.java	Fri Apr 10 13:05:12 2009 -0700
@@ -338,6 +338,8 @@
                     cache = new ConcurrentHashMap<SDKey, SDCache>(10);
                     cacheRef = new
                        SoftReference<ConcurrentHashMap<SDKey, SDCache>>(cache);
+                } else if (cache.size() >= 512) {
+                    cache.clear();
                 }
                 cache.put(key, res);
             }
--- a/jdk/src/share/classes/sun/font/StrikeCache.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/font/StrikeCache.java	Fri Apr 10 13:05:12 2009 -0700
@@ -232,6 +232,16 @@
             if (disposer.pScalerContext != 0L) {
                 freeLongMemory(new long[0], disposer.pScalerContext);
             }
+        } else if (disposer.pScalerContext != 0L) {
+            /* Rarely a strike may have been created that never cached
+             * any glyphs. In this case we still want to free the scaler
+             * context.
+             */
+            if (FontManager.longAddresses) {
+                freeLongMemory(new long[0], disposer.pScalerContext);
+            } else {
+                freeIntMemory(new int[0], disposer.pScalerContext);
+            }
         }
     }
 
--- a/jdk/src/share/classes/sun/java2d/cmm/ProfileActivator.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/java2d/cmm/ProfileActivator.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,6 +25,7 @@
 
 package sun.java2d.cmm;
 
+import java.awt.color.ProfileDataException;
 
 /**
  * An interface to allow the ProfileDeferralMgr to activate a
@@ -35,6 +36,6 @@
     /**
      * Activate a previously deferred ICC_Profile object.
      */
-    public void activate();
+    public void activate() throws ProfileDataException;
 
 }
--- a/jdk/src/share/classes/sun/java2d/cmm/ProfileDeferralMgr.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/java2d/cmm/ProfileDeferralMgr.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,6 +25,7 @@
 
 package sun.java2d.cmm;
 
+import java.awt.color.ProfileDataException;
 import java.util.Vector;
 
 
@@ -39,7 +40,7 @@
 public class ProfileDeferralMgr {
 
     public static boolean deferring = true;
-    private static Vector aVector;
+    private static Vector<ProfileActivator> aVector;
 
     /**
      * Records a ProfileActivator object whose activate method will
@@ -51,7 +52,7 @@
             return;
         }
         if (aVector == null) {
-            aVector = new Vector(3, 3);
+            aVector = new Vector<ProfileActivator>(3, 3);
         }
         aVector.addElement(pa);
         return;
@@ -89,8 +90,26 @@
             return;
         }
         n = aVector.size();
-        for (i = 0; i < n; i++) {
-            ((ProfileActivator) aVector.get(i)).activate();
+        for (ProfileActivator pa : aVector) {
+            try {
+                pa.activate();
+            } catch (ProfileDataException e) {
+                /*
+                 * Ignore profile activation error for now:
+                 * such exception is pssible due to absence
+                 * or corruption of standard color profile.
+                 * As for now we expect all profiles should
+                 * be shiped with jre and presence of this
+                 * exception is indication of some configuration
+                 * problem in jre installation.
+                 *
+                 * NB: we still are greedy loading deferred profiles
+                 * and load them all if any of them is needed.
+                 * Therefore broken profile (if any) might be never used.
+                 * If there will be attempt to use broken profile then
+                 * it will result in CMMException.
+                 */
+            }
         }
         aVector.removeAllElements();
         aVector = null;
--- a/jdk/src/share/classes/sun/java2d/pisces/Dasher.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/java2d/pisces/Dasher.java	Fri Apr 10 13:05:12 2009 -0700
@@ -120,7 +120,7 @@
 
         // Normalize so 0 <= phase < dash[0]
         int idx = 0;
-        dashOn = false;
+        dashOn = true;
         int d;
         while (phase >= (d = dash[idx])) {
             phase -= d;
--- a/jdk/src/share/classes/sun/java2d/pisces/PiscesRenderingEngine.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/java2d/pisces/PiscesRenderingEngine.java	Fri Apr 10 13:05:12 2009 -0700
@@ -245,6 +245,7 @@
                              FloatToS15_16(coords[1]));
                 break;
             case PathIterator.SEG_CLOSE:
+                lsink.lineJoin();
                 lsink.close();
                 break;
             default:
--- a/jdk/src/share/classes/sun/launcher/LauncherHelper.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/launcher/LauncherHelper.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,5 @@
-
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,18 +54,24 @@
     INSTANCE;
     private static final String defaultBundleName =
             "sun.launcher.resources.launcher";
-    private static ResourceBundle javarb =
-            ResourceBundle.getBundle(defaultBundleName);
     private static final String MAIN_CLASS = "Main-Class";
 
     private static StringBuilder outBuf = new StringBuilder();
 
+    private static ResourceBundle javarb = null;
+    private static synchronized ResourceBundle getLauncherResourceBundle() {
+        if (javarb == null) {
+            javarb = ResourceBundle.getBundle(defaultBundleName);
+        }
+        return javarb;
+    }
+
     /**
      * A private helper method to get a localized message and also
      * apply any arguments that we might pass.
      */
     private static String getLocalizedMessage(String key, Object... args) {
-        String msg = javarb.getString(key);
+        String msg = getLauncherResourceBundle().getString(key);
         return (args != null) ? MessageFormat.format(msg, args) : msg;
     }
 
--- a/jdk/src/share/classes/sun/management/Agent.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/management/Agent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -31,9 +31,9 @@
 import java.io.BufferedInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
 import java.text.MessageFormat;
 import java.util.Properties;
-import java.util.Enumeration;
 import java.util.ResourceBundle;
 import java.util.MissingResourceException;
 import java.lang.management.ManagementFactory;
@@ -41,7 +41,6 @@
 
 import javax.management.remote.JMXConnectorServer;
 
-import sun.management.snmp.AdaptorBootstrap;
 import sun.management.jmxremote.ConnectorBootstrap;
 import static sun.management.AgentConfigurationError.*;
 import sun.misc.VMSupport;
@@ -69,6 +68,9 @@
     private static final String LOCAL_CONNECTOR_ADDRESS_PROP =
         "com.sun.management.jmxremote.localConnectorAddress";
 
+    private static final String SNMP_ADAPTOR_BOOTSTRAP_CLASS_NAME =
+            "sun.management.snmp.AdaptorBootstrap";
+
     // invoked by -javaagent or -Dcom.sun.management.agent.class
     public static void premain(String args) throws Exception {
         agentmain(args);
@@ -128,7 +130,7 @@
 
         try {
             if (snmpPort != null) {
-                AdaptorBootstrap.initialize(snmpPort, props);
+                loadSnmpAgent(snmpPort, props);
             }
 
             /*
@@ -204,6 +206,36 @@
         return mgmtProps;
     }
 
+    private static void loadSnmpAgent(String snmpPort, Properties props) {
+        try {
+            // invoke the following through reflection:
+            //     AdaptorBootstrap.initialize(snmpPort, props);
+            final Class<?> adaptorClass =
+                Class.forName(SNMP_ADAPTOR_BOOTSTRAP_CLASS_NAME,true,null);
+            final Method initializeMethod =
+                    adaptorClass.getMethod("initialize",
+                        String.class, Properties.class);
+            initializeMethod.invoke(null,snmpPort,props);
+        } catch (ClassNotFoundException x) {
+            // The SNMP packages are not present: throws an exception.
+            throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT,x);
+        } catch (NoSuchMethodException x) {
+            // should not happen...
+            throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT,x);
+        } catch (InvocationTargetException x) {
+            final Throwable cause = x.getCause();
+            if (cause instanceof RuntimeException)
+                throw (RuntimeException) cause;
+            else if (cause instanceof Error)
+                throw (Error) cause;
+            // should not happen...
+            throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT,cause);
+        } catch (IllegalAccessException x) {
+            // should not happen...
+            throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT,x);
+        }
+    }
+
     // read config file and initialize the properties
     private static void readConfiguration(String fname, Properties p) {
         if (fname == null) {
--- a/jdk/src/share/classes/sun/misc/ClassLoaderUtil.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/ClassLoaderUtil.java	Fri Apr 10 13:05:12 2009 -0700
@@ -77,8 +77,6 @@
                 jarsClosed.clear();
             }
 
-            System.out.println ("classLoader = " + classLoader);
-            System.out.println ("SharedSecrets.getJavaNetAccess()="+SharedSecrets.getJavaNetAccess());
             URLClassPath ucp = SharedSecrets.getJavaNetAccess()
                                                 .getURLClassPath(classLoader);
             ArrayList loaders = ucp.loaders;
--- a/jdk/src/share/classes/sun/misc/FloatingDecimal.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/FloatingDecimal.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1867,10 +1867,16 @@
      * Grammar is compatible with hexadecimal floating-point constants
      * described in section 6.4.4.2 of the C99 specification.
      */
-    private static Pattern hexFloatPattern = Pattern.compile(
+    private static Pattern hexFloatPattern = null;
+    private static synchronized Pattern getHexFloatPattern() {
+        if (hexFloatPattern == null) {
+           hexFloatPattern = Pattern.compile(
                    //1           234                   56                7                   8      9
                     "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
                     );
+        }
+        return hexFloatPattern;
+    }
 
     /*
      * Convert string s to a suitable floating decimal; uses the
@@ -1880,7 +1886,7 @@
    static FloatingDecimal parseHexString(String s) {
         // Verify string is a member of the hexadecimal floating-point
         // string language.
-        Matcher m = hexFloatPattern.matcher(s);
+        Matcher m = getHexFloatPattern().matcher(s);
         boolean validInput = m.matches();
 
         if (!validInput) {
--- a/jdk/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Fri Apr 10 13:05:12 2009 -0700
@@ -978,15 +978,6 @@
         return new String(result);
     }
 
-    // This method should only ever be called if this object is constructed
-    // without Form.DECIMAL_FLOAT because the perThreadBuffer is not large
-    // enough to handle floating-point numbers of large precision.
-    public String toJavaFormatString() {
-        char result[] = (char[])(perThreadBuffer.get());
-        int i = getChars(result);
-        return new String(result, 0, i);
-    }
-
     // returns the exponent before rounding
     public int getExponent() {
         return decExponent - 1;
@@ -1157,265 +1148,6 @@
             }
         };
 
-    // This method should only ever be called if this object is constructed
-    // without Form.DECIMAL_FLOAT because the perThreadBuffer is not large
-    // enough to handle floating-point numbers of large precision.
-    public void appendTo(Appendable buf) {
-        char result[] = (char[])(perThreadBuffer.get());
-        int i = getChars(result);
-        if (buf instanceof StringBuilder)
-            ((StringBuilder) buf).append(result, 0, i);
-        else if (buf instanceof StringBuffer)
-            ((StringBuffer) buf).append(result, 0, i);
-        else
-            assert false;
-    }
-
-    public static FormattedFloatingDecimal
-    readJavaFormatString( String in ) throws NumberFormatException {
-        boolean isNegative = false;
-        boolean signSeen   = false;
-        int     decExp;
-        char    c;
-
-    parseNumber:
-        try{
-            in = in.trim(); // don't fool around with white space.
-                            // throws NullPointerException if null
-            int l = in.length();
-            if ( l == 0 ) throw new NumberFormatException("empty String");
-            int i = 0;
-            switch ( c = in.charAt( i ) ){
-            case '-':
-                isNegative = true;
-                //FALLTHROUGH
-            case '+':
-                i++;
-                signSeen = true;
-            }
-
-            // Check for NaN and Infinity strings
-            c = in.charAt(i);
-            if(c == 'N' || c == 'I') { // possible NaN or infinity
-                boolean potentialNaN = false;
-                char targetChars[] = null;  // char arrary of "NaN" or "Infinity"
-
-                if(c == 'N') {
-                    targetChars = notANumber;
-                    potentialNaN = true;
-                } else {
-                    targetChars = infinity;
-                }
-
-                // compare Input string to "NaN" or "Infinity"
-                int j = 0;
-                while(i < l && j < targetChars.length) {
-                    if(in.charAt(i) == targetChars[j]) {
-                        i++; j++;
-                    }
-                    else // something is amiss, throw exception
-                        break parseNumber;
-                }
-
-                // For the candidate string to be a NaN or infinity,
-                // all characters in input string and target char[]
-                // must be matched ==> j must equal targetChars.length
-                // and i must equal l
-                if( (j == targetChars.length) && (i == l) ) { // return NaN or infinity
-                    return (potentialNaN ? new FormattedFloatingDecimal(Double.NaN) // NaN has no sign
-                            : new FormattedFloatingDecimal(isNegative?
-                                                  Double.NEGATIVE_INFINITY:
-                                                  Double.POSITIVE_INFINITY)) ;
-                }
-                else { // something went wrong, throw exception
-                    break parseNumber;
-                }
-
-            } else if (c == '0')  { // check for hexadecimal floating-point number
-                if (l > i+1 ) {
-                    char ch = in.charAt(i+1);
-                    if (ch == 'x' || ch == 'X' ) // possible hex string
-                        return parseHexString(in);
-                }
-            }  // look for and process decimal floating-point string
-
-            char[] digits = new char[ l ];
-            int    nDigits= 0;
-            boolean decSeen = false;
-            int decPt = 0;
-            int nLeadZero = 0;
-            int nTrailZero= 0;
-        digitLoop:
-            while ( i < l ){
-                switch ( c = in.charAt( i ) ){
-                case '0':
-                    if ( nDigits > 0 ){
-                        nTrailZero += 1;
-                    } else {
-                        nLeadZero += 1;
-                    }
-                    break; // out of switch.
-                case '1':
-                case '2':
-                case '3':
-                case '4':
-                case '5':
-                case '6':
-                case '7':
-                case '8':
-                case '9':
-                    while ( nTrailZero > 0 ){
-                        digits[nDigits++] = '0';
-                        nTrailZero -= 1;
-                    }
-                    digits[nDigits++] = c;
-                    break; // out of switch.
-                case '.':
-                    if ( decSeen ){
-                        // already saw one ., this is the 2nd.
-                        throw new NumberFormatException("multiple points");
-                    }
-                    decPt = i;
-                    if ( signSeen ){
-                        decPt -= 1;
-                    }
-                    decSeen = true;
-                    break; // out of switch.
-                default:
-                    break digitLoop;
-                }
-                i++;
-            }
-            /*
-             * At this point, we've scanned all the digits and decimal
-             * point we're going to see. Trim off leading and trailing
-             * zeros, which will just confuse us later, and adjust
-             * our initial decimal exponent accordingly.
-             * To review:
-             * we have seen i total characters.
-             * nLeadZero of them were zeros before any other digits.
-             * nTrailZero of them were zeros after any other digits.
-             * if ( decSeen ), then a . was seen after decPt characters
-             * ( including leading zeros which have been discarded )
-             * nDigits characters were neither lead nor trailing
-             * zeros, nor point
-             */
-            /*
-             * special hack: if we saw no non-zero digits, then the
-             * answer is zero!
-             * Unfortunately, we feel honor-bound to keep parsing!
-             */
-            if ( nDigits == 0 ){
-                digits = zero;
-                nDigits = 1;
-                if ( nLeadZero == 0 ){
-                    // we saw NO DIGITS AT ALL,
-                    // not even a crummy 0!
-                    // this is not allowed.
-                    break parseNumber; // go throw exception
-                }
-
-            }
-
-            /* Our initial exponent is decPt, adjusted by the number of
-             * discarded zeros. Or, if there was no decPt,
-             * then its just nDigits adjusted by discarded trailing zeros.
-             */
-            if ( decSeen ){
-                decExp = decPt - nLeadZero;
-            } else {
-                decExp = nDigits+nTrailZero;
-            }
-
-            /*
-             * Look for 'e' or 'E' and an optionally signed integer.
-             */
-            if ( (i < l) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
-                int expSign = 1;
-                int expVal  = 0;
-                int reallyBig = Integer.MAX_VALUE / 10;
-                boolean expOverflow = false;
-                switch( in.charAt(++i) ){
-                case '-':
-                    expSign = -1;
-                    //FALLTHROUGH
-                case '+':
-                    i++;
-                }
-                int expAt = i;
-            expLoop:
-                while ( i < l  ){
-                    if ( expVal >= reallyBig ){
-                        // the next character will cause integer
-                        // overflow.
-                        expOverflow = true;
-                    }
-                    switch ( c = in.charAt(i++) ){
-                    case '0':
-                    case '1':
-                    case '2':
-                    case '3':
-                    case '4':
-                    case '5':
-                    case '6':
-                    case '7':
-                    case '8':
-                    case '9':
-                        expVal = expVal*10 + ( (int)c - (int)'0' );
-                        continue;
-                    default:
-                        i--;           // back up.
-                        break expLoop; // stop parsing exponent.
-                    }
-                }
-                int expLimit = bigDecimalExponent+nDigits+nTrailZero;
-                if ( expOverflow || ( expVal > expLimit ) ){
-                    //
-                    // The intent here is to end up with
-                    // infinity or zero, as appropriate.
-                    // The reason for yielding such a small decExponent,
-                    // rather than something intuitive such as
-                    // expSign*Integer.MAX_VALUE, is that this value
-                    // is subject to further manipulation in
-                    // doubleValue() and floatValue(), and I don't want
-                    // it to be able to cause overflow there!
-                    // (The only way we can get into trouble here is for
-                    // really outrageous nDigits+nTrailZero, such as 2 billion. )
-                    //
-                    decExp = expSign*expLimit;
-                } else {
-                    // this should not overflow, since we tested
-                    // for expVal > (MAX+N), where N >= abs(decExp)
-                    decExp = decExp + expSign*expVal;
-                }
-
-                // if we saw something not a digit ( or end of string )
-                // after the [Ee][+-], without seeing any digits at all
-                // this is certainly an error. If we saw some digits,
-                // but then some trailing garbage, that might be ok.
-                // so we just fall through in that case.
-                // HUMBUG
-                if ( i == expAt )
-                    break parseNumber; // certainly bad
-            }
-            /*
-             * We parsed everything we could.
-             * If there are leftovers, then this is not good input!
-             */
-            if ( i < l &&
-                ((i != l - 1) ||
-                (in.charAt(i) != 'f' &&
-                 in.charAt(i) != 'F' &&
-                 in.charAt(i) != 'd' &&
-                 in.charAt(i) != 'D'))) {
-                break parseNumber; // go throw exception
-            }
-
-            return new FormattedFloatingDecimal( isNegative, decExp, digits, nDigits,  false, Integer.MAX_VALUE, Form.COMPATIBLE );
-        } catch ( StringIndexOutOfBoundsException e ){ }
-        throw new NumberFormatException("For input string: \"" + in + "\"");
-    }
-
     /*
      * Take a FormattedFloatingDecimal, which we presumably just scanned in,
      * and find out what its value is, as a double.
@@ -2035,548 +1767,4 @@
     private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
     private static final char notANumber[] = { 'N', 'a', 'N' };
     private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
-
-
-    /*
-     * Grammar is compatible with hexadecimal floating-point constants
-     * described in section 6.4.4.2 of the C99 specification.
-     */
-    private static Pattern hexFloatPattern = Pattern.compile(
-                   //1           234                   56                7                   8      9
-                    "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
-                    );
-
-    /*
-     * Convert string s to a suitable floating decimal; uses the
-     * double constructor and set the roundDir variable appropriately
-     * in case the value is later converted to a float.
-     */
-   static FormattedFloatingDecimal parseHexString(String s) {
-        // Verify string is a member of the hexadecimal floating-point
-        // string language.
-        Matcher m = hexFloatPattern.matcher(s);
-        boolean validInput = m.matches();
-
-        if (!validInput) {
-            // Input does not match pattern
-            throw new NumberFormatException("For input string: \"" + s + "\"");
-        } else { // validInput
-            /*
-             * We must isolate the sign, significand, and exponent
-             * fields.  The sign value is straightforward.  Since
-             * floating-point numbers are stored with a normalized
-             * representation, the significand and exponent are
-             * interrelated.
-             *
-             * After extracting the sign, we normalized the
-             * significand as a hexadecimal value, calculating an
-             * exponent adjust for any shifts made during
-             * normalization.  If the significand is zero, the
-             * exponent doesn't need to be examined since the output
-             * will be zero.
-             *
-             * Next the exponent in the input string is extracted.
-             * Afterwards, the significand is normalized as a *binary*
-             * value and the input value's normalized exponent can be
-             * computed.  The significand bits are copied into a
-             * double significand; if the string has more logical bits
-             * than can fit in a double, the extra bits affect the
-             * round and sticky bits which are used to round the final
-             * value.
-             */
-
-            //  Extract significand sign
-            String group1 = m.group(1);
-            double sign = (( group1 == null ) || group1.equals("+"))? 1.0 : -1.0;
-
-
-            //  Extract Significand magnitude
-            /*
-             * Based on the form of the significand, calculate how the
-             * binary exponent needs to be adjusted to create a
-             * normalized *hexadecimal* floating-point number; that
-             * is, a number where there is one nonzero hex digit to
-             * the left of the (hexa)decimal point.  Since we are
-             * adjusting a binary, not hexadecimal exponent, the
-             * exponent is adjusted by a multiple of 4.
-             *
-             * There are a number of significand scenarios to consider;
-             * letters are used in indicate nonzero digits:
-             *
-             * 1. 000xxxx       =>      x.xxx   normalized
-             *    increase exponent by (number of x's - 1)*4
-             *
-             * 2. 000xxx.yyyy =>        x.xxyyyy        normalized
-             *    increase exponent by (number of x's - 1)*4
-             *
-             * 3. .000yyy  =>   y.yy    normalized
-             *    decrease exponent by (number of zeros + 1)*4
-             *
-             * 4. 000.00000yyy => y.yy normalized
-             *    decrease exponent by (number of zeros to right of point + 1)*4
-             *
-             * If the significand is exactly zero, return a properly
-             * signed zero.
-             */
-
-            String significandString =null;
-            int signifLength = 0;
-            int exponentAdjust = 0;
-            {
-                int leftDigits  = 0; // number of meaningful digits to
-                                     // left of "decimal" point
-                                     // (leading zeros stripped)
-                int rightDigits = 0; // number of digits to right of
-                                     // "decimal" point; leading zeros
-                                     // must always be accounted for
-                /*
-                 * The significand is made up of either
-                 *
-                 * 1. group 4 entirely (integer portion only)
-                 *
-                 * OR
-                 *
-                 * 2. the fractional portion from group 7 plus any
-                 * (optional) integer portions from group 6.
-                 */
-                String group4;
-                if( (group4 = m.group(4)) != null) {  // Integer-only significand
-                    // Leading zeros never matter on the integer portion
-                    significandString = stripLeadingZeros(group4);
-                    leftDigits = significandString.length();
-                }
-                else {
-                    // Group 6 is the optional integer; leading zeros
-                    // never matter on the integer portion
-                    String group6 = stripLeadingZeros(m.group(6));
-                    leftDigits = group6.length();
-
-                    // fraction
-                    String group7 = m.group(7);
-                    rightDigits = group7.length();
-
-                    // Turn "integer.fraction" into "integer"+"fraction"
-                    significandString =
-                        ((group6 == null)?"":group6) + // is the null
-                        // check necessary?
-                        group7;
-                }
-
-                significandString = stripLeadingZeros(significandString);
-                signifLength  = significandString.length();
-
-                /*
-                 * Adjust exponent as described above
-                 */
-                if (leftDigits >= 1) {  // Cases 1 and 2
-                    exponentAdjust = 4*(leftDigits - 1);
-                } else {                // Cases 3 and 4
-                    exponentAdjust = -4*( rightDigits - signifLength + 1);
-                }
-
-                // If the significand is zero, the exponent doesn't
-                // matter; return a properly signed zero.
-
-                if (signifLength == 0) { // Only zeros in input
-                    return new FormattedFloatingDecimal(sign * 0.0);
-                }
-            }
-
-            //  Extract Exponent
-            /*
-             * Use an int to read in the exponent value; this should
-             * provide more than sufficient range for non-contrived
-             * inputs.  If reading the exponent in as an int does
-             * overflow, examine the sign of the exponent and
-             * significand to determine what to do.
-             */
-            String group8 = m.group(8);
-            boolean positiveExponent = ( group8 == null ) || group8.equals("+");
-            long unsignedRawExponent;
-            try {
-                unsignedRawExponent = Integer.parseInt(m.group(9));
-            }
-            catch (NumberFormatException e) {
-                // At this point, we know the exponent is
-                // syntactically well-formed as a sequence of
-                // digits.  Therefore, if an NumberFormatException
-                // is thrown, it must be due to overflowing int's
-                // range.  Also, at this point, we have already
-                // checked for a zero significand.  Thus the signs
-                // of the exponent and significand determine the
-                // final result:
-                //
-                //                      significand
-                //                      +               -
-                // exponent     +       +infinity       -infinity
-                //              -       +0.0            -0.0
-                return new FormattedFloatingDecimal(sign * (positiveExponent ?
-                                                   Double.POSITIVE_INFINITY : 0.0));
-            }
-
-            long rawExponent =
-                (positiveExponent ? 1L : -1L) * // exponent sign
-                unsignedRawExponent;            // exponent magnitude
-
-            // Calculate partially adjusted exponent
-            long exponent = rawExponent + exponentAdjust ;
-
-            // Starting copying non-zero bits into proper position in
-            // a long; copy explicit bit too; this will be masked
-            // later for normal values.
-
-            boolean round = false;
-            boolean sticky = false;
-            int bitsCopied=0;
-            int nextShift=0;
-            long significand=0L;
-            // First iteration is different, since we only copy
-            // from the leading significand bit; one more exponent
-            // adjust will be needed...
-
-            // IMPORTANT: make leadingDigit a long to avoid
-            // surprising shift semantics!
-            long leadingDigit = getHexDigit(significandString, 0);
-
-            /*
-             * Left shift the leading digit (53 - (bit position of
-             * leading 1 in digit)); this sets the top bit of the
-             * significand to 1.  The nextShift value is adjusted
-             * to take into account the number of bit positions of
-             * the leadingDigit actually used.  Finally, the
-             * exponent is adjusted to normalize the significand
-             * as a binary value, not just a hex value.
-             */
-            if (leadingDigit == 1) {
-                significand |= leadingDigit << 52;
-                nextShift = 52 - 4;
-                /* exponent += 0 */     }
-            else if (leadingDigit <= 3) { // [2, 3]
-                significand |= leadingDigit << 51;
-                nextShift = 52 - 5;
-                exponent += 1;
-            }
-            else if (leadingDigit <= 7) { // [4, 7]
-                significand |= leadingDigit << 50;
-                nextShift = 52 - 6;
-                exponent += 2;
-            }
-            else if (leadingDigit <= 15) { // [8, f]
-                significand |= leadingDigit << 49;
-                nextShift = 52 - 7;
-                exponent += 3;
-            } else {
-                throw new AssertionError("Result from digit converstion too large!");
-            }
-            // The preceding if-else could be replaced by a single
-            // code block based on the high-order bit set in
-            // leadingDigit.  Given leadingOnePosition,
-
-            // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
-            // nextShift = 52 - (3 + leadingOnePosition);
-            // exponent += (leadingOnePosition-1);
-
-
-            /*
-             * Now the exponent variable is equal to the normalized
-             * binary exponent.  Code below will make representation
-             * adjustments if the exponent is incremented after
-             * rounding (includes overflows to infinity) or if the
-             * result is subnormal.
-             */
-
-            // Copy digit into significand until the significand can't
-            // hold another full hex digit or there are no more input
-            // hex digits.
-            int i = 0;
-            for(i = 1;
-                i < signifLength && nextShift >= 0;
-                i++) {
-                long currentDigit = getHexDigit(significandString, i);
-                significand |= (currentDigit << nextShift);
-                nextShift-=4;
-            }
-
-            // After the above loop, the bulk of the string is copied.
-            // Now, we must copy any partial hex digits into the
-            // significand AND compute the round bit and start computing
-            // sticky bit.
-
-            if ( i < signifLength ) { // at least one hex input digit exists
-                long currentDigit = getHexDigit(significandString, i);
-
-                // from nextShift, figure out how many bits need
-                // to be copied, if any
-                switch(nextShift) { // must be negative
-                case -1:
-                    // three bits need to be copied in; can
-                    // set round bit
-                    significand |= ((currentDigit & 0xEL) >> 1);
-                    round = (currentDigit & 0x1L)  != 0L;
-                    break;
-
-                case -2:
-                    // two bits need to be copied in; can
-                    // set round and start sticky
-                    significand |= ((currentDigit & 0xCL) >> 2);
-                    round = (currentDigit &0x2L)  != 0L;
-                    sticky = (currentDigit & 0x1L) != 0;
-                    break;
-
-                case -3:
-                    // one bit needs to be copied in
-                    significand |= ((currentDigit & 0x8L)>>3);
-                    // Now set round and start sticky, if possible
-                    round = (currentDigit &0x4L)  != 0L;
-                    sticky = (currentDigit & 0x3L) != 0;
-                    break;
-
-                case -4:
-                    // all bits copied into significand; set
-                    // round and start sticky
-                    round = ((currentDigit & 0x8L) != 0);  // is top bit set?
-                    // nonzeros in three low order bits?
-                    sticky = (currentDigit & 0x7L) != 0;
-                    break;
-
-                default:
-                    throw new AssertionError("Unexpected shift distance remainder.");
-                    // break;
-                }
-
-                // Round is set; sticky might be set.
-
-                // For the sticky bit, it suffices to check the
-                // current digit and test for any nonzero digits in
-                // the remaining unprocessed input.
-                i++;
-                while(i < signifLength && !sticky) {
-                    currentDigit =  getHexDigit(significandString,i);
-                    sticky = sticky || (currentDigit != 0);
-                    i++;
-                }
-
-            }
-            // else all of string was seen, round and sticky are
-            // correct as false.
-
-
-            // Check for overflow and update exponent accordingly.
-
-            if (exponent > DoubleConsts.MAX_EXPONENT) {         // Infinite result
-                // overflow to properly signed infinity
-                return new FormattedFloatingDecimal(sign * Double.POSITIVE_INFINITY);
-            } else {  // Finite return value
-                if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
-                    exponent >= DoubleConsts.MIN_EXPONENT) {
-
-                    // The result returned in this block cannot be a
-                    // zero or subnormal; however after the
-                    // significand is adjusted from rounding, we could
-                    // still overflow in infinity.
-
-                    // AND exponent bits into significand; if the
-                    // significand is incremented and overflows from
-                    // rounding, this combination will update the
-                    // exponent correctly, even in the case of
-                    // Double.MAX_VALUE overflowing to infinity.
-
-                    significand = (( ((long)exponent +
-                                      (long)DoubleConsts.EXP_BIAS) <<
-                                     (DoubleConsts.SIGNIFICAND_WIDTH-1))
-                                   & DoubleConsts.EXP_BIT_MASK) |
-                        (DoubleConsts.SIGNIF_BIT_MASK & significand);
-
-                }  else  {  // Subnormal or zero
-                    // (exponent < DoubleConsts.MIN_EXPONENT)
-
-                    if (exponent < (DoubleConsts.MIN_SUB_EXPONENT -1 )) {
-                        // No way to round back to nonzero value
-                        // regardless of significand if the exponent is
-                        // less than -1075.
-                        return new FormattedFloatingDecimal(sign * 0.0);
-                    } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
-                        /*
-                         * Find bit position to round to; recompute
-                         * round and sticky bits, and shift
-                         * significand right appropriately.
-                         */
-
-                        sticky = sticky || round;
-                        round = false;
-
-                        // Number of bits of significand to preserve is
-                        // exponent - abs_min_exp +1
-                        // check:
-                        // -1075 +1074 + 1 = 0
-                        // -1023 +1074 + 1 = 52
-
-                        int bitsDiscarded = 53 -
-                            ((int)exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
-                        assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
-
-                        // What to do here:
-                        // First, isolate the new round bit
-                        round = (significand & (1L << (bitsDiscarded -1))) != 0L;
-                        if (bitsDiscarded > 1) {
-                            // create mask to update sticky bits; low
-                            // order bitsDiscarded bits should be 1
-                            long mask = ~((~0L) << (bitsDiscarded -1));
-                            sticky = sticky || ((significand & mask) != 0L ) ;
-                        }
-
-                        // Now, discard the bits
-                        significand = significand >> bitsDiscarded;
-
-                        significand = (( ((long)(DoubleConsts.MIN_EXPONENT -1) + // subnorm exp.
-                                          (long)DoubleConsts.EXP_BIAS) <<
-                                         (DoubleConsts.SIGNIFICAND_WIDTH-1))
-                                       & DoubleConsts.EXP_BIT_MASK) |
-                            (DoubleConsts.SIGNIF_BIT_MASK & significand);
-                    }
-                }
-
-                // The significand variable now contains the currently
-                // appropriate exponent bits too.
-
-                /*
-                 * Determine if significand should be incremented;
-                 * making this determination depends on the least
-                 * significant bit and the round and sticky bits.
-                 *
-                 * Round to nearest even rounding table, adapted from
-                 * table 4.7 in "Computer Arithmetic" by IsraelKoren.
-                 * The digit to the left of the "decimal" point is the
-                 * least significant bit, the digits to the right of
-                 * the point are the round and sticky bits
-                 *
-                 * Number       Round(x)
-                 * x0.00        x0.
-                 * x0.01        x0.
-                 * x0.10        x0.
-                 * x0.11        x1. = x0. +1
-                 * x1.00        x1.
-                 * x1.01        x1.
-                 * x1.10        x1. + 1
-                 * x1.11        x1. + 1
-                 */
-                boolean incremented = false;
-                boolean leastZero  = ((significand & 1L) == 0L);
-                if( (  leastZero  && round && sticky ) ||
-                    ((!leastZero) && round )) {
-                    incremented = true;
-                    significand++;
-                }
-
-                FormattedFloatingDecimal fd = new FormattedFloatingDecimal(FpUtils.rawCopySign(
-                                                                 Double.longBitsToDouble(significand),
-                                                                 sign));
-
-                /*
-                 * Set roundingDir variable field of fd properly so
-                 * that the input string can be properly rounded to a
-                 * float value.  There are two cases to consider:
-                 *
-                 * 1. rounding to double discards sticky bit
-                 * information that would change the result of a float
-                 * rounding (near halfway case between two floats)
-                 *
-                 * 2. rounding to double rounds up when rounding up
-                 * would not occur when rounding to float.
-                 *
-                 * For former case only needs to be considered when
-                 * the bits rounded away when casting to float are all
-                 * zero; otherwise, float round bit is properly set
-                 * and sticky will already be true.
-                 *
-                 * The lower exponent bound for the code below is the
-                 * minimum (normalized) subnormal exponent - 1 since a
-                 * value with that exponent can round up to the
-                 * minimum subnormal value and the sticky bit
-                 * information must be preserved (i.e. case 1).
-                 */
-                if ((exponent >= FloatConsts.MIN_SUB_EXPONENT-1) &&
-                    (exponent <= FloatConsts.MAX_EXPONENT ) ){
-                    // Outside above exponent range, the float value
-                    // will be zero or infinity.
-
-                    /*
-                     * If the low-order 28 bits of a rounded double
-                     * significand are 0, the double could be a
-                     * half-way case for a rounding to float.  If the
-                     * double value is a half-way case, the double
-                     * significand may have to be modified to round
-                     * the the right float value (see the stickyRound
-                     * method).  If the rounding to double has lost
-                     * what would be float sticky bit information, the
-                     * double significand must be incremented.  If the
-                     * double value's significand was itself
-                     * incremented, the float value may end up too
-                     * large so the increment should be undone.
-                     */
-                    if ((significand & 0xfffffffL) ==  0x0L) {
-                        // For negative values, the sign of the
-                        // roundDir is the same as for positive values
-                        // since adding 1 increasing the significand's
-                        // magnitude and subtracting 1 decreases the
-                        // significand's magnitude.  If neither round
-                        // nor sticky is true, the double value is
-                        // exact and no adjustment is required for a
-                        // proper float rounding.
-                        if( round || sticky) {
-                            if (leastZero) { // prerounding lsb is 0
-                                // If round and sticky were both true,
-                                // and the least significant
-                                // significand bit were 0, the rounded
-                                // significand would not have its
-                                // low-order bits be zero.  Therefore,
-                                // we only need to adjust the
-                                // significand if round XOR sticky is
-                                // true.
-                                if (round ^ sticky) {
-                                    fd.roundDir =  1;
-                                }
-                            }
-                            else { // prerounding lsb is 1
-                                // If the prerounding lsb is 1 and the
-                                // resulting significand has its
-                                // low-order bits zero, the significand
-                                // was incremented.  Here, we undo the
-                                // increment, which will ensure the
-                                // right guard and sticky bits for the
-                                // float rounding.
-                                if (round)
-                                    fd.roundDir =  -1;
-                            }
-                        }
-                    }
-                }
-
-                fd.fromHex = true;
-                return fd;
-            }
-        }
-    }
-
-    /**
-     * Return <code>s</code> with any leading zeros removed.
-     */
-    static String stripLeadingZeros(String s) {
-        return  s.replaceFirst("^0+", "");
-    }
-
-    /**
-     * Extract a hexadecimal digit from position <code>position</code>
-     * of string <code>s</code>.
-     */
-    static int getHexDigit(String s, int position) {
-        int value = Character.digit(s.charAt(position), 16);
-        if (value <= -1 || value >= 16) {
-            throw new AssertionError("Unxpected failure of digit converstion of " +
-                                     s.charAt(position));
-        }
-        return value;
-    }
-
-
 }
--- a/jdk/src/share/classes/sun/misc/JavaIOAccess.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/JavaIOAccess.java	Fri Apr 10 13:05:12 2009 -0700
@@ -29,6 +29,5 @@
 
 public interface JavaIOAccess {
     public Console console();
-    public Runnable consoleRestoreHook();
     public Charset charset();
 }
--- a/jdk/src/share/classes/sun/misc/JavaIODeleteOnExitAccess.java	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Sun designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- */
-
-package sun.misc;
-
-public interface JavaIODeleteOnExitAccess extends Runnable {
-    public void run();
-}
--- a/jdk/src/share/classes/sun/misc/JavaLangAccess.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/JavaLangAccess.java	Fri Apr 10 13:05:12 2009 -0700
@@ -54,4 +54,7 @@
 
     /** Set thread's blocker field. */
     void blockedOn(Thread t, Interruptible b);
+
+    /** register shutdown hook */
+    void registerShutdownHook(int slot, Runnable r);
 }
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java	Fri Apr 10 13:05:12 2009 -0700
@@ -44,7 +44,6 @@
     private static JavaUtilJarAccess javaUtilJarAccess;
     private static JavaLangAccess javaLangAccess;
     private static JavaIOAccess javaIOAccess;
-    private static JavaIODeleteOnExitAccess javaIODeleteOnExitAccess;
     private static JavaNetAccess javaNetAccess;
     private static JavaNioAccess javaNioAccess;
     private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
@@ -103,17 +102,6 @@
         return javaIOAccess;
     }
 
-    public static void setJavaIODeleteOnExitAccess(JavaIODeleteOnExitAccess jida) {
-        javaIODeleteOnExitAccess = jida;
-    }
-
-    public static JavaIODeleteOnExitAccess getJavaIODeleteOnExitAccess() {
-        if (javaIODeleteOnExitAccess == null) {
-            unsafe.ensureClassInitialized(File.class);
-        }
-        return javaIODeleteOnExitAccess;
-    }
-
     public static void setJavaIOFileDescriptorAccess(JavaIOFileDescriptorAccess jiofda) {
         javaIOFileDescriptorAccess = jiofda;
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/nio/cs/ArrayDecoder.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.nio.cs;
+
+/*
+ * FastPath byte[]->char[] decoder, REPLACE on malformed or
+ * unmappable input.
+ */
+
+public interface ArrayDecoder {
+    int decode(byte[] src, int off, int len, char[] dst);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/nio/cs/ArrayEncoder.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.nio.cs;
+
+/*
+ * FastPath char[]->byte[] encoder, REPLACE on malformed input or
+ * unmappable input.
+ */
+
+public interface ArrayEncoder {
+    int encode(char[] src, int off, int len, byte[] dst);
+}
--- a/jdk/src/share/classes/sun/nio/cs/ISO_8859_1.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/nio/cs/ISO_8859_1.java	Fri Apr 10 13:05:12 2009 -0700
@@ -23,9 +23,6 @@
  * have any questions.
  */
 
-/*
- */
-
 package sun.nio.cs;
 
 import java.nio.ByteBuffer;
@@ -34,10 +31,7 @@
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CoderResult;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.UnmappableCharacterException;
-
+import java.util.Arrays;
 
 class ISO_8859_1
     extends Charset
@@ -65,8 +59,8 @@
         return new Encoder(this);
     }
 
-    private static class Decoder extends CharsetDecoder {
-
+    private static class Decoder extends CharsetDecoder
+                                 implements ArrayDecoder {
         private Decoder(Charset cs) {
             super(cs, 1.0f, 1.0f);
         }
@@ -127,10 +121,18 @@
                 return decodeBufferLoop(src, dst);
         }
 
+        public int decode(byte[] src, int sp, int len, char[] dst) {
+            if (len > dst.length)
+                len = dst.length;
+            int dp = 0;
+            while (dp < len)
+                dst[dp++] = (char)(src[sp++] & 0xff);
+            return dp;
+        }
     }
 
-    private static class Encoder extends CharsetEncoder {
-
+    private static class Encoder extends CharsetEncoder
+                                 implements ArrayEncoder {
         private Encoder(Charset cs) {
             super(cs, 1.0f, 1.0f);
         }
@@ -139,6 +141,10 @@
             return c <= '\u00FF';
         }
 
+        public boolean isLegalReplacement(byte[] repl) {
+            return (repl.length == 1);  // we accept any byte value
+        }
+
         private final Surrogate.Parser sgp = new Surrogate.Parser();
 
         private CoderResult encodeArrayLoop(CharBuffer src,
@@ -208,5 +214,31 @@
                 return encodeBufferLoop(src, dst);
         }
 
+        private byte repl = (byte)'?';
+        protected void implReplaceWith(byte[] newReplacement) {
+            repl = newReplacement[0];
+        }
+
+        public int encode(char[] src, int sp, int len, byte[] dst) {
+            int dp = 0;
+            int sl = sp + Math.min(len, dst.length);
+            while (sp < sl) {
+                char c = src[sp++];
+                if (c <= '\u00FF') {
+                    dst[dp++] = (byte)c;
+                    continue;
+                }
+                if (Surrogate.isHigh(c) && sp < sl &&
+                    Surrogate.isLow(src[sp])) {
+                    if (len > dst.length) {
+                        sl++;
+                        len--;
+                    }
+                    sp++;
+                }
+                dst[dp++] = repl;
+            }
+            return dp;
+        }
     }
 }
--- a/jdk/src/share/classes/sun/nio/cs/SingleByte.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/nio/cs/SingleByte.java	Fri Apr 10 13:05:12 2009 -0700
@@ -32,6 +32,7 @@
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CoderResult;
+import java.util.Arrays;
 import static sun.nio.cs.CharsetMapping.*;
 
 public class SingleByte
@@ -45,7 +46,8 @@
         return cr;
     }
 
-    public static class Decoder extends CharsetDecoder {
+    final public static class Decoder extends CharsetDecoder
+                                      implements ArrayDecoder {
         private final char[] b2c;
 
         public Decoder(Charset cs, char[] b2c) {
@@ -108,9 +110,29 @@
         private final char decode(int b) {
             return b2c[b + 128];
         }
+
+        private char repl = '\uFFFD';
+        protected void implReplaceWith(String newReplacement) {
+            repl = newReplacement.charAt(0);
+        }
+
+        public int decode(byte[] src, int sp, int len, char[] dst) {
+            if (len > dst.length)
+                len = dst.length;
+            int dp = 0;
+            while (dp < len) {
+                dst[dp] = decode(src[sp++]);
+                if (dst[dp] == UNMAPPABLE_DECODING) {
+                    dst[dp] = repl;
+                }
+                dp++;
+            }
+            return dp;
+        }
     }
 
-    public static class Encoder extends CharsetEncoder {
+    final public static class Encoder extends CharsetEncoder
+                                      implements ArrayEncoder {
         private Surrogate.Parser sgp;
         private final char[] c2b;
         private final char[] c2bIndex;
@@ -125,6 +147,11 @@
             return encode(c) != UNMAPPABLE_ENCODING;
         }
 
+        public boolean isLegalReplacement(byte[] repl) {
+            return ((repl.length == 1 && repl[0] == (byte)'?') ||
+                    super.isLegalReplacement(repl));
+        }
+
         private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
             char[] sa = src.array();
             int sp = src.arrayOffset() + src.position();
@@ -200,6 +227,34 @@
                 return UNMAPPABLE_ENCODING;
             return c2b[index + (ch & 0xff)];
         }
+
+        private byte repl = (byte)'?';
+        protected void implReplaceWith(byte[] newReplacement) {
+            repl = newReplacement[0];
+        }
+
+        public int encode(char[] src, int sp, int len, byte[] dst) {
+            int dp = 0;
+            int sl = sp + Math.min(len, dst.length);
+            while (sp < sl) {
+                char c = src[sp++];
+                int b = encode(c);
+                if (b != UNMAPPABLE_ENCODING) {
+                    dst[dp++] = (byte)b;
+                    continue;
+                }
+                if (Surrogate.isHigh(c) && sp < sl &&
+                    Surrogate.isLow(src[sp])) {
+                    if (len > dst.length) {
+                        sl++;
+                        len--;
+                    }
+                    sp++;
+                }
+                dst[dp++] = repl;
+            }
+            return dp;
+        }
     }
 
     // init the c2b and c2bIndex tables from b2c.
--- a/jdk/src/share/classes/sun/nio/cs/US_ASCII.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/nio/cs/US_ASCII.java	Fri Apr 10 13:05:12 2009 -0700
@@ -31,10 +31,7 @@
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CoderResult;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.UnmappableCharacterException;
-
+import java.util.Arrays;
 
 public class US_ASCII
     extends Charset
@@ -61,7 +58,8 @@
         return new Encoder(this);
     }
 
-    private static class Decoder extends CharsetDecoder {
+    private static class Decoder extends CharsetDecoder
+                                 implements ArrayDecoder {
 
         private Decoder(Charset cs) {
             super(cs, 1.0f, 1.0f);
@@ -131,9 +129,27 @@
                 return decodeBufferLoop(src, dst);
         }
 
+        private char repl = '\uFFFD';
+        protected void implReplaceWith(String newReplacement) {
+            repl = newReplacement.charAt(0);
+        }
+
+        public int decode(byte[] src, int sp, int len, char[] dst) {
+            int dp = 0;
+            len = Math.min(len, dst.length);
+            while (dp < len) {
+                byte b = src[sp++];
+                if (b >= 0)
+                    dst[dp++] = (char)b;
+                else
+                    dst[dp++] = repl;
+            }
+            return dp;
+        }
     }
 
-    private static class Encoder extends CharsetEncoder {
+    private static class Encoder extends CharsetEncoder
+                                 implements ArrayEncoder {
 
         private Encoder(Charset cs) {
             super(cs, 1.0f, 1.0f);
@@ -143,8 +159,11 @@
             return c < 0x80;
         }
 
+        public boolean isLegalReplacement(byte[] repl) {
+            return (repl.length == 1 && repl[0] >= 0);
+        }
+
         private final Surrogate.Parser sgp = new Surrogate.Parser();
-
         private CoderResult encodeArrayLoop(CharBuffer src,
                                             ByteBuffer dst)
         {
@@ -213,6 +232,32 @@
                 return encodeBufferLoop(src, dst);
         }
 
+        private byte repl = (byte)'?';
+        protected void implReplaceWith(byte[] newReplacement) {
+            repl = newReplacement[0];
+        }
+
+        public int encode(char[] src, int sp, int len, byte[] dst) {
+            int dp = 0;
+            int sl = sp + Math.min(len, dst.length);
+            while (sp < sl) {
+                char c = src[sp++];
+                if (c < 0x80) {
+                    dst[dp++] = (byte)c;
+                    continue;
+                }
+                if (Surrogate.isHigh(c) && sp < sl &&
+                    Surrogate.isLow(src[sp])) {
+                    if (len > dst.length) {
+                        sl++;
+                        len--;
+                    }
+                    sp++;
+                }
+                dst[dp++] = repl;
+            }
+            return dp;
+        }
     }
 
 }
--- a/jdk/src/share/classes/sun/print/ServiceDialog.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/print/ServiceDialog.java	Fri Apr 10 13:05:12 2009 -0700
@@ -2149,55 +2149,51 @@
                         }
                     }
                 }
-
-                rbPortrait.setEnabled(pSupported);
-                rbLandscape.setEnabled(lSupported);
-                rbRevPortrait.setEnabled(rpSupported);
-                rbRevLandscape.setEnabled(rlSupported);
-
-                OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory);
-                if (or == null ||
-                    !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
-
-                    or = (OrientationRequested)psCurrent.getDefaultAttributeValue(orCategory);
-                    // need to validate if default is not supported
-                    if (!psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
-                        or = null;
-                        values =
-                            psCurrent.getSupportedAttributeValues(orCategory,
-                                                                  docFlavor,
-                                                                  asCurrent);
-                        if (values instanceof OrientationRequested[]) {
-                            OrientationRequested[] orValues =
-                                                (OrientationRequested[])values;
-                            if (orValues.length > 1) {
-                                // get the first in the list
-                                or = orValues[0];
-                            }
+            }
+
+
+            rbPortrait.setEnabled(pSupported);
+            rbLandscape.setEnabled(lSupported);
+            rbRevPortrait.setEnabled(rpSupported);
+            rbRevLandscape.setEnabled(rlSupported);
+
+            OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory);
+            if (or == null ||
+                !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
+
+                or = (OrientationRequested)psCurrent.getDefaultAttributeValue(orCategory);
+                // need to validate if default is not supported
+                if ((or != null) &&
+                   !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) {
+                    or = null;
+                    Object values =
+                        psCurrent.getSupportedAttributeValues(orCategory,
+                                                              docFlavor,
+                                                              asCurrent);
+                    if (values instanceof OrientationRequested[]) {
+                        OrientationRequested[] orValues =
+                                            (OrientationRequested[])values;
+                        if (orValues.length > 1) {
+                            // get the first in the list
+                            or = orValues[0];
                         }
                     }
-
-                    if (or == null) {
-                        or = OrientationRequested.PORTRAIT;
-                    }
-                    asCurrent.add(or);
+                }
+
+                if (or == null) {
+                    or = OrientationRequested.PORTRAIT;
                 }
-
-                if (or == OrientationRequested.PORTRAIT) {
-                    rbPortrait.setSelected(true);
-                } else if (or == OrientationRequested.LANDSCAPE) {
-                    rbLandscape.setSelected(true);
-                } else if (or == OrientationRequested.REVERSE_PORTRAIT) {
-                    rbRevPortrait.setSelected(true);
-                } else { // if (or == OrientationRequested.REVERSE_LANDSCAPE)
-                    rbRevLandscape.setSelected(true);
-                }
-                } else {
-                rbPortrait.setEnabled(pSupported);
-                rbLandscape.setEnabled(lSupported);
-                rbRevPortrait.setEnabled(rpSupported);
-                rbRevLandscape.setEnabled(rlSupported);
-
+                asCurrent.add(or);
+            }
+
+            if (or == OrientationRequested.PORTRAIT) {
+                rbPortrait.setSelected(true);
+            } else if (or == OrientationRequested.LANDSCAPE) {
+                rbLandscape.setSelected(true);
+            } else if (or == OrientationRequested.REVERSE_PORTRAIT) {
+                rbRevPortrait.setSelected(true);
+            } else { // if (or == OrientationRequested.REVERSE_LANDSCAPE)
+                rbRevLandscape.setSelected(true);
             }
         }
     }
--- a/jdk/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Fri Apr 10 13:05:12 2009 -0700
@@ -788,4 +788,16 @@
         for (int i = 0; i < length; i++)
             skipMemberValue(buf);
     }
+
+    /*
+     * This method converts the annotation map returned by the parseAnnotations()
+     * method to an array.  It is called by Field.getDeclaredAnnotations(),
+     * Method.getDeclaredAnnotations(), and Constructor.getDeclaredAnnotations().
+     * This avoids the reflection classes to load the Annotation class until
+     * it is needed.
+     */
+    private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
+    public static Annotation[] toArray(Map<Class, Annotation> annotations) {
+        return annotations.values().toArray(EMPTY_ANNOTATION_ARRAY);
+    }
 }
--- a/jdk/src/share/classes/sun/security/jgss/spnego/NegTokenInit.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/jgss/spnego/NegTokenInit.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -66,11 +66,11 @@
     private byte[] mechTypes = null;
     private Oid[] mechTypeList = null;
 
-    private byte[] reqFlags = null;
+    private BitArray reqFlags = null;
     private byte[] mechToken = null;
     private byte[] mechListMIC = null;
 
-    NegTokenInit(byte[] mechTypes, byte[] flags,
+    NegTokenInit(byte[] mechTypes, BitArray flags,
                 byte[] token, byte[] mechListMIC)
     {
         super(NEG_TOKEN_INIT_ID);
@@ -101,7 +101,7 @@
             // write context flags with CONTEXT 01
             if (reqFlags != null) {
                 DerOutputStream flags = new DerOutputStream();
-                flags.putBitString(reqFlags);
+                flags.putUnalignedBitString(reqFlags);
                 initToken.write(DerValue.createTag(DerValue.TAG_CONTEXT,
                                                 true, (byte) 0x01), flags);
             }
@@ -237,7 +237,7 @@
         return mechTypeList;
     }
 
-    byte[] getReqFlags() {
+    BitArray getReqFlags() {
         return reqFlags;
     }
 
--- a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,13 +53,6 @@
 
     private int state = STATE_NEW;
 
-    private static final int CHECKSUM_DELEG_FLAG    = 1;
-    private static final int CHECKSUM_MUTUAL_FLAG   = 2;
-    private static final int CHECKSUM_REPLAY_FLAG   = 4;
-    private static final int CHECKSUM_SEQUENCE_FLAG = 8;
-    private static final int CHECKSUM_CONF_FLAG     = 16;
-    private static final int CHECKSUM_INTEG_FLAG    = 32;
-
     /*
      * Optional features that the application can set and their default
      * values.
@@ -697,25 +690,17 @@
     /**
      * get the context flags
      */
-    private byte[] getContextFlags() {
-        int flags = 0;
+    private BitArray getContextFlags() {
+        BitArray out = new BitArray(7);
 
-        if (getCredDelegState())
-            flags |= CHECKSUM_DELEG_FLAG;
-        if (getMutualAuthState())
-            flags |= CHECKSUM_MUTUAL_FLAG;
-        if (getReplayDetState())
-            flags |= CHECKSUM_REPLAY_FLAG;
-        if (getSequenceDetState())
-            flags |= CHECKSUM_SEQUENCE_FLAG;
-        if (getIntegState())
-            flags |= CHECKSUM_INTEG_FLAG;
-        if (getConfState())
-            flags |= CHECKSUM_CONF_FLAG;
+        if (getCredDelegState()) out.set(0, true);
+        if (getMutualAuthState()) out.set(1, true);
+        if (getReplayDetState()) out.set(2, true);
+        if (getSequenceDetState()) out.set(3, true);
+        if (getConfState()) out.set(5, true);
+        if (getIntegState()) out.set(6, true);
 
-        byte[] temp = new byte[1];
-        temp[0] = (byte)(flags & 0xff);
-        return temp;
+        return out;
     }
 
     private void setContextFlags() {
--- a/jdk/src/share/classes/sun/security/krb5/Realm.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/Realm.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 package sun.security.pkcs11;
 
 import java.io.*;
+import java.lang.ref.*;
 import java.math.BigInteger;
 import java.util.*;
 
@@ -67,9 +68,6 @@
     // type of key, one of (PUBLIC, PRIVATE, SECRET)
     final String type;
 
-    // session in which the key was created, relevant for session objects
-    final Session session;
-
     // token instance
     final Token token;
 
@@ -85,10 +83,12 @@
     // flags indicating whether the key is a token object, sensitive, extractable
     final boolean tokenObject, sensitive, extractable;
 
+    // weak reference notification clean up for session keys
+    private final SessionKeyRef sessionKeyRef;
+
     P11Key(String type, Session session, long keyID, String algorithm,
             int keyLength, CK_ATTRIBUTE[] attributes) {
         this.type = type;
-        this.session = session;
         this.token = session.token;
         this.keyID = keyID;
         this.algorithm = algorithm;
@@ -111,7 +111,9 @@
         this.sensitive = sensitive;
         this.extractable = extractable;
         if (tokenObject == false) {
-            session.addObject();
+            sessionKeyRef = new SessionKeyRef(this, keyID, session);
+        } else {
+            sessionKeyRef = null;
         }
     }
 
@@ -236,24 +238,6 @@
         }
     }
 
-    protected void finalize() throws Throwable {
-        if (tokenObject || (token.isValid() == false)) {
-            super.finalize();
-            return;
-        }
-        Session newSession = null;
-        try {
-            newSession = token.getOpSession();
-            token.p11.C_DestroyObject(newSession.id(), keyID);
-        } catch (PKCS11Exception e) {
-            // ignore
-        } finally {
-            token.releaseSession(newSession);
-            session.removeObject();
-            super.finalize();
-        }
-    }
-
     private final static CK_ATTRIBUTE[] A0 = new CK_ATTRIBUTE[0];
 
     private static CK_ATTRIBUTE[] getAttributes(Session session, long keyID,
@@ -1055,5 +1039,65 @@
                 + "\n  parameters: " + params;
         }
     }
+}
 
+final class SessionKeyRef extends WeakReference<P11Key>
+    implements Comparable<SessionKeyRef> {
+    private static ReferenceQueue<P11Key> refQueue =
+        new ReferenceQueue<P11Key>();
+    private static Set<SessionKeyRef> refList =
+        Collections.synchronizedSortedSet(new TreeSet<SessionKeyRef>());
+
+    static ReferenceQueue<P11Key> referenceQueue() {
+        return refQueue;
+    }
+
+    static final private int MAX_ITERATIONS = 2;
+
+    private static void drainRefQueueBounded() {
+        int iterations = 0;
+        while (iterations < MAX_ITERATIONS) {
+            SessionKeyRef next = (SessionKeyRef) refQueue.poll();
+            if (next != null) next.dispose();
+            ++iterations;
+        }
+    }
+
+    // handle to the native key
+    private long keyID;
+    private Session session;
+
+    SessionKeyRef(P11Key key , long keyID, Session session) {
+        super(key, refQueue);
+        this.keyID = keyID;
+        this.session = session;
+        this.session.addObject();
+        refList.add(this);
+        // TBD: run at some interval and not every time?
+        drainRefQueueBounded();
+    }
+
+    void dispose() {
+        refList.remove(this);
+        if (session.token.isValid()) {
+            Session newSession = null;
+            try {
+                newSession = session.token.getOpSession();
+                session.token.p11.C_DestroyObject(newSession.id(), keyID);
+            } catch (PKCS11Exception e) {
+                // ignore
+            } finally {
+                session.token.releaseSession(newSession);
+                session.removeObject();
+            }
+        }
+    }
+
+    public int compareTo(SessionKeyRef other) {
+        if (this.keyID == other.keyID) {
+            return 0;
+        } else {
+            return (this.keyID < other.keyID) ? -1 : 1;
+        }
+    }
 }
--- a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -191,7 +191,9 @@
                 throw new InvalidKeyException
                                 ("Unwrap has to be used with private keys");
             }
-            encrypt = false;
+            // No further setup needed for C_Unwrap(). We'll initialize later
+            // if we can't use C_Unwrap().
+            return;
         } else {
             throw new InvalidKeyException("Unsupported mode: " + opmode);
         }
@@ -452,7 +454,7 @@
                 long keyID = token.p11.C_UnwrapKey(s.id(),
                         new CK_MECHANISM(mechanism), p11Key.keyID, wrappedKey,
                         attributes);
-                return P11Key.secretKey(session, keyID, algorithm, 48 << 3,
+                return P11Key.secretKey(s, keyID, algorithm, 48 << 3,
                         attributes);
             } catch (PKCS11Exception e) {
                 throw new InvalidKeyException("unwrap() failed", e);
@@ -461,6 +463,7 @@
             }
         }
         // XXX implement unwrap using C_Unwrap() for all keys
+        implInit(Cipher.DECRYPT_MODE, p11Key);
         if (wrappedKey.length > maxInputSize) {
             throw new InvalidKeyException("Key is too long for unwrapping");
         }
--- a/jdk/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Fri Apr 10 13:05:12 2009 -0700
@@ -151,7 +151,7 @@
                         session = token.getObjSession();
                         long newKeyID = token.p11.C_CopyObject(session.id(),
                                 p11Key.keyID, extraAttrs);
-                        p11Key = (P11Key) (P11Key.secretKey(p11Key.session,
+                        p11Key = (P11Key) (P11Key.secretKey(session,
                                 newKeyID, p11Key.algorithm, p11Key.keyLength,
                                 extraAttrs));
                     } catch (PKCS11Exception p11e) {
--- a/jdk/src/share/classes/sun/security/provider/SeedGenerator.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/provider/SeedGenerator.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1996-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -68,6 +68,9 @@
 import java.util.Properties;
 import java.util.Enumeration;
 import java.net.*;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Path;
+import java.util.Random;
 import sun.security.util.Debug;
 
 abstract class SeedGenerator {
@@ -180,10 +183,27 @@
 
                         // The temporary dir
                         File f = new File(p.getProperty("java.io.tmpdir"));
-                        String[] sa = f.list();
-                        for(int i = 0; i < sa.length; i++)
-                            md.update(sa[i].getBytes());
-
+                        int count = 0;
+                        DirectoryStream<Path> ds
+                                = f.toPath().newDirectoryStream();
+                        try {
+                            // We use a Random object to choose what file names
+                            // should be used. Otherwise on a machine with too
+                            // many files, the same first 1024 files always get
+                            // used. Any, We make sure the first 512 files are
+                            // always used.
+                            Random r = new Random();
+                            for (Path path: ds) {
+                                if (count < 512 || r.nextBoolean()) {
+                                    md.update(path.getName().toString().getBytes());
+                                }
+                                if (count++ > 1024) {
+                                    break;
+                                }
+                            }
+                        } finally {
+                            ds.close();
+                        }
                     } catch (Exception ex) {
                         md.update((byte)ex.hashCode());
                     }
--- a/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,8 +28,6 @@
 import java.io.*;
 import java.math.BigInteger;
 import java.security.*;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateFactory;
 import java.security.cert.CertPathValidatorException;
 import java.security.cert.CRLReason;
 import java.security.cert.X509Certificate;
@@ -335,7 +333,7 @@
 
             // Check whether the cert returned by the responder is trusted
             if (x509Certs != null && x509Certs[0] != null) {
-                X509Certificate cert = x509Certs[0];
+                X509CertImpl cert = x509Certs[0];
 
                 // First check if the cert matches the responder cert which
                 // was set locally.
@@ -344,8 +342,8 @@
 
                 // Next check if the cert was issued by the responder cert
                 // which was set locally.
-                } else if (cert.getIssuerDN().equals(
-                    responderCert.getSubjectDN())) {
+                } else if (cert.getIssuerX500Principal().equals(
+                    responderCert.getSubjectX500Principal())) {
 
                     // Check for the OCSPSigning key purpose
                     List<String> keyPurposes = cert.getExtendedKeyUsage();
@@ -360,6 +358,43 @@
                             "OCSP responses");
                     }
 
+                    // check the validity
+                    try {
+                        Date dateCheckedAgainst = params.getDate();
+                        if (dateCheckedAgainst == null) {
+                            cert.checkValidity();
+                        } else {
+                            cert.checkValidity(dateCheckedAgainst);
+                        }
+                    } catch (GeneralSecurityException e) {
+                        if (DEBUG != null) {
+                            DEBUG.println("Responder's certificate is not " +
+                                "within the validity period.");
+                        }
+                        throw new CertPathValidatorException(
+                            "Responder's certificate not within the " +
+                            "validity period");
+                    }
+
+                    // check for revocation
+                    //
+                    // A CA may specify that an OCSP client can trust a
+                    // responder for the lifetime of the responder's
+                    // certificate. The CA does so by including the
+                    // extension id-pkix-ocsp-nocheck.
+                    //
+                    Extension noCheck =
+                            cert.getExtension(PKIXExtensions.OCSPNoCheck_Id);
+                    if (noCheck != null) {
+                        if (DEBUG != null) {
+                            DEBUG.println("Responder's certificate includes " +
+                                "the extension id-pkix-ocsp-nocheck.");
+                        }
+                    } else {
+                        // we should do the revocating checking of the
+                        // authorized responder in a future update.
+                    }
+
                     // verify the signature
                     try {
                         cert.verify(responderCert.getPublicKey());
@@ -369,6 +404,14 @@
                     } catch (GeneralSecurityException e) {
                         responderCert = null;
                     }
+                } else {
+                    if (DEBUG != null) {
+                        DEBUG.println("Responder's certificate is not " +
+                            "authorized to sign OCSP responses.");
+                    }
+                    throw new CertPathValidatorException(
+                        "Responder's certificate not authorized to sign " +
+                        "OCSP responses");
                 }
             }
 
--- a/jdk/src/share/classes/sun/security/provider/certpath/PKIXMasterCertPathValidator.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/PKIXMasterCertPathValidator.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -143,11 +143,15 @@
                     }
 
                 } catch (CertPathValidatorException cpve) {
-                    // Throw the saved OCSP exception
-                    // (when the CRL check has also failed)
+                    // Throw the saved OCSP exception unless the CRL
+                    // checker has determined that the cert is revoked
                     if (ocspCause != null &&
-                        currChecker instanceof CrlRevocationChecker) {
-                        throw ocspCause;
+                            currChecker instanceof CrlRevocationChecker) {
+                        if (cpve.getReason() == BasicReason.REVOKED) {
+                            throw cpve;
+                        } else {
+                            throw ocspCause;
+                        }
                     }
                     /*
                      * Handle failover from OCSP to CRLs
--- a/jdk/src/share/classes/sun/security/tools/KeyTool.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java	Fri Apr 10 13:05:12 2009 -0700
@@ -875,6 +875,18 @@
             if (filename != null) {
                 inStream = new FileInputStream(filename);
             }
+            // Read the full stream before feeding to X509Factory,
+            // otherwise, keytool -gencert | keytool -importcert
+            // might not work properly, since -gencert is slow
+            // and there's no data in the pipe at the beginning.
+            ByteArrayOutputStream bout = new ByteArrayOutputStream();
+            byte[] b = new byte[4096];
+            while (true) {
+                int len = inStream.read(b);
+                if (len < 0) break;
+                bout.write(b, 0, len);
+            }
+            inStream = new ByteArrayInputStream(bout.toByteArray());
             try {
                 String importAlias = (alias!=null)?alias:keyAlias;
                 if (keyStore.entryInstanceOf(importAlias, KeyStore.PrivateKeyEntry.class)) {
@@ -1060,8 +1072,8 @@
 
         X509CertInfo info = new X509CertInfo();
         info.set(X509CertInfo.VALIDITY, interval);
-        info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber
-                 ((int)(firstDate.getTime()/1000)));
+        info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
+                    new java.util.Random().nextInt() & 0x7fffffff));
         info.set(X509CertInfo.VERSION,
                      new CertificateVersion(CertificateVersion.V3));
         info.set(X509CertInfo.ALGORITHM_ID,
@@ -1910,7 +1922,9 @@
             ObjectIdentifier oid = attr.getAttributeId();
             if (oid.equals(PKCS9Attribute.EXTENSION_REQUEST_OID)) {
                 CertificateExtensions exts = (CertificateExtensions)attr.getAttributeValue();
-                printExtensions(rb.getString("Extension Request:"), exts, out);
+                if (exts != null) {
+                    printExtensions(rb.getString("Extension Request:"), exts, out);
+                }
             } else {
                 out.println(attr.getAttributeId());
                 out.println(attr.getAttributeValue());
@@ -2107,8 +2121,8 @@
         certInfo.set(X509CertInfo.VALIDITY, interval);
 
         // Make new serial number
-        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber
-                     ((int)(firstDate.getTime()/1000)));
+        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
+                    new java.util.Random().nextInt() & 0x7fffffff));
 
         // Set owner and issuer fields
         X500Name owner;
@@ -2495,7 +2509,9 @@
                                                            X509CertImpl.INFO);
             CertificateExtensions exts = (CertificateExtensions)
                     certInfo.get(X509CertInfo.EXTENSIONS);
-            printExtensions(rb.getString("Extensions: "), exts, out);
+            if (exts != null) {
+                printExtensions(rb.getString("Extensions: "), exts, out);
+            }
         }
     }
 
--- a/jdk/src/share/classes/sun/security/x509/AuthorityInfoAccessExtension.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/x509/AuthorityInfoAccessExtension.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java	Fri Apr 10 13:05:12 2009 -0700
@@ -265,8 +265,8 @@
             // Add all mandatory attributes
             info.set(X509CertInfo.VERSION,
                      new CertificateVersion(CertificateVersion.V3));
-            info.set(X509CertInfo.SERIAL_NUMBER,
-                 new CertificateSerialNumber((int)(firstDate.getTime()/1000)));
+            info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
+                    new java.util.Random().nextInt() & 0x7fffffff));
             AlgorithmId algID = issuer.getAlgorithmId();
             info.set(X509CertInfo.ALGORITHM_ID,
                      new CertificateAlgorithmId(algID));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/x509/OCSPNoCheckExtension.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.security.x509;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Enumeration;
+
+import sun.security.util.*;
+
+/**
+ * Represent the OCSP NoCheck Extension from RFC2560.
+ * <p>
+ * A CA may specify that an OCSP client can trust a responder for the
+ * lifetime of the responder's certificate. The CA does so by including
+ * the extension id-pkix-ocsp-nocheck. This SHOULD be a non-critical
+ * extension. The value of the extension should be NULL. CAs issuing
+ * such a certificate should realized that a compromise of the
+ * responder's key, is as serious as the compromise of a CA key used to
+ * sign CRLs, at least for the validity period of this certificate. CA's
+ * may choose to issue this type of certificate with a very short
+ * lifetime and renew it frequently.
+ * <pre>
+ * id-pkix-ocsp-nocheck OBJECT IDENTIFIER ::= { id-pkix-ocsp 5 }
+ * </pre>
+ *
+ * @author Xuelei Fan
+ * @see Extension
+ * @see CertAttrSet
+ */
+public class OCSPNoCheckExtension extends Extension
+    implements CertAttrSet<String> {
+
+    /**
+     * Identifier for this attribute, to be used with the
+     * get, set, delete methods of Certificate, x509 type.
+     */
+    public static final String IDENT =
+                         "x509.info.extensions.OCSPNoCheck";
+    /**
+     * Attribute names.
+     */
+    public static final String NAME = "OCSPNoCheck";
+
+    /**
+     * Create a OCSPNoCheckExtension
+     */
+    public OCSPNoCheckExtension() throws IOException {
+        this.extensionId = PKIXExtensions.OCSPNoCheck_Id;
+        this.critical = false;
+        this.extensionValue = new byte[0];
+    }
+
+    /**
+     * Create the extension from the passed DER encoded value.
+     *
+     * @param critical true if the extension is to be treated as critical.
+     * @param value an array of DER encoded bytes of the actual value.
+     * @exception IOException on error.
+     */
+    public OCSPNoCheckExtension(Boolean critical, Object value)
+        throws IOException {
+
+        this.extensionId = PKIXExtensions.OCSPNoCheck_Id;
+        this.critical = critical.booleanValue();
+
+        // the value should be null, just ignore it here.
+        this.extensionValue = new byte[0];
+    }
+
+    /**
+     * Set the attribute value.
+     */
+    public void set(String name, Object obj) throws IOException {
+        throw new IOException("No attribute is allowed by " +
+                        "CertAttrSet:OCSPNoCheckExtension.");
+    }
+
+    /**
+     * Get the attribute value.
+     */
+    public Object get(String name) throws IOException {
+        throw new IOException("No attribute is allowed by " +
+                        "CertAttrSet:OCSPNoCheckExtension.");
+    }
+
+    /**
+     * Delete the attribute value.
+     */
+    public void delete(String name) throws IOException {
+        throw new IOException("No attribute is allowed by " +
+                        "CertAttrSet:OCSPNoCheckExtension.");
+    }
+
+    /**
+     * Return an enumeration of names of attributes existing within this
+     * attribute.
+     */
+    public Enumeration<String> getElements() {
+        return (new AttributeNameEnumeration()).elements();
+    }
+
+    /**
+     * Return the name of this attribute.
+     */
+    public String getName() {
+        return NAME;
+    }
+}
--- a/jdk/src/share/classes/sun/security/x509/OIDMap.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/x509/OIDMap.java	Fri Apr 10 13:05:12 2009 -0700
@@ -100,6 +100,8 @@
                                         DeltaCRLIndicatorExtension.NAME;
     private static final String FRESHEST_CRL = ROOT + "." +
                                         FreshestCRLExtension.NAME;
+    private static final String OCSPNOCHECK = ROOT + "." +
+                                        OCSPNoCheckExtension.NAME;
 
     private static final int NetscapeCertType_data[] =
         { 2, 16, 840, 1, 113730, 1, 1 };
@@ -161,6 +163,8 @@
                     "sun.security.x509.DeltaCRLIndicatorExtension");
         addInternal(FRESHEST_CRL, PKIXExtensions.FreshestCRL_Id,
                     "sun.security.x509.FreshestCRLExtension");
+        addInternal(OCSPNOCHECK, PKIXExtensions.OCSPNoCheck_Id,
+                    "sun.security.x509.OCSPNoCheckExtension");
     }
 
     /**
--- a/jdk/src/share/classes/sun/security/x509/PKIXExtensions.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/classes/sun/security/x509/PKIXExtensions.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,6 +74,8 @@
     private static final int AuthInfoAccess_data [] = { 1, 3, 6, 1, 5, 5, 7, 1, 1};
     private static final int SubjectInfoAccess_data [] = { 1, 3, 6, 1, 5, 5, 7, 1, 11};
     private static final int FreshestCRL_data [] = { 2, 5, 29, 46 };
+    private static final int OCSPNoCheck_data [] = { 1, 3, 6, 1, 5, 5, 7,
+                                                    48, 1, 5};
 
     /**
      * Identifies the particular public key used to sign the certificate.
@@ -216,6 +218,12 @@
      */
     public static final ObjectIdentifier FreshestCRL_Id;
 
+    /**
+     * Identifies the OCSP client can trust the responder for the
+     * lifetime of the responder's certificate.
+     */
+    public static final ObjectIdentifier OCSPNoCheck_Id;
+
     static {
         AuthorityKey_Id = ObjectIdentifier.newInternal(AuthorityKey_data);
         SubjectKey_Id   = ObjectIdentifier.newInternal(SubjectKey_data);
@@ -257,5 +265,6 @@
         SubjectInfoAccess_Id =
             ObjectIdentifier.newInternal(SubjectInfoAccess_data);
         FreshestCRL_Id = ObjectIdentifier.newInternal(FreshestCRL_data);
+        OCSPNoCheck_Id = ObjectIdentifier.newInternal(OCSPNoCheck_data);
     }
 }
--- a/jdk/src/share/lib/security/java.policy	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/lib/security/java.policy	Fri Apr 10 13:05:12 2009 -0700
@@ -15,7 +15,8 @@
 	// It is strongly recommended that you either remove this permission
 	// from this policy file or further restrict it to code sources
 	// that you specify, because Thread.stop() is potentially unsafe.
-	// See "http://java.sun.com/notes" for more information.
+	// See the API specification of java.lang.Thread.stop() for more 
+        // information.
 	permission java.lang.RuntimePermission "stopThread";
 
 	// allows anyone to listen on un-privileged ports
--- a/jdk/src/share/native/java/util/zip/zip_util.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/java/util/zip/zip_util.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/native/java/util/zip/zip_util.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/java/util/zip/zip_util.h	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/native/sun/awt/image/dither.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/awt/image/dither.c	Fri Apr 10 13:05:12 2009 -0700
@@ -169,6 +169,7 @@
     int cubesize = cube_dim * cube_dim * cube_dim;
     unsigned char *useFlags;
     unsigned char *newILut = (unsigned char*)malloc(cubesize);
+    int cmap_mid = (cmap_len >> 1) + (cmap_len & 0x1);
     if (newILut) {
 
       useFlags = (unsigned char *)calloc(cubesize, 1);
@@ -188,7 +189,7 @@
         currentState.iLUT           = newILut;
 
         currentState.rgb = (unsigned short *)
-                                malloc(256 * sizeof(unsigned short));
+                                malloc(cmap_len * sizeof(unsigned short));
         if (currentState.rgb == NULL) {
             free(newILut);
             free(useFlags);
@@ -199,7 +200,7 @@
         }
 
         currentState.indices = (unsigned char *)
-                                malloc(256 * sizeof(unsigned char));
+                                malloc(cmap_len * sizeof(unsigned char));
         if (currentState.indices == NULL) {
             free(currentState.rgb);
             free(newILut);
@@ -210,18 +211,18 @@
             return NULL;
         }
 
-        for (i = 0; i < 128; i++) {
+        for (i = 0; i < cmap_mid; i++) {
             unsigned short rgb;
             int pixel = cmap[i];
             rgb = (pixel & 0x00f80000) >> 9;
             rgb |= (pixel & 0x0000f800) >> 6;
             rgb |=  (pixel & 0xf8) >> 3;
             INSERTNEW(currentState, rgb, i);
-            pixel = cmap[255-i];
+            pixel = cmap[cmap_len - i - 1];
             rgb = (pixel & 0x00f80000) >> 9;
             rgb |= (pixel & 0x0000f800) >> 6;
             rgb |=  (pixel & 0xf8) >> 3;
-            INSERTNEW(currentState, rgb, 255-i);
+            INSERTNEW(currentState, rgb, cmap_len - i - 1);
         }
 
         if (!recurseLevel(&currentState)) {
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c	Fri Apr 10 13:05:12 2009 -0700
@@ -396,7 +396,7 @@
     data->jpegObj = cinfo;
     cinfo->client_data = data;
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("new structures: data is %p, cinfo is %p\n", data, cinfo);
 #endif
 
@@ -673,7 +673,7 @@
     j_decompress_ptr decomp;
 
     qlen = (*env)->GetArrayLength(env, qtables);
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("in setQTables, qlen = %d, write is %d\n", qlen, write);
 #endif
     for (i = 0; i < qlen; i++) {
@@ -876,7 +876,7 @@
         return FALSE;
     }
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("Filling input buffer, remaining skip is %ld, ",
            sb->remaining_skip);
     printf("Buffer length is %d\n", sb->bufferLength);
@@ -906,7 +906,7 @@
             cinfo->err->error_exit((j_common_ptr) cinfo);
     }
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
       printf("Buffer filled. ret = %d\n", ret);
 #endif
     /*
@@ -917,7 +917,7 @@
      */
     if (ret <= 0) {
         jobject reader = data->imageIOobj;
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
       printf("YO! Early EOI! ret = %d\n", ret);
 #endif
         RELEASE_ARRAYS(env, data, src->next_input_byte);
@@ -1216,21 +1216,24 @@
 {
     jpeg_saved_marker_ptr marker;
     int num_markers = 0;
+    int num_found_markers = 0;
     int seq_no;
     JOCTET *icc_data;
+    JOCTET *dst_ptr;
     unsigned int total_length;
 #define MAX_SEQ_NO  255         // sufficient since marker numbers are bytes
-    char marker_present[MAX_SEQ_NO+1];    // 1 if marker found
-    unsigned int data_length[MAX_SEQ_NO+1]; // size of profile data in marker
-    unsigned int data_offset[MAX_SEQ_NO+1]; // offset for data in marker
+    jpeg_saved_marker_ptr icc_markers[MAX_SEQ_NO + 1];
+    int first;         // index of the first marker in the icc_markers array
+    int last;          // index of the last marker in the icc_markers array
     jbyteArray data = NULL;
 
     /* This first pass over the saved markers discovers whether there are
      * any ICC markers and verifies the consistency of the marker numbering.
      */
 
-    for (seq_no = 1; seq_no <= MAX_SEQ_NO; seq_no++)
-        marker_present[seq_no] = 0;
+    for (seq_no = 0; seq_no <= MAX_SEQ_NO; seq_no++)
+        icc_markers[seq_no] = NULL;
+
 
     for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
         if (marker_is_icc(marker)) {
@@ -1242,37 +1245,58 @@
                 return NULL;
             }
             seq_no = GETJOCTET(marker->data[12]);
-            if (seq_no <= 0 || seq_no > num_markers) {
+
+            /* Some third-party tools produce images with profile chunk
+             * numeration started from zero. It is inconsistent with ICC
+             * spec, but seems to be recognized by majority of image
+             * processing tools, so we should be more tolerant to this
+             * departure from the spec.
+             */
+            if (seq_no < 0 || seq_no > num_markers) {
                 JNU_ThrowByName(env, "javax/imageio/IIOException",
                      "Invalid icc profile: bad sequence number");
                 return NULL;
             }
-            if (marker_present[seq_no]) {
+            if (icc_markers[seq_no] != NULL) {
                 JNU_ThrowByName(env, "javax/imageio/IIOException",
                      "Invalid icc profile: duplicate sequence numbers");
                 return NULL;
             }
-            marker_present[seq_no] = 1;
-            data_length[seq_no] = marker->data_length - ICC_OVERHEAD_LEN;
+            icc_markers[seq_no] = marker;
+            num_found_markers ++;
         }
     }
 
     if (num_markers == 0)
         return NULL;  // There is no profile
 
-    /* Check for missing markers, count total space needed,
-     * compute offset of each marker's part of the data.
+    if (num_markers != num_found_markers) {
+        JNU_ThrowByName(env, "javax/imageio/IIOException",
+                        "Invalid icc profile: invalid number of icc markers");
+        return NULL;
+    }
+
+    first = icc_markers[0] ? 0 : 1;
+    last = num_found_markers + first;
+
+    /* Check for missing markers, count total space needed.
      */
-
     total_length = 0;
-    for (seq_no = 1; seq_no <= num_markers; seq_no++) {
-        if (marker_present[seq_no] == 0) {
+    for (seq_no = first; seq_no < last; seq_no++) {
+        unsigned int length;
+        if (icc_markers[seq_no] == NULL) {
             JNU_ThrowByName(env, "javax/imageio/IIOException",
                  "Invalid icc profile: missing sequence number");
             return NULL;
         }
-        data_offset[seq_no] = total_length;
-        total_length += data_length[seq_no];
+        /* check the data length correctness */
+        length = icc_markers[seq_no]->data_length;
+        if (ICC_OVERHEAD_LEN > length || length > MAX_BYTES_IN_MARKER) {
+            JNU_ThrowByName(env, "javax/imageio/IIOException",
+                 "Invalid icc profile: invalid data length");
+            return NULL;
+        }
+        total_length += (length - ICC_OVERHEAD_LEN);
     }
 
     if (total_length <= 0) {
@@ -1301,19 +1325,14 @@
     }
 
     /* and fill it in */
-    for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
-        if (marker_is_icc(marker)) {
-            JOCTET FAR *src_ptr;
-            JOCTET *dst_ptr;
-            unsigned int length;
-            seq_no = GETJOCTET(marker->data[12]);
-            dst_ptr = icc_data + data_offset[seq_no];
-            src_ptr = marker->data + ICC_OVERHEAD_LEN;
-            length = data_length[seq_no];
-            while (length--) {
-                *dst_ptr++ = *src_ptr++;
-            }
-        }
+    dst_ptr = icc_data;
+    for (seq_no = first; seq_no < last; seq_no++) {
+        JOCTET FAR *src_ptr = icc_markers[seq_no]->data + ICC_OVERHEAD_LEN;
+        unsigned int length =
+            icc_markers[seq_no]->data_length - ICC_OVERHEAD_LEN;
+
+        memcpy(dst_ptr, src_ptr, length);
+        dst_ptr += length;
     }
 
     /* finally, unpin the array */
@@ -1530,6 +1549,7 @@
     j_decompress_ptr cinfo;
     struct jpeg_source_mgr *src;
     sun_jpeg_error_ptr jerr;
+    jbyteArray profileData = NULL;
 
     if (data == NULL) {
         JNU_ThrowByName(env,
@@ -1557,7 +1577,7 @@
         return retval;
     }
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("In readImageHeader, data is %p cinfo is %p\n", data, cinfo);
     printf("clearFirst is %d\n", clearFirst);
 #endif
@@ -1584,7 +1604,7 @@
     if (ret == JPEG_HEADER_TABLES_ONLY) {
         retval = JNI_TRUE;
         imageio_term_source(cinfo);  // Pushback remaining buffer contents
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
         printf("just read tables-only image; q table 0 at %p\n",
                cinfo->quant_tbl_ptrs[0]);
 #endif
@@ -1691,6 +1711,14 @@
             }
         }
         RELEASE_ARRAYS(env, data, src->next_input_byte);
+
+        /* read icc profile data */
+        profileData = read_icc_profile(env, cinfo);
+
+        if ((*env)->ExceptionCheck(env)) {
+            return retval;
+        }
+
         (*env)->CallVoidMethod(env, this,
                                JPEGImageReader_setImageDataID,
                                cinfo->image_width,
@@ -1698,7 +1726,7 @@
                                cinfo->jpeg_color_space,
                                cinfo->out_color_space,
                                cinfo->num_components,
-                               read_icc_profile(env, cinfo));
+                               profileData);
         if (reset) {
             jpeg_abort_decompress(cinfo);
         }
@@ -1827,7 +1855,7 @@
 
     (*env)->ReleaseIntArrayElements(env, srcBands, body, JNI_ABORT);
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("---- in reader.read ----\n");
     printf("numBands is %d\n", numBands);
     printf("bands array: ");
@@ -2487,7 +2515,7 @@
 
     data->streamBuf.suspendable = FALSE;
     if (qtables != NULL) {
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
         printf("in writeTables: qtables not NULL\n");
 #endif
         setQTables(env, (j_common_ptr) cinfo, qtables, TRUE);
@@ -2763,7 +2791,7 @@
 
     cinfo->restart_interval = restartInterval;
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
     printf("writer setup complete, starting compressor\n");
 #endif
 
@@ -2812,13 +2840,13 @@
             for (i = 0; i < numBands; i++) {
                 if (scale !=NULL && scale[i] != NULL) {
                     *out++ = scale[i][*(in+i)];
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
                     if (in == data->pixelBuf.buf.bp){ // Just the first pixel
                         printf("in %d -> out %d, ", *(in+i), *(out-i-1));
                     }
 #endif
 
-#ifdef DEBUG
+#ifdef DEBUG_IIO_JPEG
                     if (in == data->pixelBuf.buf.bp){ // Just the first pixel
                         printf("\n");
                     }
--- a/jdk/src/share/native/sun/font/freetypeScaler.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/font/freetypeScaler.c	Fri Apr 10 13:05:12 2009 -0700
@@ -394,12 +394,14 @@
     scalerInfo->env = env;
     scalerInfo->font2D = font2D;
 
-    FT_Set_Transform(scalerInfo->face, &context->transform, NULL);
+    if (context != NULL) {
+        FT_Set_Transform(scalerInfo->face, &context->transform, NULL);
 
-    errCode = FT_Set_Char_Size(scalerInfo->face, 0, context->ptsz, 72, 72);
+        errCode = FT_Set_Char_Size(scalerInfo->face, 0, context->ptsz, 72, 72);
 
-    if (errCode == 0) {
-        errCode = FT_Activate_Size(scalerInfo->face->size);
+        if (errCode == 0) {
+            errCode = FT_Activate_Size(scalerInfo->face->size);
+        }
     }
 
     return errCode;
@@ -885,6 +887,14 @@
         JNIEnv *env, jobject scaler, jlong pScaler) {
     FTScalerInfo* scalerInfo = (FTScalerInfo *) jlong_to_ptr(pScaler);
 
+    /* Freetype functions *may* cause callback to java
+       that can use cached values. Make sure our cache is up to date.
+       NB: scaler context is not important at this point, can use NULL. */
+    int errCode = setupFTContext(env, scaler, scalerInfo, NULL);
+    if (errCode) {
+        return;
+    }
+
     freeNativeResources(env, scalerInfo);
 }
 
@@ -932,12 +942,21 @@
         JNIEnv *env, jobject scaler, jlong pScaler, jchar charCode) {
 
     FTScalerInfo* scalerInfo = (FTScalerInfo *) jlong_to_ptr(pScaler);
+    int errCode;
 
     if (scaler == NULL || scalerInfo->face == NULL) { /* bad/null scaler */
         invalidateJavaScaler(env, scaler, scalerInfo);
         return 0;
     }
 
+    /* Freetype functions *may* cause callback to java
+       that can use cached values. Make sure our cache is up to date.
+       Scaler context is not important here, can use NULL. */
+    errCode = setupFTContext(env, scaler, scalerInfo, NULL);
+    if (errCode) {
+        return 0;
+    }
+
     return FT_Get_Char_Index(scalerInfo->face, charCode);
 }
 
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Fri Apr 10 13:05:12 2009 -0700
@@ -30,6 +30,41 @@
 #include "Disposer.h"
 #include "lcms.h"
 
+
+#define ALIGNLONG(x) (((x)+3) & ~(3))         // Aligns to DWORD boundary
+
+#ifdef USE_BIG_ENDIAN
+#define AdjustEndianess32(a)
+#else
+
+static
+void AdjustEndianess32(LPBYTE pByte)
+{
+    BYTE temp1;
+    BYTE temp2;
+
+    temp1 = *pByte++;
+    temp2 = *pByte++;
+    *(pByte-1) = *pByte;
+    *pByte++ = temp2;
+    *(pByte-3) = *pByte;
+    *pByte = temp1;
+}
+
+#endif
+
+// Transports to properly encoded values - note that icc profiles does use
+// big endian notation.
+
+static
+icInt32Number TransportValue32(icInt32Number Value)
+{
+    icInt32Number Temp = Value;
+
+    AdjustEndianess32((LPBYTE) &Temp);
+    return Temp;
+}
+
 #define SigMake(a,b,c,d) \
                     ( ( ((int) ((unsigned char) (a))) << 24) | \
                       ( ((int) ((unsigned char) (b))) << 16) | \
@@ -182,6 +217,8 @@
 
     sProf.pf = cmsOpenProfileFromMem((LPVOID)dataArray, (DWORD) dataSize);
 
+    (*env)->ReleaseByteArrayElements (env, data, dataArray, 0);
+
     if (sProf.pf == NULL) {
         JNU_ThrowIllegalArgumentException(env, "Invalid profile data");
     }
@@ -337,6 +374,10 @@
     return;
 }
 
+// Modify data for a tag in a profile
+LCMSBOOL LCMSEXPORT _cmsModifyTagData(cmsHPROFILE hProfile,
+                                 icTagSignature sig, void *data, size_t size);
+
 /*
  * Class:     sun_java2d_cmm_lcms_LCMS
  * Method:    setTagData
@@ -345,7 +386,23 @@
 JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagData
   (JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
 {
-    fprintf(stderr, "setTagData operation is not implemented");
+    cmsHPROFILE profile;
+    storeID_t sProf;
+    jbyte* dataArray;
+    int tagSize;
+
+    if (tagSig == SigHead) {
+        J2dRlsTraceLn(J2D_TRACE_ERROR, "LCMS_setTagData on icSigHead not "
+                      "permitted");
+        return;
+    }
+
+    sProf.j = id;
+    profile = (cmsHPROFILE) sProf.pf;
+    dataArray = (*env)->GetByteArrayElements(env, data, 0);
+    tagSize =(*env)->GetArrayLength(env, data);
+    _cmsModifyTagData(profile, (icTagSignature) tagSig, dataArray, tagSize);
+    (*env)->ReleaseByteArrayElements(env, data, dataArray, 0);
 }
 
 void* getILData (JNIEnv *env, jobject img, jint* pDataType,
@@ -507,3 +564,174 @@
 
     PF_ID_fID = (*env)->GetFieldID (env, Pf, "ID", "J");
 }
+
+LCMSBOOL _cmsModifyTagData(cmsHPROFILE hProfile, icTagSignature sig,
+                       void *data, size_t size)
+{
+    LCMSBOOL isNew;
+    int i, idx, delta, count;
+    LPBYTE padChars[3] = {0, 0, 0};
+    LPBYTE beforeBuf, afterBuf, ptr;
+    size_t beforeSize, afterSize;
+    icUInt32Number profileSize, temp;
+    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+
+    isNew = FALSE;
+    idx = _cmsSearchTag(Icc, sig, FALSE);
+    if (idx < 0) {
+        isNew = TRUE;
+        idx = Icc->TagCount++;
+        if (Icc->TagCount >= MAX_TABLE_TAG) {
+            J2dRlsTraceLn1(J2D_TRACE_ERROR, "_cmsModifyTagData: Too many tags "
+                           "(%d)\n", Icc->TagCount);
+            Icc->TagCount = MAX_TABLE_TAG-1;
+            return FALSE;
+        }
+    }
+
+    /* Read in size from header */
+    Icc->Seek(Icc, 0);
+    Icc->Read(&profileSize, sizeof(icUInt32Number), 1, Icc);
+    AdjustEndianess32((LPBYTE) &profileSize);
+
+    /* Compute the change in profile size */
+    if (isNew) {
+        delta = sizeof(icTag) + ALIGNLONG(size);
+    } else {
+        delta = ALIGNLONG(size) - ALIGNLONG(Icc->TagSizes[idx]);
+    }
+    /* Add tag to internal structures */
+    ptr = malloc(size);
+    if (ptr == NULL) {
+        if(isNew) {
+            Icc->TagCount--;
+        }
+        J2dRlsTraceLn(J2D_TRACE_ERROR, "_cmsModifyTagData: ptr == NULL");
+        return FALSE;
+    }
+
+    if (!Icc->Grow(Icc, delta)) {
+        free(ptr);
+        if(isNew) {
+            Icc->TagCount--;
+        }
+        J2dRlsTraceLn(J2D_TRACE_ERROR,
+                      "_cmsModifyTagData: Icc->Grow() == FALSE");
+        return FALSE;
+    }
+
+    /* Compute size of tag data before/after the modified tag */
+    beforeSize = ((isNew)?profileSize:Icc->TagOffsets[idx]) -
+                 Icc->TagOffsets[0];
+    if (Icc->TagCount == (idx + 1)) {
+        afterSize = 0;
+    } else {
+        afterSize = profileSize - Icc->TagOffsets[idx+1];
+    }
+    /* Make copies of the data before/after the modified tag */
+    if (beforeSize > 0) {
+        beforeBuf = malloc(beforeSize);
+        if (!beforeBuf) {
+            if(isNew) {
+                Icc->TagCount--;
+            }
+            free(ptr);
+            J2dRlsTraceLn(J2D_TRACE_ERROR,
+                          "_cmsModifyTagData: beforeBuf == NULL");
+            return FALSE;
+        }
+        Icc->Seek(Icc, Icc->TagOffsets[0]);
+        Icc->Read(beforeBuf, beforeSize, 1, Icc);
+    }
+
+    if (afterSize > 0) {
+        afterBuf = malloc(afterSize);
+        if (!afterBuf) {
+            free(ptr);
+            if(isNew) {
+                Icc->TagCount--;
+            }
+            if (beforeSize > 0) {
+                free(beforeBuf);
+            }
+            J2dRlsTraceLn(J2D_TRACE_ERROR,
+                          "_cmsModifyTagData: afterBuf == NULL");
+            return FALSE;
+        }
+        Icc->Seek(Icc, Icc->TagOffsets[idx+1]);
+        Icc->Read(afterBuf, afterSize, 1, Icc);
+    }
+
+    CopyMemory(ptr, data, size);
+    Icc->TagSizes[idx] = size;
+    Icc->TagNames[idx] = sig;
+    if (Icc->TagPtrs[idx]) {
+        free(Icc->TagPtrs[idx]);
+    }
+    Icc->TagPtrs[idx] = ptr;
+    if (isNew) {
+        Icc->TagOffsets[idx] = profileSize;
+    }
+
+
+    /* Update the profile size in the header */
+    profileSize += delta;
+    Icc->Seek(Icc, 0);
+    temp = TransportValue32(profileSize);
+    Icc->Write(Icc, sizeof(icUInt32Number), &temp);
+
+
+    /* Adjust tag offsets: if the tag is new, we must account
+       for the new tag table entry; otherwise, only those tags after
+       the modified tag are changed (by delta) */
+    if (isNew) {
+        for (i = 0; i < Icc->TagCount; ++i) {
+            Icc->TagOffsets[i] += sizeof(icTag);
+        }
+    } else {
+        for (i = idx+1; i < Icc->TagCount; ++i) {
+            Icc->TagOffsets[i] += delta;
+        }
+    }
+
+    /* Write out a new tag table */
+    count = 0;
+    for (i = 0; i < Icc->TagCount; ++i) {
+        if (Icc->TagNames[i] != 0) {
+            ++count;
+        }
+    }
+    Icc->Seek(Icc, sizeof(icHeader));
+    temp = TransportValue32(count);
+    Icc->Write(Icc, sizeof(icUInt32Number), &temp);
+
+    for (i = 0; i < Icc->TagCount; ++i) {
+        if (Icc->TagNames[i] != 0) {
+            icTag tag;
+            tag.sig = TransportValue32(Icc->TagNames[i]);
+            tag.offset = TransportValue32((icInt32Number) Icc->TagOffsets[i]);
+            tag.size = TransportValue32((icInt32Number) Icc->TagSizes[i]);
+            Icc->Write(Icc, sizeof(icTag), &tag);
+        }
+    }
+
+    /* Write unchanged data before the modified tag */
+    if (beforeSize > 0) {
+        Icc->Write(Icc, beforeSize, beforeBuf);
+        free(beforeBuf);
+    }
+
+    /* Write modified tag data */
+    Icc->Write(Icc, size, data);
+    if (size % 4) {
+        Icc->Write(Icc, 4 - (size % 4), padChars);
+    }
+
+    /* Write unchanged data after the modified tag */
+    if (afterSize > 0) {
+        Icc->Write(Icc, afterSize, afterBuf);
+        free(afterBuf);
+    }
+
+    return TRUE;
+}
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -51,7 +51,7 @@
 
 
 
-// CIECAM 02 appearance model
+// CIECAM 02 appearance model. Many thanks to Jordi Vilar for the debugging.
 
 #include "lcms.h"
 
@@ -196,6 +196,10 @@
             clr.RGBpa[i] = (400.0 * temp) / (temp + 27.13) + 0.1;
         }
     }
+
+    clr.A = (((2.0 * clr.RGBpa[0]) + clr.RGBpa[1] +
+        (clr.RGBpa[2] / 20.0)) - 0.305) * pMod->Nbb;
+
     return clr;
 }
 
@@ -249,9 +253,6 @@
         clr.H = 300 + ((100*((clr.h - 237.53)/1.2)) / temp);
     }
 
-    clr.A = (((2.0 * clr.RGBpa[0]) + clr.RGBpa[1] +
-        (clr.RGBpa[2] / 20.0)) - 0.305) * pMod->Nbb;
-
     clr.J = 100.0 * pow((clr.A / pMod->adoptedWhite.A),
         (pMod->c * pMod->z));
 
@@ -395,7 +396,7 @@
     LPcmsCIECAM02 lpMod;
 
 
-   if((lpMod = (LPcmsCIECAM02) malloc(sizeof(cmsCIECAM02))) == NULL) {
+   if((lpMod = (LPcmsCIECAM02) _cmsMalloc(sizeof(cmsCIECAM02))) == NULL) {
         return (LCMSHANDLE) NULL;
     }
 
@@ -449,14 +450,19 @@
     lpMod -> z   = compute_z(lpMod);
     lpMod -> Nbb = computeNbb(lpMod);
     lpMod -> FL  = computeFL(lpMod);
+
+    if (lpMod -> D == D_CALCULATE ||
+        lpMod -> D == D_CALCULATE_DISCOUNT) {
+
     lpMod -> D   = computeD(lpMod);
+    }
+
     lpMod -> Ncb = lpMod -> Nbb;
 
     lpMod -> adoptedWhite = XYZtoCAT02(lpMod -> adoptedWhite);
     lpMod -> adoptedWhite = ChromaticAdaptation(lpMod -> adoptedWhite, lpMod);
     lpMod -> adoptedWhite = CAT02toHPE(lpMod -> adoptedWhite);
     lpMod -> adoptedWhite = NonlinearCompression(lpMod -> adoptedWhite, lpMod);
-    lpMod -> adoptedWhite = ComputeCorrelates(lpMod -> adoptedWhite, lpMod);
 
     return (LCMSHANDLE) lpMod;
 
@@ -465,7 +471,7 @@
 void LCMSEXPORT cmsCIECAM02Done(LCMSHANDLE hModel)
 {
     LPcmsCIECAM02 lpMod = (LPcmsCIECAM02) (LPSTR) hModel;
-    if (lpMod) free(lpMod);
+    if (lpMod) _cmsFree(lpMod);
 }
 
 
@@ -510,3 +516,4 @@
     pOut ->Z = clr.XYZ[2];
 
 }
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam97.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam97.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -174,7 +174,7 @@
 LCMSAPI void LCMSEXPORT cmsCIECAM97sDone(LCMSHANDLE hModel)
 {
     LPcmsCIECAM97s lpMod = (LPcmsCIECAM97s) (LPSTR) hModel;
-    if (lpMod) free(lpMod);
+    if (lpMod) _cmsFree(lpMod);
 }
 
 // Partial discounting for adaptation degree computation
@@ -331,7 +331,7 @@
     LPcmsCIECAM97s lpMod;
     VEC3 tmp;
 
-    if((lpMod = (LPcmsCIECAM97s) malloc(sizeof(cmsCIECAM97s))) == NULL) {
+    if((lpMod = (LPcmsCIECAM97s) _cmsMalloc(sizeof(cmsCIECAM97s))) == NULL) {
         return (LCMSHANDLE) NULL;
     }
 
@@ -449,7 +449,7 @@
 
     // RGB_subw = [MlamRigg][WP/YWp]
 #ifdef USE_CIECAM97s2
-    MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, (LPVEC3) &lpMod -> WP);
+    MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &lpMod -> WP);
 #else
     VEC3divK(&tmp, (LPVEC3) &lpMod -> WP, lpMod->WP.Y);
     MAT3eval(&lpMod -> RGB_subw, &lpMod -> MlamRigg, &tmp);
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -65,22 +65,25 @@
 // Persistence
 LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName);
 LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
 
 // Properties
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
-
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
-
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
+
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
+
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char* cSubProp, const char *Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* cProp);
 LCMSAPI double          LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, char ***PropertyNames);
+LCMSAPI const char*     LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char *cSubProp);
+LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, const char ***PropertyNames);
+LCMSAPI int             LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char*** SubpropertyNames);
 
 // Datasets
 
@@ -89,10 +92,10 @@
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE IT8, int row, int col);
 LCMSAPI double          LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE IT8, int col, int row);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
                                                 const char* Val);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
                                                 double Val);
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetData(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
@@ -100,15 +103,15 @@
 
 LCMSAPI double          LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
                                                 const char* cSample,
                                                 const char *Val);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
                                                 const char* cSample,
                                                 double Val);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
 LCMSAPI int             LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE IT8, char ***SampleNames);
 
 LCMSAPI void            LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE IT8, const char* Formatter);
@@ -126,7 +129,7 @@
 // #define STRICT_CGATS  1
 
 #define MAXID       128     // Max lenght of identifier
-#define MAXSTR      255     // Max lenght of string
+#define MAXSTR      1024     // Max lenght of string
 #define MAXTABLES   255     // Max Number of tables in a single stream
 #define MAXINCLUDE   20     // Max number of nested includes
 
@@ -137,6 +140,9 @@
 
 #ifndef NON_WINDOWS
 #include <io.h>
+#define DIR_CHAR    '\\'
+#else
+#define DIR_CHAR    '/'
 #endif
 
 // Symbols
@@ -160,6 +166,7 @@
         SEND_DATA,
         SEND_DATA_FORMAT,
         SKEYWORD,
+        SDATA_FORMAT_ID,
         SINCLUDE
 
     } SYMBOL;
@@ -171,7 +178,8 @@
         WRITE_UNCOOKED,
         WRITE_STRINGIFY,
         WRITE_HEXADECIMAL,
-        WRITE_BINARY
+        WRITE_BINARY,
+        WRITE_PAIR
 
     } WRITEMODE;
 
@@ -181,6 +189,8 @@
 
         struct _KeyVal*  Next;
         char*            Keyword;       // Name of variable
+        struct _KeyVal*  NextSubkey;    // If key is a dictionary, points to the next item
+        char*            Subkey;        // If key is a dictionary, points to the subkey name
         char*            Value;         // Points to value
         WRITEMODE        WriteAs;       // How to write the value
 
@@ -220,7 +230,12 @@
 
     } TABLE, *LPTABLE;
 
-
+// File stream being parsed
+
+typedef struct _FileContext {
+        char           FileName[MAX_PATH];    // File name if being readed from file
+        FILE*          Stream;                // File stream or NULL if holded in memory
+    } FILECTX, *LPFILECTX;
 
 // This struct hold all information about an openened
 // IT8 handler. Only one dataset is allowed.
@@ -257,9 +272,9 @@
         char*          Source;                // Points to loc. being parsed
         int            lineno;                // line counter for error reporting
 
-        char           FileName[MAX_PATH];    // File name if being readed from file
-        FILE*          Stream[MAXINCLUDE];    // File stream or NULL if holded in memory
+        LPFILECTX      FileStack[MAXINCLUDE]; // Stack of files being parsed
         int            IncludeSP;             // Include Stack Pointer
+
         char*          MemoryBlock;           // The stream if holded in memory
 
         char           DoubleFormatter[MAXID];   // Printf-like 'double' formatter
@@ -270,14 +285,14 @@
 
 typedef struct {
 
-                FILE* stream;   // For save-to-file behaviour
-
-                LPBYTE Base;
-                LPBYTE Ptr;             // For save-to-mem behaviour
-                size_t Used;
-                size_t Max;
-
-        } SAVESTREAM, FAR* LPSAVESTREAM;
+        FILE* stream;   // For save-to-file behaviour
+
+        LPBYTE Base;
+        LPBYTE Ptr;     // For save-to-mem behaviour
+        size_t Used;
+        size_t Max;
+
+    } SAVESTREAM, FAR* LPSAVESTREAM;
 
 
 // ------------------------------------------------------ IT8 parsing routines
@@ -298,59 +313,104 @@
         {".INCLUDE",            SINCLUDE},
         {"BEGIN_DATA",          SBEGIN_DATA },
         {"BEGIN_DATA_FORMAT",   SBEGIN_DATA_FORMAT },
+        {"DATA_FORMAT_IDENTIFIER", SDATA_FORMAT_ID},
         {"END_DATA",            SEND_DATA},
         {"END_DATA_FORMAT",     SEND_DATA_FORMAT},
         {"KEYWORD",             SKEYWORD}
-
         };
 
 #define NUMKEYS (sizeof(TabKeys)/sizeof(KEYWORD))
 
 // Predefined properties
 
-static const char* PredefinedProperties[] = {
-
-        "NUMBER_OF_FIELDS",    // Required - NUMBER OF FIELDS
-        "NUMBER_OF_SETS",      // Required - NUMBER OF SETS
-        "ORIGINATOR",          // Required - Identifies the specific system, organization or individual that created the data file.
-        "FILE_DESCRIPTOR",     // Required - Describes the purpose or contents of the data file.
-        "CREATED",             // Required - Indicates date of creation of the data file.
-        "DESCRIPTOR",          // Required  - Describes the purpose or contents of the data file.
-        "DIFFUSE_GEOMETRY",    // The diffuse geometry used. Allowed values are "sphere" or "opal".
-        "MANUFACTURER",
-        "MANUFACTURE",         // Some broken Fuji targets does store this value
-        "PROD_DATE",           // Identifies year and month of production of the target in the form yyyy:mm.
-        "SERIAL",              // Uniquely identifies individual physical target.
-
-        "MATERIAL",            // Identifies the material on which the target was produced using a code
+// A property
+typedef struct {
+        const char *id;
+        WRITEMODE as;
+    } PROPERTY;
+
+static PROPERTY PredefinedProperties[] = {
+
+        {"NUMBER_OF_FIELDS", WRITE_UNCOOKED},    // Required - NUMBER OF FIELDS
+        {"NUMBER_OF_SETS",   WRITE_UNCOOKED},    // Required - NUMBER OF SETS
+        {"ORIGINATOR",       WRITE_STRINGIFY},   // Required - Identifies the specific system, organization or individual that created the data file.
+        {"FILE_DESCRIPTOR",  WRITE_STRINGIFY},   // Required - Describes the purpose or contents of the data file.
+        {"CREATED",          WRITE_STRINGIFY},   // Required - Indicates date of creation of the data file.
+        {"DESCRIPTOR",       WRITE_STRINGIFY},   // Required  - Describes the purpose or contents of the data file.
+        {"DIFFUSE_GEOMETRY", WRITE_STRINGIFY},   // The diffuse geometry used. Allowed values are "sphere" or "opal".
+        {"MANUFACTURER",     WRITE_STRINGIFY},
+        {"MANUFACTURE",      WRITE_STRINGIFY},   // Some broken Fuji targets does store this value
+        {"PROD_DATE",        WRITE_STRINGIFY},   // Identifies year and month of production of the target in the form yyyy:mm.
+        {"SERIAL",           WRITE_STRINGIFY},   // Uniquely identifies individual physical target.
+
+        {"MATERIAL",         WRITE_STRINGIFY},   // Identifies the material on which the target was produced using a code
                                // uniquely identifying th e material. This is intend ed to be used for IT8.7
                                // physical targets only (i.e . IT8.7/1 a nd IT8.7/2).
 
-        "INSTRUMENTATION",     // Used to report the specific instrumentation used (manufacturer and
+        {"INSTRUMENTATION",  WRITE_STRINGIFY},   // Used to report the specific instrumentation used (manufacturer and
                                // model number) to generate the data reported. This data will often
                                // provide more information about the particular data collected than an
                                // extensive list of specific details. This is particularly important for
                                // spectral data or data derived from spectrophotometry.
 
-        "MEASUREMENT_SOURCE",  // Illumination used for spectral measurements. This data helps provide
+        {"MEASUREMENT_SOURCE", WRITE_STRINGIFY}, // Illumination used for spectral measurements. This data helps provide
                                // a guide to the potential for issues of paper fluorescence, etc.
 
-        "PRINT_CONDITIONS",    // Used to define the characteristics of the printed sheet being reported.
+        {"PRINT_CONDITIONS", WRITE_STRINGIFY},   // Used to define the characteristics of the printed sheet being reported.
                                // Where standard conditions have been defined (e.g., SWOP at nominal)
                                // named conditions may suffice. Otherwise, detailed information is
                                // needed.
 
-        "SAMPLE_BACKING",      // Identifies the backing material used behind the sample during
-                               // measurement. Allowed values are “black”, “white”, or "na".
-
-        "CHISQ_DOF"            // Degrees of freedom associated with the Chi squared statistic
+        {"SAMPLE_BACKING",   WRITE_STRINGIFY},   // Identifies the backing material used behind the sample during
+                               // measurement. Allowed values are “black”, “white”, or {"na".
+
+        {"CHISQ_DOF",        WRITE_STRINGIFY},   // Degrees of freedom associated with the Chi squared statistic
+
+//    new in recent specs:
+        {"MEASUREMENT_GEOMETRY", WRITE_STRINGIFY}, // The type of measurement, either reflection or transmission, should be indicated
+                               // along with details of the geometry and the aperture size and shape. For example,
+                               // for transmission measurements it is important to identify 0/diffuse, diffuse/0,
+                               // opal or integrating sphere, etc. For reflection it is important to identify 0/45,
+                               // 45/0, sphere (specular included or excluded), etc.
+
+       {"FILTER",            WRITE_STRINGIFY},   // Identifies the use of physical filter(s) during measurement. Typically used to
+                               // denote the use of filters such as none, D65, Red, Green or Blue.
+
+       {"POLARIZATION",      WRITE_STRINGIFY},   // Identifies the use of a physical polarization filter during measurement. Allowed
+                               // values are {"yes”, “white”, “none” or “na”.
+
+       {"WEIGHTING_FUNCTION", WRITE_PAIR},   // Indicates such functions as: the CIE standard observer functions used in the
+                               // calculation of various data parameters (2 degree and 10 degree), CIE standard
+                               // illuminant functions used in the calculation of various data parameters (e.g., D50,
+                               // D65, etc.), density status response, etc. If used there shall be at least one
+                               // name-value pair following the WEIGHTING_FUNCTION tag/keyword. The first attribute
+                               // in the set shall be {"name" and shall identify the particular parameter used.
+                               // The second shall be {"value" and shall provide the value associated with that name.
+                               // For ASCII data, a string containing the Name and Value attribute pairs shall follow
+                               // the weighting function keyword. A semi-colon separates attribute pairs from each
+                               // other and within the attribute the name and value are separated by a comma.
+
+       {"COMPUTATIONAL_PARAMETER", WRITE_PAIR}, // Parameter that is used in computing a value from measured data. Name is the name
+                               // of the calculation, parameter is the name of the parameter used in the calculation
+                               // and value is the value of the parameter.
+
+       {"TARGET_TYPE",        WRITE_STRINGIFY},  // The type of target being measured, e.g. IT8.7/1, IT8.7/3, user defined, etc.
+
+       {"COLORANT",           WRITE_STRINGIFY},  // Identifies the colorant(s) used in creating the target.
+
+       {"TABLE_DESCRIPTOR",   WRITE_STRINGIFY},  // Describes the purpose or contents of a data table.
+
+       {"TABLE_NAME",         WRITE_STRINGIFY}   // Provides a short name for a data table.
 };
 
-#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(char *))
+#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(PROPERTY))
 
 
 // Predefined sample types on dataset
 static const char* PredefinedSampleID[] = {
+        "SAMPLE_ID",      // Identifies sample that data represents
+        "STRING",         // Identifies label, or other non-machine readable value.
+                          // Value must begin and end with a " symbol
 
         "CMYK_C",         // Cyan component of CMYK data expressed as a percentage
         "CMYK_M",         // Magenta component of CMYK data expressed as a percentage
@@ -378,7 +438,7 @@
         "LAB_B",          // b* component of Lab data
         "LAB_C",          // C*ab component of Lab data
         "LAB_H",          // hab component of Lab data
-        "LAB_DE"          //  CIE dE
+        "LAB_DE",         //  CIE dE
         "LAB_DE_94",      //  CIE dE using CIE 94
         "LAB_DE_CMC",     //  dE using CMC
         "LAB_DE_2000",    // CIE dE using CIE DE 2000
@@ -388,7 +448,7 @@
         "STDEV_Y",        // Standard deviation of Y (tristimulus data)
         "STDEV_Z",        // Standard deviation of Z (tristimulus data)
         "STDEV_L",        // Standard deviation of L*
-        "STDEV_A"         // Standard deviation of a*
+        "STDEV_A",        // Standard deviation of a*
         "STDEV_B",        // Standard deviation of b*
         "STDEV_DE",       // Standard deviation of CIE dE
         "CHI_SQD_PAR"};   // The average of the standard deviations of L*, a* and b*. It is
@@ -397,57 +457,120 @@
 
 #define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
 
+//Forward declaration of some internal functions
+static
+void* AllocChunk(LPIT8 it8, size_t size);
+
 // Checks if c is a separator
 static
-BOOL isseparator(int c)
+LCMSBOOL isseparator(int c)
 {
         return (c == ' ') || (c == '\t') || (c == '\r');
 }
 
 // Checks whatever if c is a valid identifier char
-
 static
-BOOL ismiddle(int c)
+LCMSBOOL ismiddle(int c)
 {
    return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
 }
 
 // Checks whatsever if c is a valid identifier middle char.
 static
-BOOL isidchar(int c)
+LCMSBOOL isidchar(int c)
 {
    return isalnum(c) || ismiddle(c);
 }
 
 // Checks whatsever if c is a valid identifier first char.
 static
-BOOL isfirstidchar(int c)
+LCMSBOOL isfirstidchar(int c)
 {
      return !isdigit(c) && ismiddle(c);
 }
 
+// checks whether the supplied path looks like an absolute path
+// NOTE: this function doesn't checks if the path exists or even if it's legal
+static
+LCMSBOOL isabsolutepath(const char *path)
+{
+    if(path == NULL)
+        return FALSE;
+
+    if(path[0] == DIR_CHAR)
+        return TRUE;
+
+#ifndef NON_WINDOWS
+    if(isalpha(path[0]) && path[1] == ':')
+        return TRUE;
+#endif
+    return FALSE;
+}
+
+// Makes a file path based on a given reference path
+// NOTE: buffer is assumed to point to at least MAX_PATH bytes
+// NOTE: both relPath and basePath are assumed to be no more than MAX_PATH characters long (including the null terminator!)
+// NOTE: this function doesn't check if the path exists or even if it's legal
+static
+LCMSBOOL _cmsMakePath(const char *relPath, const char *basePath, char *buffer)
+{
+    if (!isabsolutepath(relPath)) {
+
+        char *tail;
+
+        strncpy(buffer, basePath, MAX_PATH-1);
+        tail = strrchr(buffer, DIR_CHAR);
+        if (tail != NULL) {
+
+            size_t len = tail - buffer;
+            strncpy(tail + 1, relPath, MAX_PATH - len -1);
+            //  TODO: if combined path is longer than MAX_PATH, this should return FALSE!
+            return TRUE;
+        }
+    }
+    strncpy(buffer, relPath, MAX_PATH - 1);
+        buffer[MAX_PATH-1] = 0;
+    return TRUE;
+}
+
+
+// Make sure no exploit is being even tried
 
 static
-BOOL SynError(LPIT8 it8, const char *Txt, ...)
+const char* NoMeta(const char* str)
+{
+    if (strchr(str, '%') != NULL)
+        return "**** CORRUPTED FORMAT STRING ***";
+
+    return str;
+}
+
+
+// Syntax error
+static
+LCMSBOOL SynError(LPIT8 it8, const char *Txt, ...)
 {
         char Buffer[256], ErrMsg[1024];
         va_list args;
 
         va_start(args, Txt);
-        vsprintf(Buffer, Txt, args);
+        vsnprintf(Buffer, 255, Txt, args);
+        Buffer[255] = 0;
         va_end(args);
 
-        sprintf(ErrMsg, "%s: Line %d, %s", it8->FileName, it8->lineno, Buffer);
+        snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
+        ErrMsg[1023] = 0;
         it8->sy = SSYNERROR;
-        cmsSignalError(LCMS_ERRC_ABORTED, ErrMsg);
+        cmsSignalError(LCMS_ERRC_ABORTED, "%s", ErrMsg);
         return FALSE;
 }
 
+// Check if current symbol is same as specified. issue an error else.
 static
-BOOL Check(LPIT8 it8, SYMBOL sy, const char* Err)
+LCMSBOOL Check(LPIT8 it8, SYMBOL sy, const char* Err)
 {
         if (it8 -> sy != sy)
-                return SynError(it8, Err);
+                return SynError(it8, NoMeta(Err));
         return TRUE;
 }
 
@@ -457,15 +580,15 @@
 static
 void NextCh(LPIT8 it8)
 {
-    if (it8 -> Stream[it8 ->IncludeSP]) {
-
-        it8 ->ch = fgetc(it8 ->Stream[it8 ->IncludeSP]);
-
-        if (feof(it8 -> Stream[it8 ->IncludeSP]))  {
+    if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
+
+        it8 ->ch = fgetc(it8 ->FileStack[it8 ->IncludeSP]->Stream);
+
+        if (feof(it8 -> FileStack[it8 ->IncludeSP]->Stream))  {
 
             if (it8 ->IncludeSP > 0) {
 
-                fclose(it8 ->Stream[it8->IncludeSP--]);
+                fclose(it8 ->FileStack[it8->IncludeSP--]->Stream);
                 it8 -> ch = ' ';                            // Whitespace to be ignored
 
             } else
@@ -476,7 +599,6 @@
 
     }
     else {
-
         it8->ch = *it8->Source;
         if (it8->ch) it8->Source++;
     }
@@ -799,18 +921,39 @@
 
     if (it8 -> sy == SINCLUDE) {
 
-                FILE* IncludeFile;
+                LPFILECTX FileNest;
+
+                if(it8 -> IncludeSP >= (MAXINCLUDE-1))
+                {
+                    SynError(it8, "Too many recursion levels");
+                    return;
+                }
 
                 InSymbol(it8);
                 if (!Check(it8, SSTRING, "Filename expected")) return;
-                IncludeFile = fopen(it8 -> str, "rt");
-                if (IncludeFile == NULL) {
-
-                        SynError(it8, "File %s not found", it8 ->str);
+
+                FileNest = it8 -> FileStack[it8 -> IncludeSP + 1];
+                if(FileNest == NULL)
+                {
+                    FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+                    //if(FileNest == NULL)
+                        //  TODO: how to manage out-of-memory conditions?
+                }
+
+                if(_cmsMakePath(it8->str, it8->FileStack[it8->IncludeSP]->FileName, FileNest->FileName) == FALSE)
+                {
+                    SynError(it8, "File path too long");
+                    return;
+                }
+
+                FileNest->Stream = fopen(FileNest->FileName, "rt");
+                if (FileNest->Stream == NULL) {
+
+                        SynError(it8, "File %s not found", FileNest->FileName);
                         return;
                 }
-
-                it8 -> Stream[++it8 -> IncludeSP] = IncludeFile;
+                it8->IncludeSP++;
+
                 it8 ->ch = ' ';
                 InSymbol(it8);
     }
@@ -819,7 +962,7 @@
 
 // Checks end of line separator
 static
-BOOL CheckEOLN(LPIT8 it8)
+LCMSBOOL CheckEOLN(LPIT8 it8)
 {
         if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
         while (it8 -> sy == SEOLN)
@@ -850,21 +993,26 @@
 
 // Returns a string holding current value
 static
-BOOL GetVal(LPIT8 it8, char* Buffer, const char* ErrorTitle)
+LCMSBOOL GetVal(LPIT8 it8, char* Buffer, size_t max, const char* ErrorTitle)
 {
     switch (it8->sy) {
 
-    case SIDENT:  strncpy(Buffer, it8->id, MAXID-1); break;
-    case SINUM:   sprintf(Buffer, "%d", it8 -> inum); break;
-    case SDNUM:   sprintf(Buffer, it8->DoubleFormatter, it8 -> dnum); break;
-    case SSTRING: strncpy(Buffer, it8->str, MAXSTR-1); break;
+    case SIDENT:  strncpy(Buffer, it8->id, max);
+                  Buffer[max-1]=0;
+                  break;
+    case SINUM:   snprintf(Buffer, max, "%d", it8 -> inum); break;
+    case SDNUM:   snprintf(Buffer, max, it8->DoubleFormatter, it8 -> dnum); break;
+    case SSTRING: strncpy(Buffer, it8->str, max);
+                  Buffer[max-1] = 0;
+                  break;
 
 
     default:
-         return SynError(it8, ErrorTitle);
+         return SynError(it8, "%s", ErrorTitle);
     }
 
-     return TRUE;
+    Buffer[max] = 0;
+    return TRUE;
 }
 
 // ---------------------------------------------------------- Table
@@ -872,7 +1020,13 @@
 static
 LPTABLE GetTable(LPIT8 it8)
 {
-    return it8 ->Tab + it8 ->nTable;
+   if ((it8 -> nTable >= it8 ->TablesCount) || (it8 -> nTable < 0)) {
+
+           SynError(it8, "Table %d out of sequence", it8 -> nTable);
+           return it8 -> Tab;
+   }
+
+   return it8 ->Tab + it8 ->nTable;
 }
 
 // ---------------------------------------------------------- Memory management
@@ -896,15 +1050,15 @@
         for (p = it8->MemorySink; p != NULL; p = n) {
 
             n = p->Next;
-            if (p->Ptr) free(p->Ptr);
-            free(p);
+            if (p->Ptr) _cmsFree(p->Ptr);
+            _cmsFree(p);
         }
     }
 
     if (it8->MemoryBlock)
-        free(it8->MemoryBlock);
-
-    free(it8);
+        _cmsFree(it8->MemoryBlock);
+
+     _cmsFree(it8);
 }
 
 
@@ -913,16 +1067,16 @@
 void* AllocBigBlock(LPIT8 it8, size_t size)
 {
    LPOWNEDMEM ptr1;
-   void* ptr = malloc(size);
+   void* ptr = _cmsMalloc(size);
 
         if (ptr) {
 
                 ZeroMemory(ptr, size);
-                ptr1 = (LPOWNEDMEM) malloc(sizeof(OWNEDMEM));
+                ptr1 = (LPOWNEDMEM) _cmsMalloc(sizeof(OWNEDMEM));
 
                 if (ptr1 == NULL) {
 
-                    free(ptr);
+                     _cmsFree(ptr);
                     return NULL;
                 }
 
@@ -986,8 +1140,9 @@
 // Searches through linked list
 
 static
-BOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, LPKEYVALUE* LastPtr)
+LCMSBOOL IsAvailableOnList(LPKEYVALUE p, const char* Key, const char* Subkey, LPKEYVALUE* LastPtr)
 {
+    if (LastPtr) *LastPtr = p;
 
     for (;  p != NULL; p = p->Next) {
 
@@ -996,8 +1151,22 @@
         if (*Key != '#') { // Comments are ignored
 
             if (stricmp(Key, p->Keyword) == 0)
-                    return TRUE;
+                    break;
+        }
         }
+
+    if (p == NULL)
+        return FALSE;
+
+    if (Subkey == 0)
+        return TRUE;
+
+    for (; p != NULL; p = p->NextSubkey) {
+
+        if (LastPtr) *LastPtr = p;
+
+        if (stricmp(Subkey, p->Subkey) == 0)
+            return TRUE;
     }
 
     return FALSE;
@@ -1007,35 +1176,55 @@
 
 // Add a property into a linked list
 static
-BOOL AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char* xValue, WRITEMODE WriteAs)
+LPKEYVALUE AddToList(LPIT8 it8, LPKEYVALUE* Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
 {
     LPKEYVALUE p;
-    LPKEYVALUE last;
-
 
     // Check if property is already in list (this is an error)
 
-    if (IsAvailableOnList(*Head, Key, &last)) {
-
-                        // This may work for editing properties
-
-                         last->Value   = AllocString(it8, xValue);
-                         last->WriteAs = WriteAs;
-                         return TRUE;
-
-             // return SynError(it8, "duplicate key <%s>", Key);
+    if (IsAvailableOnList(*Head, Key, Subkey, &p)) {
+
+            // This may work for editing properties
+
+        //     return SynError(it8, "duplicate key <%s>", Key);
     }
-
-        // Allocate the container
+    else {
+        LPKEYVALUE last = p;
+
+    // Allocate the container
     p = (LPKEYVALUE) AllocChunk(it8, sizeof(KEYVALUE));
     if (p == NULL)
     {
-        return SynError(it8, "AddToList: out of memory");
+            SynError(it8, "AddToList: out of memory");
+            return NULL;
     }
 
     // Store name and value
     p->Keyword = AllocString(it8, Key);
-
+        p->Subkey = (Subkey == NULL) ? NULL : AllocString(it8, Subkey);
+
+        // Keep the container in our list
+        if (*Head == NULL)
+            *Head = p;
+        else
+        {
+            if(Subkey != 0 && last != 0) {
+                last->NextSubkey = p;
+
+                // If Subkey is not null, then last is the last property with the same key,
+                // but not necessarily is the last property in the list, so we need to move
+                // to the actual list end
+                while(last->Next != 0)
+                    last = last->Next;
+    }
+            last->Next = p;
+    }
+
+    p->Next    = NULL;
+        p->NextSubkey = NULL;
+    }
+
+    p->WriteAs = WriteAs;
     if (xValue != NULL) {
 
         p->Value   = AllocString(it8, xValue);
@@ -1044,29 +1233,20 @@
         p->Value   = NULL;
     }
 
-    p->Next    = NULL;
-    p->WriteAs = WriteAs;
-
-    // Keep the container in our list
-    if (*Head == NULL)
-        *Head = p;
-    else
-        last->Next = p;
-
-    return TRUE;
+    return p;
 }
 
 static
-BOOL AddAvailableProperty(LPIT8 it8, const char* Key)
+LPKEYVALUE AddAvailableProperty(LPIT8 it8, const char* Key, WRITEMODE as)
 {
-        return AddToList(it8, &it8->ValidKeywords, Key, NULL, WRITE_UNCOOKED);
+        return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
 }
 
 
 static
-BOOL AddAvailableSampleID(LPIT8 it8, const char* Key)
+LPKEYVALUE AddAvailableSampleID(LPIT8 it8, const char* Key)
 {
-        return AddToList(it8, &it8->ValidSampleID, Key, NULL, WRITE_UNCOOKED);
+        return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
 }
 
 
@@ -1122,8 +1302,6 @@
     AllocTable(it8);
 
     it8->MemoryBlock = NULL;
-    it8->Stream[0]   = NULL;
-    it8->IncludeSP   = 0;
     it8->MemorySink  = NULL;
 
     it8 ->nTable = 0;
@@ -1141,6 +1319,8 @@
     it8 -> inum = 0;
     it8 -> dnum = 0.0;
 
+    it8->FileStack[0] = (LPFILECTX)AllocChunk(it8, sizeof(FILECTX));
+    it8->IncludeSP   = 0;
     it8 -> lineno = 1;
 
     strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
@@ -1149,7 +1329,7 @@
     // Initialize predefined properties & data
 
     for (i=0; i < NUMPREDEFINEDPROPS; i++)
-            AddAvailableProperty(it8, PredefinedProperties[i]);
+            AddAvailableProperty(it8, PredefinedProperties[i].id, PredefinedProperties[i].as);
 
     for (i=0; i < NUMPREDEFINEDSAMPLEID; i++)
             AddAvailableSampleID(it8, PredefinedSampleID[i]);
@@ -1167,65 +1347,72 @@
 
 }
 
-BOOL  LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
+LCMSBOOL  LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type)
 {
         LPIT8 it8 = (LPIT8) hIT8;
 
         strncpy(it8 ->SheetType, Type, MAXSTR-1);
+        it8 ->SheetType[MAXSTR-1] = 0;
         return TRUE;
 }
 
-BOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
 
     if (!Val) return FALSE;
     if (!*Val) return FALSE;
 
-    return AddToList(it8, &GetTable(it8)->HeaderList, "# ", Val, WRITE_UNCOOKED);
+    return AddToList(it8, &GetTable(it8)->HeaderList, "# ", NULL, Val, WRITE_UNCOOKED) != NULL;
 }
 
 
 
 // Sets a property
-BOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* Key, const char *Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
 
     if (!Val) return FALSE;
     if (!*Val) return FALSE;
 
-    return AddToList(it8, &GetTable(it8)->HeaderList, Key, Val, WRITE_STRINGIFY);
+    return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Val, WRITE_STRINGIFY) != NULL;
 }
 
 
-BOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
     char Buffer[1024];
 
     sprintf(Buffer, it8->DoubleFormatter, Val);
 
-    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_UNCOOKED);
+    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
 
-BOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
     char Buffer[1024];
 
     sprintf(Buffer, "%d", Val);
 
-    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, Buffer, WRITE_HEXADECIMAL);
+    return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
 }
 
-BOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer)
 {
     LPIT8 it8 = (LPIT8) hIT8;
 
-    return AddToList(it8, &GetTable(it8)->HeaderList, Key, Buffer, WRITE_UNCOOKED);
+    return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
 
+LCMSBOOL LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    return AddToList(it8, &GetTable(it8)->HeaderList, Key, SubKey, Buffer, WRITE_PAIR) != NULL;
+}
 
 // Gets a property
 const char* LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* Key)
@@ -1233,7 +1420,7 @@
     LPIT8 it8 = (LPIT8) hIT8;
     LPKEYVALUE p;
 
-    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, &p))
+    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, NULL, &p))
     {
         return p -> Value;
     }
@@ -1249,6 +1436,18 @@
     else return 0.0;
 }
 
+const char* LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* Key, const char *SubKey)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    LPKEYVALUE p;
+
+    if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p))
+    {
+        return p -> Value;
+    }
+    return NULL;
+}
+
 // ----------------------------------------------------------------- Datasets
 
 
@@ -1287,10 +1486,17 @@
 }
 
 static
-BOOL SetDataFormat(LPIT8 it8, int n, const char *label)
+LCMSBOOL SetDataFormat(LPIT8 it8, int n, const char *label)
 {
     LPTABLE t = GetTable(it8);
 
+#ifdef  STRICT_CGATS
+    if (!IsAvailableOnList(it8-> ValidSampleID, label, NULL, NULL)) {
+        SynError(it8, "Invalid data format '%s'.", label);
+        return FALSE;
+    }
+#endif
+
     if (!t->DataFormat)
         AllocateDataFormat(it8);
 
@@ -1308,7 +1514,7 @@
 }
 
 
-BOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE h, int n, const char *Sample)
 {
         LPIT8 it8 = (LPIT8) h;
         return SetDataFormat(it8, n, Sample);
@@ -1348,7 +1554,7 @@
 }
 
 static
-BOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
+LCMSBOOL SetData(LPIT8 it8, int nSet, int nField, const char *Val)
 {
     LPTABLE t = GetTable(it8);
 
@@ -1383,42 +1589,43 @@
 void WriteStr(LPSAVESTREAM f, const char *str)
 {
 
-        size_t len;
-
-        if (str == NULL)
-                str = " ";
-
-        // Lenghth to write
-        len = strlen(str);
+    size_t len;
+
+    if (str == NULL)
+        str = " ";
+
+    // Lenghth to write
+    len = strlen(str);
     f ->Used += len;
 
 
-        if (f ->stream) {       // Should I write it to a file?
-
-                fwrite(str, 1, len, f->stream);
+    if (f ->stream) {   // Should I write it to a file?
+
+        fwrite(str, 1, len, f->stream);
+
+    }
+    else {  // Or to a memory block?
+
+
+        if (f ->Base) {   // Am I just counting the bytes?
+
+            if (f ->Used > f ->Max) {
+
+                cmsSignalError(LCMS_ERRC_ABORTED, "Write to memory overflows in CGATS parser");
+                return;
+            }
+
+            CopyMemory(f ->Ptr, str, len);
+            f->Ptr += len;
 
         }
-        else {  // Or to a memory block?
-
-
-                if (f ->Base) {   // Am I just counting the bytes?
-
-                        if (f ->Used > f ->Max) {
-
-                                cmsSignalError(LCMS_ERRC_ABORTED, "Write to memory overflows in CGATS parser");
-                                return;
-                        }
-
-                        CopyMemory(f ->Ptr, str, len);
-                        f->Ptr += len;
-
-                }
-
-        }
+
+    }
 }
 
 
-//
+// Write formatted
+
 static
 void Writef(LPSAVESTREAM f, const char* frm, ...)
 {
@@ -1426,7 +1633,8 @@
     va_list args;
 
     va_start(args, frm);
-    vsprintf(Buffer, frm, args);
+    vsnprintf(Buffer, 4095, frm, args);
+    Buffer[4095] = 0;
     WriteStr(f, Buffer);
     va_end(args);
 
@@ -1450,7 +1658,7 @@
             for (Pt = p ->Value; *Pt; Pt++) {
 
 
-                                Writef(fp, "%c", *Pt);
+                Writef(fp, "%c", *Pt);
 
                 if (*Pt == '\n') {
                     WriteStr(fp, "# ");
@@ -1462,7 +1670,7 @@
         }
 
 
-        if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL)) {
+        if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL, NULL)) {
 
 #ifdef STRICT_CGATS
             WriteStr(fp, "KEYWORD\t\"");
@@ -1470,7 +1678,7 @@
             WriteStr(fp, "\"\n");
 #endif
 
-            AddAvailableProperty(it8, p->Keyword);
+            AddAvailableProperty(it8, p->Keyword, WRITE_UNCOOKED);
 
         }
 
@@ -1495,6 +1703,10 @@
                     Writef(fp, "\t0x%B", atoi(p ->Value));
                     break;
 
+            case WRITE_PAIR:
+                    Writef(fp, "\t\"%s,%s\"", p->Subkey, p->Value);
+                    break;
+
             default: SynError(it8, "Unknown write mode %d", p ->WriteAs);
                      return;
             }
@@ -1573,13 +1785,13 @@
 
 
 // Saves whole file
-BOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
+LCMSBOOL LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE hIT8, const char* cFileName)
 {
     SAVESTREAM sd;
     int i;
     LPIT8 it8 = (LPIT8) hIT8;
 
-        ZeroMemory(&sd, sizeof(SAVESTREAM));
+    ZeroMemory(&sd, sizeof(SAVESTREAM));
 
     sd.stream = fopen(cFileName, "wt");
     if (!sd.stream) return FALSE;
@@ -1594,31 +1806,31 @@
             WriteData(&sd, it8);
     }
 
-        fclose(sd.stream);
+    fclose(sd.stream);
 
     return TRUE;
 }
 
 
 // Saves to memory
-BOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
+LCMSBOOL LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded)
 {
     SAVESTREAM sd;
     int i;
     LPIT8 it8 = (LPIT8) hIT8;
 
-        ZeroMemory(&sd, sizeof(SAVESTREAM));
+    ZeroMemory(&sd, sizeof(SAVESTREAM));
 
     sd.stream = NULL;
-        sd.Base   = (LPBYTE) MemPtr;
-        sd.Ptr    = sd.Base;
-
-        sd.Used = 0;
-
-        if (sd.Base)
-                sd.Max  = *BytesNeeded;         // Write to memory?
-        else
-                sd.Max  = 0;                            // Just counting the needed bytes
+    sd.Base   = (LPBYTE) MemPtr;
+    sd.Ptr    = sd.Base;
+
+    sd.Used = 0;
+
+    if (sd.Base)
+        sd.Max  = *BytesNeeded;     // Write to memory?
+    else
+        sd.Max  = 0;                // Just counting the needed bytes
 
     WriteStr(&sd, it8->SheetType);
     WriteStr(&sd, "\n");
@@ -1630,12 +1842,12 @@
             WriteData(&sd, it8);
     }
 
-        sd.Used++;      // The \0 at the very end
-
-        if (sd.Base)
-                sd.Ptr = 0;
-
-        *BytesNeeded = sd.Used;
+    sd.Used++;  // The \0 at the very end
+
+    if (sd.Base)
+        sd.Ptr = 0;
+
+    *BytesNeeded = sd.Used;
 
     return TRUE;
 }
@@ -1644,7 +1856,7 @@
 // -------------------------------------------------------------- Higer level parsing
 
 static
-BOOL DataFormatSection(LPIT8 it8)
+LCMSBOOL DataFormatSection(LPIT8 it8)
 {
     int iField = 0;
     LPTABLE t = GetTable(it8);
@@ -1685,16 +1897,19 @@
 
 
 static
-BOOL DataSection (LPIT8 it8)
+LCMSBOOL DataSection (LPIT8 it8)
 {
     int  iField = 0;
     int  iSet   = 0;
-    char Buffer[256];
+    char Buffer[MAXSTR];
     LPTABLE t = GetTable(it8);
 
     InSymbol(it8);   // Eats "BEGIN_DATA"
     CheckEOLN(it8);
 
+    if (!t->Data)
+        AllocateDataSet(it8);
+
     while (it8->sy != SEND_DATA && it8->sy != SEOF)
     {
         if (iField >= t -> nSamples) {
@@ -1705,7 +1920,7 @@
 
         if (it8->sy != SEND_DATA && it8->sy != SEOF) {
 
-            if (!GetVal(it8, Buffer, "Sample data expected"))
+            if (!GetVal(it8, Buffer, 255, "Sample data expected"))
                 return FALSE;
 
             if (!SetData(it8, iSet, iField, Buffer))
@@ -1734,10 +1949,11 @@
 
 
 static
-BOOL HeaderSection(LPIT8 it8)
+LCMSBOOL HeaderSection(LPIT8 it8)
 {
     char VarName[MAXID];
     char Buffer[MAXSTR];
+    LPKEYVALUE Key;
 
         while (it8->sy != SEOF &&
                it8->sy != SSYNERROR &&
@@ -1749,30 +1965,79 @@
 
         case SKEYWORD:
                 InSymbol(it8);
-                if (!GetVal(it8, Buffer, "Keyword expected")) return FALSE;
-                if (!AddAvailableProperty(it8, Buffer)) return FALSE;
+                if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
+                if (!AddAvailableProperty(it8, Buffer, WRITE_UNCOOKED)) return FALSE;
+                InSymbol(it8);
+                break;
+
+
+        case SDATA_FORMAT_ID:
+                InSymbol(it8);
+                if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
+                if (!AddAvailableSampleID(it8, Buffer)) return FALSE;
                 InSymbol(it8);
                 break;
 
 
         case SIDENT:
                 strncpy(VarName, it8->id, MAXID-1);
-
-                if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL)) {
+                VarName[MAXID-1] = 0;
+
+                if (!IsAvailableOnList(it8-> ValidKeywords, VarName, NULL, &Key)) {
 
 #ifdef STRICT_CGATS
                  return SynError(it8, "Undefined keyword '%s'", VarName);
 #else
-                if (!AddAvailableProperty(it8, VarName)) return FALSE;
+                    Key = AddAvailableProperty(it8, VarName, WRITE_UNCOOKED);
+                    if (Key == NULL) return FALSE;
 #endif
                 }
 
                 InSymbol(it8);
-                if (!GetVal(it8, Buffer, "Property data expected")) return FALSE;
-
-
-                AddToList(it8, &GetTable(it8)->HeaderList, VarName, Buffer,
-                                                                (it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
+                if (!GetVal(it8, Buffer, MAXSTR-1, "Property data expected")) return FALSE;
+
+                if(Key->WriteAs != WRITE_PAIR) {
+                    AddToList(it8, &GetTable(it8)->HeaderList, VarName, NULL, Buffer,
+                                (it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED);
+                }
+                else {
+                    const char *Subkey;
+                    char *Nextkey;
+                    if (it8->sy != SSTRING)
+                        return SynError(it8, "Invalid value '%s' for property '%s'.", Buffer, VarName);
+
+                    // chop the string as a list of "subkey, value" pairs, using ';' as a separator
+                    for(Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
+                    {
+                        char *Value, *temp;
+
+                        //  identify token pair boundary
+                        Nextkey = (char*) strchr(Subkey, ';');
+                        if(Nextkey)
+                            *Nextkey++ = '\0';
+
+                        // for each pair, split the subkey and the value
+                        Value = (char*) strrchr(Subkey, ',');
+                        if(Value == NULL)
+                            return SynError(it8, "Invalid value for property '%s'.", VarName);
+
+                        // gobble the spaces before the coma, and the coma itself
+                        temp = Value++;
+                        do *temp-- = '\0'; while(temp >= Subkey && *temp == ' ');
+
+                        // gobble any space at the right
+                        temp = Value + strlen(Value) - 1;
+                        while(*temp == ' ') *temp-- = '\0';
+
+                        // trim the strings from the left
+                        Subkey += strspn(Subkey, " ");
+                        Value += strspn(Value, " ");
+
+                        if(Subkey[0] == 0 || Value[0] == 0)
+                            return SynError(it8, "Invalid value for property '%s'.", VarName);
+                        AddToList(it8, &GetTable(it8)->HeaderList, VarName, Subkey, Value, WRITE_PAIR);
+                    }
+                }
 
                 InSymbol(it8);
                 break;
@@ -1793,22 +2058,23 @@
 
 
 static
-BOOL ParseIT8(LPIT8 it8)
+LCMSBOOL ParseIT8(LPIT8 it8, LCMSBOOL nosheet)
 {
-    char* SheetTypePtr;
+    char* SheetTypePtr = it8 ->SheetType;
+
+    if (nosheet == 0) {
 
     // First line is a very special case.
 
     while (isseparator(it8->ch))
             NextCh(it8);
 
-    SheetTypePtr = it8 ->SheetType;
-
     while (it8->ch != '\r' && it8 ->ch != '\n' && it8->ch != '\t' && it8 -> ch != -1) {
 
         *SheetTypePtr++= (char) it8 ->ch;
         NextCh(it8);
     }
+    }
 
     *SheetTypePtr = 0;
     InSymbol(it8);
@@ -1869,6 +2135,12 @@
 
     for (idField = 0; idField < t -> nSamples; idField++)
     {
+        if (t ->DataFormat == NULL) {
+             SynError(it8, "Undefined DATA_FORMAT");
+             return;
+
+        }
+
         Fld = t->DataFormat[idField];
         if (!Fld) continue;
 
@@ -1884,6 +2156,7 @@
                     char Buffer[256];
 
                     strncpy(Buffer, Data, 255);
+                    Buffer[255] = 0;
 
                     if (strlen(Buffer) <= strlen(Data))
                         strcpy(Data, Buffer);
@@ -1916,7 +2189,7 @@
                                     LPTABLE Table = it8 ->Tab + k;
                                     LPKEYVALUE p;
 
-                                    if (IsAvailableOnList(Table->HeaderList, Label, &p)) {
+                                    if (IsAvailableOnList(Table->HeaderList, Label, NULL, &p)) {
 
                                         // Available, keep type and table
                                         char Buffer[256];
@@ -1924,7 +2197,7 @@
                                         char *Type  = p ->Value;
                                         int  nTable = k;
 
-                                        sprintf(Buffer, "%s %d %s", Label, nTable, Type );
+                                        snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type );
 
                                         SetData(it8, i, idField, Buffer);
                                     }
@@ -1948,8 +2221,9 @@
 // that should be something like some printable characters plus a \n
 
 static
-BOOL IsMyBlock(LPBYTE Buffer, size_t n)
+int IsMyBlock(LPBYTE Buffer, size_t n)
 {
+    int cols = 1, space = 0, quot = 0;
     size_t i;
 
     if (n < 10) return FALSE;   // Too small
@@ -1959,9 +2233,26 @@
 
     for (i = 1; i < n; i++) {
 
-        if (Buffer[i] == '\n' || Buffer[i] == '\r' || Buffer[i] == '\t') return TRUE;
-        if (Buffer[i] < 32) return FALSE;
-
+        switch(Buffer[i])
+        {
+        case '\n':
+        case '\r':
+            return quot == 1 || cols > 2 ? 0 : cols;
+        case '\t':
+        case ' ':
+            if(!quot && !space)
+                space = 1;
+            break;
+        case '\"':
+            quot = !quot;
+            break;
+        default:
+            if (Buffer[i] < 32) return 0;
+            if (Buffer[i] > 127) return 0;
+            cols += space;
+            space = 0;
+            break;
+        }
     }
 
     return FALSE;
@@ -1970,7 +2261,7 @@
 
 
 static
-BOOL IsMyFile(const char* FileName)
+int IsMyFile(const char* FileName)
 {
    FILE *fp;
    size_t Size;
@@ -1998,21 +2289,22 @@
     LCMSHANDLE hIT8;
     LPIT8  it8;
 
-    if (!IsMyBlock((LPBYTE) Ptr, len)) return NULL;
+    int type = IsMyBlock((LPBYTE) Ptr, len);
+    if (type == 0) return NULL;
 
     hIT8 = cmsIT8Alloc();
     if (!hIT8) return NULL;
 
     it8 = (LPIT8) hIT8;
-    it8 ->MemoryBlock = (char*) malloc(len + 1);
+    it8 ->MemoryBlock = (char*) _cmsMalloc(len + 1);
 
     strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
     it8 ->MemoryBlock[len] = 0;
 
-    strncpy(it8->FileName, "", MAX_PATH-1);
+    strncpy(it8->FileStack[0]->FileName, "", MAX_PATH-1);
     it8-> Source = it8 -> MemoryBlock;
 
-    if (!ParseIT8(it8)) {
+    if (!ParseIT8(it8, type-1)) {
 
         cmsIT8Free(hIT8);
         return FALSE;
@@ -2021,7 +2313,7 @@
     CookPointers(it8);
     it8 ->nTable = 0;
 
-    free(it8->MemoryBlock);
+     _cmsFree(it8->MemoryBlock);
     it8 -> MemoryBlock = NULL;
 
     return hIT8;
@@ -2036,26 +2328,28 @@
      LCMSHANDLE hIT8;
      LPIT8  it8;
 
-     if (!IsMyFile(cFileName)) return NULL;
+     int type = IsMyFile(cFileName);
+     if (type == 0) return NULL;
 
      hIT8 = cmsIT8Alloc();
      it8 = (LPIT8) hIT8;
      if (!hIT8) return NULL;
 
 
-     it8 ->Stream[0] = fopen(cFileName, "rt");
-
-     if (!it8 ->Stream[0]) {
+     it8 ->FileStack[0]->Stream = fopen(cFileName, "rt");
+
+     if (!it8 ->FileStack[0]->Stream) {
          cmsIT8Free(hIT8);
          return NULL;
      }
 
 
-    strncpy(it8->FileName, cFileName, MAX_PATH-1);
-
-    if (!ParseIT8(it8)) {
-
-            fclose(it8 ->Stream[0]);
+    strncpy(it8->FileStack[0]->FileName, cFileName, MAX_PATH-1);
+    it8->FileStack[0]->FileName[MAX_PATH-1] = 0;
+
+    if (!ParseIT8(it8, type-1)) {
+
+            fclose(it8 ->FileStack[0]->Stream);
             cmsIT8Free(hIT8);
             return NULL;
     }
@@ -2063,7 +2357,7 @@
     CookPointers(it8);
     it8 ->nTable = 0;
 
-    fclose(it8 ->Stream[0]);
+    fclose(it8 ->FileStack[0]->Stream);
     return hIT8;
 
 }
@@ -2078,12 +2372,12 @@
 }
 
 
-int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, char ***PropertyNames)
+int LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, const char ***PropertyNames)
 {
     LPIT8 it8 = (LPIT8) hIT8;
     LPKEYVALUE p;
     int n;
-    char **Props;
+    const char **Props;
     LPTABLE t = GetTable(it8);
 
     // Pass#1 - count properties
@@ -2094,7 +2388,7 @@
     }
 
 
-    Props = (char **) AllocChunk(it8, sizeof(char *) * n);
+    Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
 
     // Pass#2 - Fill pointers
     n = 0;
@@ -2106,6 +2400,41 @@
     return n;
 }
 
+int LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+    LPKEYVALUE p, tmp;
+    int n;
+    const char **Props;
+    LPTABLE t = GetTable(it8);
+
+    if(!IsAvailableOnList(t->HeaderList, cProp, NULL, &p)) {
+        *SubpropertyNames = 0;
+        return 0;
+    }
+
+    // Pass#1 - count properties
+
+    n = 0;
+    for (tmp = p;  tmp != NULL; tmp = tmp->NextSubkey) {
+        if(tmp->Subkey != NULL)
+            n++;
+    }
+
+
+    Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
+
+    // Pass#2 - Fill pointers
+    n = 0;
+    for (tmp = p;  tmp != NULL; tmp = tmp->NextSubkey) {
+        if(tmp->Subkey != NULL)
+            Props[n++] = p ->Subkey;
+    }
+
+    *SubpropertyNames = Props;
+    return n;
+}
+
 static
 int LocatePatch(LPIT8 it8, const char* cPatch)
 {
@@ -2201,7 +2530,7 @@
 }
 
 
-BOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col, const char* Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
 
@@ -2209,7 +2538,7 @@
 }
 
 
-BOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
+LCMSBOOL LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col, double Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
     char Buff[256];
@@ -2260,7 +2589,7 @@
 
 
 
-BOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
+LCMSBOOL LCMSEXPORT cmsIT8SetData(LCMSHANDLE hIT8, const char* cPatch,
                         const char* cSample,
                         const char *Val)
 {
@@ -2305,18 +2634,19 @@
 }
 
 
-BOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+LCMSBOOL LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
                         const char* cSample,
                         double Val)
 {
     LPIT8 it8 = (LPIT8) hIT8;
     char Buff[256];
 
-        sprintf(Buff, it8->DoubleFormatter, Val);
+        snprintf(Buff, 255, it8->DoubleFormatter, Val);
         return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
 
 }
 
+// Buffer should get MAXSTR at least
 
 const char* LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer)
 {
@@ -2327,10 +2657,16 @@
         if (!Data) return NULL;
         if (!buffer) return Data;
 
-        strcpy(buffer, Data);
+        strncpy(buffer, Data, MAXSTR-1);
+        buffer[MAXSTR-1] = 0;
         return buffer;
 }
 
+int LCMSEXPORT cmsIT8GetPatchByName(LCMSHANDLE hIT8, const char *cPatch)
+{
+    return LocatePatch((LPIT8)hIT8, cPatch);
+}
+
 int LCMSEXPORT cmsIT8TableCount(LCMSHANDLE hIT8)
 {
         LPIT8 it8 = (LPIT8) hIT8;
@@ -2356,7 +2692,7 @@
     cLabelFld = cmsIT8GetData(hIT8, cSet, cField);
     if (!cLabelFld) return -1;
 
-    if (sscanf(cLabelFld, "%s %d %s", Label, &nTable, Type) != 3)
+    if (sscanf(cLabelFld, "%255s %d %255s", Label, &nTable, Type) != 3)
             return -1;
 
     if (ExpectedType != NULL && *ExpectedType == 0)
@@ -2371,6 +2707,19 @@
 }
 
 
+LCMSBOOL LCMSEXPORT cmsIT8SetIndexColumn(LCMSHANDLE hIT8, const char* cSample)
+{
+    LPIT8 it8 = (LPIT8) hIT8;
+
+    int pos = LocateSample(it8, cSample);
+    if(pos == -1)
+        return FALSE;
+
+    it8->Tab[it8->nTable].SampleID = pos;
+    return TRUE;
+}
+
+
 void LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE hIT8, const char* Formatter)
 {
     LPIT8 it8 = (LPIT8) hIT8;
@@ -2380,3 +2729,4 @@
     else
         strcpy(it8->DoubleFormatter, Formatter);
 }
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -256,7 +256,7 @@
 // Return TRUE if both m and of are empy -- "m" being identity and "of" being 0
 
 static
-BOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
+LCMSBOOL IdentityParameters(LPWMAT3 m, LPWVEC3 of)
 {
     WVEC3 wv0;
 
@@ -661,3 +661,6 @@
 
        return rc;
 }
+
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -57,6 +57,7 @@
 // errors.
 
 void cdecl cmsSignalError(int ErrorCode, const char *ErrorText, ...);
+
 int  LCMSEXPORT cmsErrorAction(int lAbort);
 void LCMSEXPORT cmsSetErrorHandler(cmsErrorHandlerFunction Fn);
 
@@ -96,7 +97,7 @@
 
             char Buffer[1024];
 
-            vsprintf(Buffer, ErrorText, args);
+            vsnprintf(Buffer, 1023, ErrorText, args);
             va_end(args);
 
             if (UserErrorHandler(ErrorCode, Buffer)) {
@@ -118,8 +119,8 @@
               char Buffer1[1024];
               char Buffer2[256];
 
-              sprintf(Buffer1, "Error #%x; ", ErrorCode);
-              vsprintf(Buffer2, ErrorText, args);
+              snprintf(Buffer1,  767, "Error #%x; ", ErrorCode);
+              vsnprintf(Buffer2, 255, ErrorText, args);
               strcat(Buffer1, Buffer2);
               MessageBox(NULL, Buffer1, "Little cms",
                                           MB_OK|MB_ICONSTOP|MB_TASKMODAL);
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -63,9 +63,9 @@
 LPGAMMATABLE LCMSEXPORT cmsBuildParametricGamma(int nEntries, int Type, double Params[]);
 LPGAMMATABLE LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma);
 LPGAMMATABLE LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma, LPGAMMATABLE OutGamma, int nPoints);
-BOOL         LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
+LCMSBOOL         LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
 
-BOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
+LCMSBOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nPoints);
 
 
 // Sampled curves
@@ -74,7 +74,7 @@
 void           cdecl cmsFreeSampledCurve(LPSAMPLEDCURVE p);
 void           cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
 void           cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
-BOOL           cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
+LCMSBOOL       cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
 void           cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
 
 LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
@@ -84,7 +84,6 @@
 
 // ----------------------------------------------------------------------------------------
 
-// #define DEBUG 1
 
 #define MAX_KNOTS   4096
 typedef float vec[MAX_KNOTS+1];
@@ -144,14 +143,14 @@
        LPGAMMATABLE p;
        size_t size;
 
-       if (nEntries > 65530) {
-                cmsSignalError(LCMS_ERRC_WARNING, "Couldn't create gammatable of more than 65530 entries; 65530 assumed");
-                nEntries = 65530;
+       if (nEntries > 65530 || nEntries <= 0) {
+                cmsSignalError(LCMS_ERRC_ABORTED, "Couldn't create gammatable of more than 65530 entries");
+                return NULL;
        }
 
        size = sizeof(GAMMATABLE) + (sizeof(WORD) * (nEntries-1));
 
-       p = (LPGAMMATABLE) malloc(size);
+       p = (LPGAMMATABLE) _cmsMalloc(size);
        if (!p) return NULL;
 
        ZeroMemory(p, size);
@@ -164,7 +163,7 @@
 
 void LCMSEXPORT cmsFreeGamma(LPGAMMATABLE Gamma)
 {
-       if (Gamma) free(Gamma);
+       if (Gamma)  _cmsFree(Gamma);
 }
 
 
@@ -278,6 +277,15 @@
        LPWORD InPtr;
        LPGAMMATABLE p;
 
+       // Try to reverse it analytically whatever possible
+       if (InGamma -> Seed.Type > 0 && InGamma -> Seed.Type <= 5 &&
+            _cmsCrc32OfGammaTable(InGamma) == InGamma -> Seed.Crc32) {
+
+                return cmsBuildParametricGamma(nResultSamples, -(InGamma -> Seed.Type), InGamma ->Seed.Params);
+       }
+
+
+       // Nope, reverse the table
        p = cmsAllocGamma(nResultSamples);
        if (!p) return NULL;
 
@@ -528,7 +536,7 @@
 
 // Smooths a curve sampled at regular intervals
 
-BOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
+LCMSBOOL LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda)
 
 {
     vec w, y, z;
@@ -640,13 +648,13 @@
 {
     LPSAMPLEDCURVE pOut;
 
-    pOut = (LPSAMPLEDCURVE) malloc(sizeof(SAMPLEDCURVE));
+    pOut = (LPSAMPLEDCURVE) _cmsMalloc(sizeof(SAMPLEDCURVE));
     if (pOut == NULL)
             return NULL;
 
-    if((pOut->Values = (double *) malloc(nItems * sizeof(double))) == NULL)
+    if((pOut->Values = (double *) _cmsMalloc(nItems * sizeof(double))) == NULL)
     {
-        free(pOut);
+         _cmsFree(pOut);
         return NULL;
     }
 
@@ -659,8 +667,8 @@
 
 void cmsFreeSampledCurve(LPSAMPLEDCURVE p)
 {
-    free((LPVOID) p -> Values);
-    free((LPVOID) p);
+     _cmsFree((LPVOID) p -> Values);
+     _cmsFree((LPVOID) p);
 }
 
 
@@ -731,7 +739,7 @@
 
 // Smooths a curve sampled at regular intervals
 
-BOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
+LCMSBOOL cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double lambda)
 {
     vec w, y, z;
     int i, nItems;
@@ -915,14 +923,11 @@
 
 // Smooth endpoints (used in Black/White compensation)
 
-BOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
+LCMSBOOL _cmsSmoothEndpoints(LPWORD Table, int nEntries)
 {
     vec w, y, z;
     int i, Zeros, Poles;
 
-#ifdef DEBUG
-        ASAVE(Table, nEntries, "nonsmt.txt");
-#endif
 
 
     if (cmsIsLinear(Table, nEntries)) return FALSE; // Nothing to do
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -66,7 +66,7 @@
 */
 
 
-BOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
+LCMSBOOL _cmsEndPointsBySpace(icColorSpaceSignature Space, WORD **White, WORD **Black,
                             int *nOutputs)
 {
        // Only most common spaces
@@ -376,7 +376,6 @@
     double bs = Lab2 ->b;
     double Cs = sqrt( Sqr(as) + Sqr(bs) );
 
-
     double G = 0.5 * ( 1 - sqrt(pow((C + Cs) / 2 , 7.0) / (pow((C + Cs) / 2, 7.0) + pow(25.0, 7.0) ) ));
 
     double a_p = (1 + G ) * a1;
@@ -390,15 +389,21 @@
     double C_ps = sqrt(Sqr(a_ps) + Sqr(b_ps));
     double h_ps = atan2deg(a_ps, b_ps);
 
-
-
     double meanC_p =(C_p + C_ps) / 2;
 
-    double meanh_p = fabs(h_ps-h_p) <= 180 ? (h_ps + h_p)/2 : (h_ps+h_p-360)/2;
+    double hps_plus_hp  = h_ps + h_p;
+    double hps_minus_hp = h_ps - h_p;
+
+    double meanh_p = fabs(hps_minus_hp) <= 180.000001 ? (hps_plus_hp)/2 :
+                            (hps_plus_hp) < 360 ? (hps_plus_hp + 360)/2 :
+                                                 (hps_plus_hp - 360)/2;
 
-    double delta_h = fabs(h_p - h_ps) <= 180 ? fabs(h_p - h_ps) : 360 - fabs(h_p - h_ps);
-    double delta_L = fabs(L1 - Ls);
-    double delta_C = fabs(C_p - C_ps);
+    double delta_h = (hps_minus_hp) <= -180.000001 ?  (hps_minus_hp + 360) :
+                            (hps_minus_hp) > 180 ? (hps_minus_hp - 360) :
+                                                    (hps_minus_hp);
+    double delta_L = (Ls - L1);
+    double delta_C = (C_ps - C_p );
+
 
     double delta_H =2 * sqrt(C_ps*C_p) * sin(RADIANES(delta_h) / 2);
 
@@ -1065,7 +1070,7 @@
 // Check for monotonicity.
 
 static
-BOOL IsMonotonic(LPGAMMATABLE t)
+LCMSBOOL IsMonotonic(LPGAMMATABLE t)
 {
     int n = t -> nEntries;
     int i, last;
@@ -1088,7 +1093,7 @@
 // Check for endpoints
 
 static
-BOOL HasProperEndpoints(LPGAMMATABLE t)
+LCMSBOOL HasProperEndpoints(LPGAMMATABLE t)
 {
     if (t ->GammaTable[0] != 0) return FALSE;
     if (t ->GammaTable[t ->nEntries-1] != 0xFFFF) return FALSE;
@@ -1109,7 +1114,7 @@
     unsigned int t, i, v;
     int j;
     WORD In[MAXCHANNELS], Out[MAXCHANNELS];
-    BOOL lIsSuitable;
+    LCMSBOOL lIsSuitable;
     _LPcmsTRANSFORM InputXForm   = (_LPcmsTRANSFORM) h[0];
     _LPcmsTRANSFORM OutputXForm  = (_LPcmsTRANSFORM) h[nTransforms-1];
 
@@ -1126,10 +1131,10 @@
     }
 
 
-    // Do nothing on all but RGB to RGB transforms
+    // Do nothing on all but Gray/RGB to Gray/RGB transforms
 
-    if ((InputXForm ->EntryColorSpace != icSigRgbData) ||
-        (OutputXForm->ExitColorSpace  != icSigRgbData)) return;
+    if (((InputXForm ->EntryColorSpace != icSigRgbData) && (InputXForm ->EntryColorSpace != icSigGrayData)) ||
+        ((OutputXForm->ExitColorSpace  != icSigRgbData) && (OutputXForm->ExitColorSpace  != icSigGrayData))) return;
 
 
     for (t = 0; t < Grid -> InputChan; t++)
@@ -1169,10 +1174,13 @@
         if (!HasProperEndpoints(Trans[t]))
                     lIsSuitable = FALSE;
 
+        /*
         // Exclude if transfer function is not smooth enough
         // to be modelled as a gamma function, or the gamma is reversed
+
         if (cmsEstimateGamma(Trans[t]) < 1.0)
                     lIsSuitable = FALSE;
+        */
 
     }
 
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -282,7 +282,7 @@
 // Fills optimization parameters
 
 void cmsCalcCLUT16ParamsEx(int nSamples, int InputChan, int OutputChan,
-                                            BOOL lUseTetrahedral, LPL16PARAMS p)
+                                            LCMSBOOL lUseTetrahedral, LPL16PARAMS p)
 {
        int clutPoints;
 
@@ -579,7 +579,7 @@
 
                 // Identify if value fall downto 0 or FFFF zone
                 if (Value == 0) return 0;
-                if (Value == 0xFFFF) return 0xFFFF;
+               // if (Value == 0xFFFF) return 0xFFFF;
 
                 // else restrict to valid zone
 
@@ -631,7 +631,7 @@
         a = (y1 - y0) / (x1 - x0);
         b = y0 - a * x0;
 
-        if (a == 0) return (WORD) x;
+        if (fabs(a) < 0.01) return (WORD) x;
 
         f = ((Value - b) / a);
 
@@ -763,7 +763,7 @@
     X0 = p -> opta3 * x0;
     X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
 
-        Y0 = p -> opta2 * y0;
+    Y0 = p -> opta2 * y0;
     Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
 
     Z0 = p -> opta1 * z0;
@@ -942,7 +942,7 @@
     X0 = p -> opta3 * x0;
     X1 = X0 + (Input[0] == 0xFFFFU ? 0 : p->opta3);
 
-        Y0 = p -> opta2 * y0;
+    Y0 = p -> opta2 * y0;
     Y1 = Y0 + (Input[1] == 0xFFFFU ? 0 : p->opta2);
 
     Z0 = p -> opta1 * z0;
@@ -1009,11 +1009,11 @@
 
         Rest = c1 * rx + c2 * ry + c3 * rz;
 
-                // There is a lot of math hidden in this expression. The rest is in fixed domain
-                // and the result in 0..ffff domain. So the complete expression should be
-                // ROUND_FIXED_TO_INT(ToFixedDomain(Rest)) But that can be optimized as (Rest + 0x7FFF) / 0xFFFF
+        // There is a lot of math hidden in this expression. The rest is in fixed domain
+        // and the result in 0..ffff domain. So the complete expression should be
+        // ROUND_FIXED_TO_INT(ToFixedDomain(Rest)) But that can be optimized as (Rest + 0x7FFF) / 0xFFFF
 
-                Output[OutChan] = (WORD) (c0 + ((Rest + 0x7FFF) / 0xFFFF));
+        Output[OutChan] = (WORD) (c0 + ((Rest + 0x7FFF) / 0xFFFF));
 
     }
 
@@ -1131,3 +1131,4 @@
 }
 
 #undef DENS
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -62,7 +62,7 @@
 typedef struct {
                 LPBYTE Block;           // Points to allocated memory
                 size_t Size;            // Size of allocated memory
-                int Pointer;            // Points to current location
+                size_t Pointer;         // Points to current location
                 int FreeBlockOnClose;   // As title
 
                 } FILEMEM;
@@ -70,18 +70,19 @@
 static
 LPVOID MemoryOpen(LPBYTE Block, size_t Size, char Mode)
 {
-    FILEMEM* fm = (FILEMEM*) malloc(sizeof(FILEMEM));
+    FILEMEM* fm = (FILEMEM*) _cmsMalloc(sizeof(FILEMEM));
+    if (fm == NULL) return NULL;
+
     ZeroMemory(fm, sizeof(FILEMEM));
 
     if (Mode == 'r') {
 
-        fm ->Block   = (LPBYTE) malloc(Size);
+        fm ->Block   = (LPBYTE) _cmsMalloc(Size);
         if (fm ->Block == NULL) {
-            free(fm);
+             _cmsFree(fm);
             return NULL;
         }
 
-
         CopyMemory(fm->Block, Block, Size);
         fm ->FreeBlockOnClose = TRUE;
     }
@@ -103,13 +104,27 @@
      FILEMEM* ResData = (FILEMEM*) Icc ->stream;
      LPBYTE Ptr;
      size_t len = size * count;
+     size_t extent = ResData -> Pointer + len;
 
+        if (len == 0) {
+                return 0;
+        }
 
-     if (ResData -> Pointer + len > ResData -> Size){
+        if (len / size != count) {
+          cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with count / size.");
+          return 0;
+      }
+
+      if (extent < len || extent < ResData -> Pointer) {
+          cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Integer overflow with len.");
+          return 0;
+      }
+
+      if (ResData -> Pointer + len > ResData -> Size) {
 
          len = (ResData -> Size - ResData -> Pointer);
-         cmsSignalError(LCMS_ERRC_WARNING, "Read from memory error. Got %d bytes, block should be of %d bytes", len * size, count * size);
-
+         cmsSignalError(LCMS_ERRC_ABORTED, "Read from memory error. Got %d bytes, block should be of %d bytes", len * size, count * size);
+         return 0;
      }
 
     Ptr  = ResData -> Block;
@@ -123,7 +138,7 @@
 // SEEK_CUR is assumed
 
 static
-BOOL MemorySeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+LCMSBOOL MemorySeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
 {
     FILEMEM* ResData = (FILEMEM*) Icc ->stream;
 
@@ -147,18 +162,19 @@
 }
 
 
-// Writes data to memory, also keeps used space for further reference
+// Writes data to memory, also keeps used space for further reference. NO CHECK IS PERFORMED
 
 static
-BOOL MemoryWrite(struct _lcms_iccprofile_struct* Icc, size_t size, void *Ptr)
+LCMSBOOL MemoryWrite(struct _lcms_iccprofile_struct* Icc, size_t size, void *Ptr)
 {
         FILEMEM* ResData = (FILEMEM*) Icc ->stream;
 
        if (size == 0) return TRUE;
 
        if (ResData != NULL)
-           CopyMemory(ResData ->Block + Icc ->UsedSpace, Ptr, size);
+           CopyMemory(ResData ->Block + ResData ->Pointer, Ptr, size);
 
+       ResData->Pointer += size;
        Icc->UsedSpace += size;
 
        return TRUE;
@@ -166,15 +182,37 @@
 
 
 static
-BOOL MemoryClose(struct _lcms_iccprofile_struct* Icc)
+LCMSBOOL MemoryGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
+{
+    FILEMEM* ResData = (FILEMEM*) Icc->stream;
+
+    void* newBlock = NULL;
+
+    /* Follow same policies as functions in lcms.h  */
+    if (ResData->Size + size < 0) return NULL;
+    if (ResData->Size + size > ((size_t)1024*1024*500)) return NULL;
+
+    newBlock = realloc(ResData->Block, ResData->Size + size);
+
+    if (!newBlock) {
+        return FALSE;
+    }
+    ResData->Block = newBlock;
+    ResData->Size += size;
+    return TRUE;
+}
+
+
+static
+LCMSBOOL MemoryClose(struct _lcms_iccprofile_struct* Icc)
 {
     FILEMEM* ResData = (FILEMEM*) Icc ->stream;
 
     if (ResData ->FreeBlockOnClose) {
 
-        if (ResData ->Block) free(ResData ->Block);
+        if (ResData ->Block)  _cmsFree(ResData ->Block);
     }
-    free(ResData);
+     _cmsFree(ResData);
     return 0;
 }
 
@@ -192,7 +230,7 @@
 {
     size_t nReaded = fread(buffer, size, count, (FILE*) Icc->stream);
     if (nReaded != count) {
-            cmsSignalError(LCMS_ERRC_WARNING, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
+            cmsSignalError(LCMS_ERRC_ABORTED, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
             return 0;
     }
 
@@ -201,7 +239,7 @@
 
 
 static
-BOOL FileSeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
+LCMSBOOL FileSeek(struct _lcms_iccprofile_struct* Icc, size_t offset)
 {
     if (fseek((FILE*) Icc ->stream, (long) offset, SEEK_SET) != 0) {
 
@@ -223,7 +261,7 @@
 
 
 static
-BOOL FileWrite(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr)
+LCMSBOOL FileWrite(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr)
 {
        if (size == 0) return TRUE;
 
@@ -239,7 +277,14 @@
 
 
 static
-BOOL FileClose(struct _lcms_iccprofile_struct* Icc)
+LCMSBOOL FileGrow(struct _lcms_iccprofile_struct* Icc, size_t size)
+{
+  return TRUE;
+}
+
+
+static
+LCMSBOOL FileClose(struct _lcms_iccprofile_struct* Icc)
 {
     return fclose((FILE*) Icc ->stream);
 }
@@ -252,7 +297,7 @@
 cmsHPROFILE _cmsCreateProfilePlaceholder(void)
 {
 
-    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) malloc(sizeof(LCMSICCPROFILE));
+    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) _cmsMalloc(sizeof(LCMSICCPROFILE));
     if (Icc == NULL) return NULL;
 
     // Empty values
@@ -290,7 +335,7 @@
 // Search for a specific tag in tag dictionary
 // Returns position or -1 if tag not found
 
-icInt32Number _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, BOOL lSignalError)
+icInt32Number _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, LCMSBOOL lSignalError)
 {
        icInt32Number i;
 
@@ -311,7 +356,7 @@
 
 // Check existance
 
-BOOL LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig)
+LCMSBOOL LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig)
 {
        LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
@@ -330,7 +375,7 @@
 
     if (i >=0) {
 
-        if (Icc -> TagPtrs[i]) free(Icc -> TagPtrs[i]);
+        if (Icc -> TagPtrs[i]) _cmsFree(Icc -> TagPtrs[i]);
     }
     else  {
 
@@ -341,11 +386,14 @@
 
             cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", MAX_TABLE_TAG);
             Icc ->TagCount = MAX_TABLE_TAG-1;
+            return NULL;
         }
     }
 
 
-    Ptr = malloc(size);
+    Ptr = _cmsMalloc(size);
+    if (Ptr == NULL) return NULL;
+
     CopyMemory(Ptr, Init, size);
 
     Icc ->TagNames[i] = sig;
@@ -376,12 +424,15 @@
     if (NewIcc == NULL) return NULL;
 
     strncpy(NewIcc -> PhysicalFile, FileName, MAX_PATH-1);
+    NewIcc -> PhysicalFile[MAX_PATH-1] = 0;
+
     NewIcc ->stream = ICCfile;
 
     NewIcc ->Read  = FileRead;
     NewIcc ->Seek  = FileSeek;
     NewIcc ->Tell  = FileTell;
     NewIcc ->Close = FileClose;
+    NewIcc ->Grow  = FileGrow;
     NewIcc ->Write = NULL;
 
     NewIcc ->IsWrite = FALSE;
@@ -419,7 +470,8 @@
     NewIcc ->Seek  = MemorySeek;
     NewIcc ->Tell  = MemoryTell;
     NewIcc ->Close = MemoryClose;
-    NewIcc ->Write = NULL;
+    NewIcc ->Grow  = MemoryGrow;
+    NewIcc ->Write = MemoryWrite;
 
     NewIcc ->IsWrite = FALSE;
 
@@ -476,7 +528,7 @@
 
 
 
-BOOL LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
 {
      LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) hProfile;
      *Dest = Icc -> MediaWhitePoint;
@@ -484,14 +536,14 @@
 }
 
 
-BOOL LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
 {
       LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) hProfile;
       *Dest = Icc -> MediaBlackPoint;
       return TRUE;
 }
 
-BOOL  LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
+LCMSBOOL  LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile)
 {
        LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
        *Dest = Icc -> Illuminant;
@@ -549,7 +601,7 @@
 }
 
 
-BOOL LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
 {
     LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
     CopyMemory(Dest, &Icc ->Created, sizeof(struct tm));
@@ -570,23 +622,18 @@
        Icc -> PCS = pcs;
 }
 
-
-
 icColorSpaceSignature LCMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
 {
        LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
        return Icc -> ColorSpace;
 }
 
-
-
 void LCMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, icColorSpaceSignature sig)
 {
        LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
        Icc -> ColorSpace = sig;
 }
 
-
 icProfileClassSignature LCMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
 {
        LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
@@ -599,7 +646,6 @@
        return (DWORD) Icc -> Version;
 }
 
-
 void LCMSEXPORT cmsSetProfileICCversion(cmsHPROFILE hProfile, DWORD Version)
 {
    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) hProfile;
@@ -638,7 +684,7 @@
 
 // This is tricky, since LUT structs does have pointers
 
-BOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile, icTagSignature sig, const void* lut)
+LCMSBOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile, icTagSignature sig, const void* lut)
 {
        LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
        LPLUT Orig, Stored;
@@ -666,7 +712,7 @@
 }
 
 
-BOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* XYZ)
+LCMSBOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* XYZ)
 {
        LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
@@ -675,7 +721,7 @@
 }
 
 
-BOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile, icTagSignature sig, const char* Text)
+LCMSBOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile, icTagSignature sig, const char* Text)
 {
        LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
@@ -683,7 +729,7 @@
        return TRUE;
 }
 
-BOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction)
+LCMSBOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
@@ -692,7 +738,7 @@
 }
 
 
-BOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm)
+LCMSBOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
@@ -701,7 +747,7 @@
 }
 
 
-BOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ pseq)
+LCMSBOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ pseq)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
@@ -711,28 +757,40 @@
 }
 
 
-BOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
+LCMSBOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
     _cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
-    return FALSE;
+    return TRUE;
 }
 
 
-BOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime)
+LCMSBOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
     _cmsInitTag(Icc, sig, sizeof(struct tm), DateTime);
-    return FALSE;
+    return TRUE;
 }
 
 
-BOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
+LCMSBOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
 
     _cmsInitTag(Icc, sig, sizeof(cmsNAMEDCOLORLIST) + (nc ->nColors - 1) * sizeof(cmsNAMEDCOLOR), nc);
-    return FALSE;
+    return TRUE;
 }
+
+
+LCMSBOOL LCMSEXPORT _cmsAddChromaticAdaptationTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* mat)
+{
+    LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
+
+    _cmsInitTag(Icc, sig, 3*sizeof(cmsCIEXYZ), mat);
+    return TRUE;
+
+}
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -149,6 +149,7 @@
 
 #endif
 
+
 // Transports to properly encoded values - note that icc profiles does use
 // big endian notation.
 
@@ -216,7 +217,8 @@
 {
     icTagBase Base;
 
-    Icc -> Read(&Base, sizeof(icTagBase), 1, Icc);
+    if (Icc -> Read(&Base, sizeof(icTagBase), 1, Icc) != 1)
+                return (icTagTypeSignature) 0;
     AdjustEndianess32((LPBYTE) &Base.sig);
 
     return Base.sig;
@@ -288,13 +290,15 @@
 // Read profile header and validate it
 
 static
-LPLCMSICCPROFILE ReadHeader(LPLCMSICCPROFILE Icc, BOOL lIsFromMemory)
+LPLCMSICCPROFILE ReadHeader(LPLCMSICCPROFILE Icc, LCMSBOOL lIsFromMemory)
 {
      icTag Tag;
      icHeader Header;
      icInt32Number TagCount, i;
-
-     Icc -> Read(&Header, sizeof(icHeader), 1, Icc);
+     icUInt32Number extent;
+
+       if (Icc -> Read(&Header, sizeof(icHeader), 1, Icc) != 1)
+                      goto ErrorCleanup;
 
        // Convert endian
 
@@ -306,14 +310,13 @@
        AdjustEndianess32((LPBYTE) &Header.pcs);
        AdjustEndianess32((LPBYTE) &Header.magic);
        AdjustEndianess32((LPBYTE) &Header.flags);
-           AdjustEndianess32((LPBYTE) &Header.attributes[0]);
+       AdjustEndianess32((LPBYTE) &Header.attributes[0]);
        AdjustEndianess32((LPBYTE) &Header.renderingIntent);
 
        // Validate it
 
        if (Header.magic != icMagicNumber) goto ErrorCleanup;
 
-
        if (Icc ->Read(&TagCount, sizeof(icInt32Number), 1, Icc) != 1)
                      goto ErrorCleanup;
 
@@ -324,7 +327,7 @@
        Icc -> PCS             = Header.pcs;
        Icc -> RenderingIntent = (icRenderingIntent) Header.renderingIntent;
        Icc -> flags           = Header.flags;
-           Icc -> attributes      = Header.attributes[0];
+       Icc -> attributes      = Header.attributes[0];
        Icc -> Illuminant.X    = Convert15Fixed16(Header.illuminant.X);
        Icc -> Illuminant.Y    = Convert15Fixed16(Header.illuminant.Y);
        Icc -> Illuminant.Z    = Convert15Fixed16(Header.illuminant.Z);
@@ -348,7 +351,7 @@
 
        // Read tag directory
 
-       if (TagCount > MAX_TABLE_TAG) {
+       if (TagCount > MAX_TABLE_TAG || TagCount < 0) {
 
            cmsSignalError(LCMS_ERRC_ABORTED, "Too many tags (%d)", TagCount);
            goto ErrorCleanup;
@@ -357,12 +360,18 @@
        Icc -> TagCount = TagCount;
        for (i=0; i < TagCount; i++) {
 
-              Icc ->Read(&Tag, sizeof(icTag), 1, Icc);
+              if (Icc ->Read(&Tag, sizeof(icTag), 1, Icc) != 1)
+                  goto ErrorCleanup;
 
               AdjustEndianess32((LPBYTE) &Tag.offset);
               AdjustEndianess32((LPBYTE) &Tag.size);
               AdjustEndianess32((LPBYTE) &Tag.sig);            // Signature
 
+              // Perform some sanity check. Offset + size should fall inside file.
+              extent = Tag.offset + Tag.size;
+              if (extent > Header.size || extent < Tag.offset)
+                  goto ErrorCleanup;
+
               Icc -> TagNames[i]   = Tag.sig;
               Icc -> TagOffsets[i] = Tag.offset;
               Icc -> TagSizes[i]   = Tag.size;
@@ -381,13 +390,10 @@
              cmsSignalError(LCMS_ERRC_ABORTED, "Corrupted profile: '%s'", Icc->PhysicalFile);
 
 
-       free(Icc);
+        _cmsFree(Icc);
        return NULL;
 }
 
-
-
-
 static
 unsigned int uipow(unsigned int a, unsigned int b) {
         unsigned int rv = 1;
@@ -497,7 +503,7 @@
 // The infamous LUT 8
 
 static
-void ReadLUT8(LPLCMSICCPROFILE Icc, LPLUT NewLUT, icTagSignature sig)
+LCMSBOOL ReadLUT8(LPLCMSICCPROFILE Icc, LPLUT NewLUT, icTagSignature sig)
 {
     icLut8 LUT8;
     LPBYTE Temp;
@@ -506,7 +512,7 @@
     unsigned int AllLinear;
     LPWORD PtrW;
 
-       Icc ->Read(&LUT8, sizeof(icLut8) - SIZEOF_UINT8_ALIGNED, 1, Icc);
+       if (Icc ->Read(&LUT8, sizeof(icLut8) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return FALSE;
 
        NewLUT -> wFlags        = LUT_HASTL1|LUT_HASTL2|LUT_HAS3DGRID;
        NewLUT -> cLutPoints    = LUT8.clutPoints;
@@ -515,6 +521,10 @@
        NewLUT -> InputEntries  = 256;
        NewLUT -> OutputEntries = 256;
 
+       // Do some checking
+       if (!_cmsValidateLUT(NewLUT)) {
+          return FALSE;
+       }
 
        AdjustEndianess32((LPBYTE) &LUT8.e00);
        AdjustEndianess32((LPBYTE) &LUT8.e01);
@@ -550,13 +560,24 @@
 
        // Copy input tables
 
-       Temp = (LPBYTE) malloc(256);
+       Temp = (LPBYTE) _cmsMalloc(256);
+       if (Temp == NULL) return FALSE;
+
        AllLinear = 0;
        for (i=0; i < NewLUT -> InputChan; i++) {
 
-              PtrW = (LPWORD) malloc(sizeof(WORD) * 256);
+              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
+              if (PtrW == NULL) {
+                   _cmsFree(Temp);
+                  return FALSE;
+                  }
+
               NewLUT -> L1[i] = PtrW;
-              Icc ->Read(Temp, 1, 256, Icc);
+              if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
+                   _cmsFree(Temp);
+                  return FALSE;
+                  }
+
               for (j=0; j < 256; j++)
                      PtrW[j] = TO16_TAB(Temp[j]);
                      AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
@@ -569,7 +590,7 @@
               NewLUT -> wFlags &= ~LUT_HASTL1;
        }
 
-       free(Temp);
+        _cmsFree(Temp);
 
        // Copy 3D CLUT
 
@@ -578,9 +599,20 @@
 
        if (nTabSize > 0) {
 
-            PtrW = (LPWORD) malloc(sizeof(WORD) * nTabSize);
-            Temp = (LPBYTE) malloc(nTabSize);
-            Icc ->Read(Temp, 1, nTabSize, Icc);
+            PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+            if (PtrW == NULL) return FALSE;
+
+            Temp = (LPBYTE) _cmsMalloc(nTabSize);
+            if (Temp == NULL) {
+                 _cmsFree(PtrW);
+                return FALSE;
+                }
+
+            if (Icc ->Read(Temp, 1, nTabSize, Icc) != nTabSize) {
+                 _cmsFree(Temp);
+                _cmsFree(PtrW);
+                return FALSE;
+                }
 
             NewLUT -> T = PtrW;
             NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
@@ -589,25 +621,37 @@
 
                      *PtrW++ = TO16_TAB(Temp[i]);
             }
-            free(Temp);
+            _cmsFree(Temp);
        }
        else {
            NewLUT ->T = NULL;
            NewLUT ->Tsize = 0;
-           NewLUT -> wFlags &= ~LUT_HAS3DGRID;
+           NewLUT ->wFlags &= ~LUT_HAS3DGRID;
        }
 
 
-
        // Copy output tables
 
-       Temp = (LPBYTE) malloc(256);
+       Temp = (LPBYTE) _cmsMalloc(256);
+       if (Temp == NULL) {
+           return FALSE;
+           }
+
        AllLinear = 0;
        for (i=0; i < NewLUT -> OutputChan; i++) {
 
-              PtrW = (LPWORD) malloc(sizeof(WORD) * 256);
+              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * 256);
+              if (PtrW == NULL) {
+                  _cmsFree(Temp);
+                  return FALSE;
+                  }
+
               NewLUT -> L2[i] = PtrW;
-              Icc ->Read(Temp, 1, 256, Icc);
+              if (Icc ->Read(Temp, 1, 256, Icc) != 256) {
+                  _cmsFree(Temp);
+                  return FALSE;
+                  }
+
               for (j=0; j < 256; j++)
                      PtrW[j] = TO16_TAB(Temp[j]);
                      AllLinear += cmsIsLinear(NewLUT -> L2[i], 256);
@@ -621,7 +665,7 @@
        }
 
 
-       free(Temp);
+       _cmsFree(Temp);
 
        cmsCalcL16Params(NewLUT -> InputEntries,  &NewLUT -> In16params);
        cmsCalcL16Params(NewLUT -> OutputEntries, &NewLUT -> Out16params);
@@ -646,6 +690,15 @@
            // some profiles does claim to do that. Poor lcms will try
            // to detect such condition and fix up "on the fly".
 
+           switch (sig) {
+
+            case icSigBToA0Tag:
+            case icSigBToA1Tag:
+            case icSigBToA2Tag:
+            case icSigGamutTag:
+            case icSigPreview0Tag:
+            case icSigPreview1Tag:
+            case icSigPreview2Tag:
            {
                LPWORD WhiteLab, ExpectedWhite;
                WORD WhiteFixed[MAXCHANNELS], WhiteUnfixed[MAXCHANNELS];
@@ -685,9 +738,13 @@
                }
 
            }
-
+           break;
+
+        default:;
+        }
        }
 
+       return TRUE;
 }
 
 
@@ -696,7 +753,7 @@
 // Case LUT 16
 
 static
-void ReadLUT16(LPLCMSICCPROFILE Icc, LPLUT NewLUT)
+LCMSBOOL ReadLUT16(LPLCMSICCPROFILE Icc, LPLUT NewLUT)
 {
     icLut16 LUT16;
     size_t nTabSize;
@@ -705,7 +762,8 @@
     LPWORD PtrW;
 
 
-       Icc ->Read(&LUT16, sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, 1, Icc);
+       if (Icc ->Read(&LUT16, sizeof(icLut16)- SIZEOF_UINT16_ALIGNED, 1, Icc) != 1)
+            return FALSE;
 
        NewLUT -> wFlags        = LUT_HASTL1 | LUT_HASTL2 | LUT_HAS3DGRID;
        NewLUT -> cLutPoints    = LUT16.clutPoints;
@@ -718,6 +776,9 @@
        NewLUT -> InputEntries  = LUT16.inputEnt;
        NewLUT -> OutputEntries = LUT16.outputEnt;
 
+       if (!_cmsValidateLUT(NewLUT)) {
+         return FALSE;
+       }
 
        // Matrix handling
 
@@ -754,9 +815,14 @@
        AllLinear = 0;
        for (i=0; i < NewLUT -> InputChan; i++) {
 
-              PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> InputEntries);
+              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
+              if (PtrW == NULL) return FALSE;
+
               NewLUT -> L1[i] = PtrW;
-              Icc ->Read(PtrW, sizeof(WORD), NewLUT -> InputEntries, Icc);
+              if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> InputEntries, Icc) != NewLUT -> InputEntries) {
+                  return FALSE;
+                  }
+
               AdjustEndianessArray16(PtrW, NewLUT -> InputEntries);
               AllLinear += cmsIsLinear(NewLUT -> L1[i], NewLUT -> InputEntries);
               }
@@ -775,12 +841,17 @@
                                                 NewLUT->InputChan));
        if (nTabSize > 0) {
 
-           PtrW = (LPWORD) malloc(sizeof(WORD) * nTabSize);
+           PtrW = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+           if (PtrW == NULL)
+               return FALSE;
 
            NewLUT -> T = PtrW;
            NewLUT -> Tsize = (unsigned int) (nTabSize * sizeof(WORD));
 
-           Icc -> Read(PtrW, sizeof(WORD), nTabSize, Icc);
+           if (Icc -> Read(PtrW, sizeof(WORD), nTabSize, Icc) != nTabSize) {
+               return FALSE;
+           }
+
            AdjustEndianessArray16(NewLUT -> T, nTabSize);
        }
        else {
@@ -794,9 +865,16 @@
        AllLinear = 0;
        for (i=0; i < NewLUT -> OutputChan; i++) {
 
-              PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> OutputEntries);
+              PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
+              if (PtrW == NULL) {
+                  return FALSE;
+                  }
+
               NewLUT -> L2[i] = PtrW;
-              Icc ->Read(PtrW, sizeof(WORD), NewLUT -> OutputEntries, Icc);
+              if (Icc ->Read(PtrW, sizeof(WORD), NewLUT -> OutputEntries, Icc) != NewLUT -> OutputEntries) {
+                  return FALSE;
+                  }
+
               AdjustEndianessArray16(PtrW, NewLUT -> OutputEntries);
               AllLinear += cmsIsLinear(NewLUT -> L2[i], NewLUT -> OutputEntries);
               }
@@ -814,6 +892,8 @@
        cmsCalcCLUT16Params(NewLUT -> cLutPoints,  NewLUT -> InputChan,
                                                   NewLUT -> OutputChan,
                                                   &NewLUT -> CLut16params);
+
+       return TRUE;
 }
 
 
@@ -830,17 +910,15 @@
 
 
        BaseType = ReadBase(Icc);
-
        switch (BaseType) {
 
 
-       case 0x9478ee00L:    // Monaco 2 profiler is BROKEN!
+       case ((icTagTypeSignature) 0x9478ee00):    // Monaco 2 profiler is BROKEN!
        case icSigCurveType:
 
-           Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+           if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
            AdjustEndianess32((LPBYTE) &Count);
 
-
            switch (Count) {
 
            case 0:   // Linear.
@@ -855,7 +933,7 @@
                     {
                      WORD SingleGammaFixed;
 
-                     Icc ->Read(&SingleGammaFixed, sizeof(WORD), 1, Icc);
+                     if (Icc ->Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
                      AdjustEndianess16((LPBYTE) &SingleGammaFixed);
                      return cmsBuildGamma(4096, Convert8Fixed8(SingleGammaFixed));
                      }
@@ -865,10 +943,9 @@
                      NewGamma = cmsAllocGamma(Count);
                      if (!NewGamma) return NULL;
 
-                     Icc ->Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc);
-
+                     if (Icc ->Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
+                         return NULL;
                      AdjustEndianessArray16(NewGamma -> GammaTable, Count);
-
                      return NewGamma;
                     }
               }
@@ -885,11 +962,11 @@
            icUInt16Number   Type;
            int i;
 
-           Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc);
-           Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc);
+           if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
+           if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
 
            AdjustEndianess16((LPBYTE) &Type);
-           if (Type > 5) {
+           if (Type > 4) {
 
                 cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
                 return NULL;
@@ -900,7 +977,7 @@
 
           for (i=0; i < n; i++) {
                 Num = 0;
-                Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
+                if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
                 Params[i] = Convert15Fixed16(Num);
           }
 
@@ -938,7 +1015,7 @@
        case 0x9478ee00L:    // Monaco 2 profiler is BROKEN!
        case icSigCurveType:
 
-           Icc -> Read(&Count, sizeof(icUInt32Number), 1, Icc);
+           if (Icc -> Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
            AdjustEndianess32((LPBYTE) &Count);
 
 
@@ -948,6 +1025,7 @@
 
                      NewGamma = cmsAllocGamma(2);
                      if (!NewGamma) return NULL;
+
                      NewGamma -> GammaTable[0] = 0;
                      NewGamma -> GammaTable[1] = 0xFFFF;
                      return NewGamma;
@@ -955,7 +1033,7 @@
            case 1:  {
                      WORD SingleGammaFixed;
 
-                     Icc -> Read(&SingleGammaFixed, sizeof(WORD), 1, Icc);
+                     if (Icc -> Read(&SingleGammaFixed, sizeof(WORD), 1, Icc) != 1) return NULL;
                      AdjustEndianess16((LPBYTE) &SingleGammaFixed);
                      return cmsBuildGamma(4096, 1./Convert8Fixed8(SingleGammaFixed));
                      }
@@ -965,7 +1043,8 @@
                      NewGamma = cmsAllocGamma(Count);
                      if (!NewGamma) return NULL;
 
-                     Icc -> Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc);
+                     if (Icc -> Read(NewGamma -> GammaTable, sizeof(WORD), Count, Icc) != Count)
+                         return NULL;
 
                      AdjustEndianessArray16(NewGamma -> GammaTable, Count);
 
@@ -992,11 +1071,11 @@
            int i;
 
 
-           Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc);
-           Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc);
+           if (Icc -> Read(&Type, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
+           if (Icc -> Read(&Reserved, sizeof(icUInt16Number), 1, Icc) != 1) return NULL;
 
            AdjustEndianess16((LPBYTE) &Type);
-           if (Type > 5) {
+           if (Type > 4) {
 
                 cmsSignalError(LCMS_ERRC_ABORTED, "Unknown parametric curve type '%d' found.", Type);
                 return NULL;
@@ -1006,7 +1085,7 @@
           n = ParamsByType[Type];
 
           for (i=0; i < n; i++) {
-                Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
+                if (Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc) != 1) return NULL;
                 Params[i] = Convert15Fixed16(Num);
           }
 
@@ -1028,7 +1107,7 @@
 // V4 stuff. Read matrix for LutAtoB and LutBtoA
 
 static
-BOOL ReadMatrixOffset(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, DWORD dwFlags)
+LCMSBOOL ReadMatrixOffset(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, DWORD dwFlags)
 {
 
     icS15Fixed16Number All[12];
@@ -1038,7 +1117,8 @@
 
     if (Icc -> Seek(Icc, Offset)) return FALSE;
 
-    Icc ->Read(All, sizeof(icS15Fixed16Number), 12, Icc);
+    if (Icc ->Read(All, sizeof(icS15Fixed16Number), 12, Icc) != 12)
+        return FALSE;
 
     for (i=0; i < 12;  i++)
               AdjustEndianess32((LPBYTE) &All[i]);
@@ -1067,17 +1147,26 @@
 //  V4 stuff. Read CLUT part for LutAtoB and LutBtoA
 
 static
-BOOL ReadCLUT(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT)
+LCMSBOOL ReadCLUT(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT)
 {
-
+    unsigned int j;
     icCLutStruct CLUT;
 
     if (Icc -> Seek(Icc, Offset)) return FALSE;
-    Icc ->Read(&CLUT, sizeof(icCLutStruct), 1, Icc);
-
-
-    cmsAlloc3DGrid(NewLUT, CLUT.gridPoints[0], NewLUT ->InputChan,
-                                               NewLUT ->OutputChan);
+    if (Icc ->Read(&CLUT, sizeof(icCLutStruct), 1, Icc) != 1) return FALSE;
+
+
+    for (j=1; j < NewLUT ->InputChan; j++) {
+        if (CLUT.gridPoints[0] != CLUT.gridPoints[j]) {
+            cmsSignalError(LCMS_ERRC_ABORTED, "CLUT with different granulatity is currently unsupported.");
+            return FALSE;
+        }
+
+
+    }
+
+    if (cmsAlloc3DGrid(NewLUT, CLUT.gridPoints[0], NewLUT ->InputChan,
+                                               NewLUT ->OutputChan) == NULL) return FALSE;
 
     // Precission can be 1 or 2 bytes
 
@@ -1087,7 +1176,7 @@
         unsigned int i;
 
         for (i=0; i < NewLUT->Tsize / sizeof(WORD); i++) {
-                Icc ->Read(&v, sizeof(BYTE), 1, Icc);
+                if (Icc ->Read(&v, sizeof(BYTE), 1, Icc) != 1) return FALSE;
                 NewLUT->T[i] = TO16_TAB(v);
         }
 
@@ -1095,10 +1184,10 @@
     else
         if (CLUT.prec == 2) {
 
-         Icc ->Read(NewLUT ->T, sizeof(WORD),
-                    NewLUT->Tsize / sizeof(WORD), Icc);
-
-        AdjustEndianessArray16(NewLUT ->T, NewLUT->Tsize / sizeof(WORD));
+         size_t n = NewLUT->Tsize / sizeof(WORD);
+
+         if (Icc ->Read(NewLUT ->T, sizeof(WORD), n, Icc) != n) return FALSE;
+         AdjustEndianessArray16(NewLUT ->T, NewLUT->Tsize / sizeof(WORD));
     }
     else {
         cmsSignalError(LCMS_ERRC_ABORTED, "Unknow precission of '%d'", CLUT.prec);
@@ -1110,6 +1199,22 @@
 
 
 static
+void ResampleCurves(LPGAMMATABLE Curves[], int nCurves)
+{
+    int i;
+    LPSAMPLEDCURVE sc;
+
+    for (i=0; i < nCurves; i++) {
+        sc = cmsConvertGammaToSampledCurve(Curves[i], 4096);
+        cmsFreeGamma(Curves[i]);
+        Curves[i] = cmsConvertSampledCurveToGamma(sc, 0xFFFF);
+        cmsFreeSampledCurve(sc);
+    }
+
+}
+
+
+static
 void SkipAlignment(LPLCMSICCPROFILE Icc)
 {
     BYTE Buffer[4];
@@ -1121,7 +1226,7 @@
 
 // Read a set of curves from specific offset
 static
-BOOL ReadSetOfCurves(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, int nLocation)
+LCMSBOOL ReadSetOfCurves(LPLCMSICCPROFILE Icc, size_t Offset, LPLUT NewLUT, int nLocation)
 {
     LPGAMMATABLE Curves[MAXCHANNELS];
     unsigned int i, nCurves;
@@ -1134,20 +1239,41 @@
     else
         nCurves = NewLUT ->OutputChan;
 
+    ZeroMemory(Curves, sizeof(Curves));
     for (i=0; i < nCurves; i++) {
 
         Curves[i] = ReadCurve(Icc);
+        if (Curves[i] == NULL) goto Error;
         SkipAlignment(Icc);
-
+    }
+
+    // March-26'08: some V4 profiles may have different sampling
+    // rates, in this case resample all curves to maximum
+
+    for (i=1; i < nCurves; i++) {
+        if (Curves[i]->nEntries != Curves[0]->nEntries) {
+            ResampleCurves(Curves, nCurves);
+        break;
+        }
     }
 
     NewLUT = cmsAllocLinearTable(NewLUT, Curves, nLocation);
+    if (NewLUT == NULL) goto Error;
 
     for (i=0; i < nCurves; i++)
         cmsFreeGamma(Curves[i]);
 
     return TRUE;
 
+Error:
+
+    for (i=0; i < nCurves; i++)
+        if (Curves[i])
+            cmsFreeGamma(Curves[i]);
+
+    return FALSE;
+
+
 }
 
 // V4 stuff. LutAtoB type
@@ -1160,22 +1286,28 @@
 //   L2 = B curves
 
 static
-BOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
+LCMSBOOL ReadLUT_A2B(LPLCMSICCPROFILE Icc, LPLUT NewLUT, size_t BaseOffset, icTagSignature sig)
 {
     icLutAtoB LUT16;
 
-       Icc ->Read(&LUT16, sizeof(icLutAtoB), 1, Icc);
+       if (Icc ->Read(&LUT16, sizeof(icLutAtoB), 1, Icc) != 1) return FALSE;
 
        NewLUT -> InputChan     = LUT16.inputChan;
        NewLUT -> OutputChan    = LUT16.outputChan;
 
+       // Validate the NewLUT here to avoid excessive number of channels
+       // (leading to stack-based buffer overflow in ReadSetOfCurves).
+       // Needs revalidation after table size is filled in.
+       if (!_cmsValidateLUT(NewLUT)) {
+           return FALSE;
+       }
+
        AdjustEndianess32((LPBYTE) &LUT16.offsetB);
        AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
        AdjustEndianess32((LPBYTE) &LUT16.offsetM);
        AdjustEndianess32((LPBYTE) &LUT16.offsetC);
        AdjustEndianess32((LPBYTE) &LUT16.offsetA);
 
-
        if (LUT16.offsetB != 0)
                 ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetB, NewLUT, 2);
 
@@ -1220,15 +1352,22 @@
 // V4 stuff. LutBtoA type
 
 static
-BOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, LPLUT NewLUT,  size_t BaseOffset, icTagSignature sig)
+LCMSBOOL ReadLUT_B2A(LPLCMSICCPROFILE Icc, LPLUT NewLUT,  size_t BaseOffset, icTagSignature sig)
 {
   icLutBtoA LUT16;
 
-       Icc ->Read(&LUT16, sizeof(icLutBtoA), 1, Icc);
+       if (Icc ->Read(&LUT16, sizeof(icLutBtoA), 1, Icc) != 1) return FALSE;
 
        NewLUT -> InputChan     = LUT16.inputChan;
        NewLUT -> OutputChan    = LUT16.outputChan;
 
+       // Validate the NewLUT here to avoid excessive number of channels
+       // (leading to stack-based buffer overflow in ReadSetOfCurves).
+       // Needs revalidation after table size is filled in.
+       if (!_cmsValidateLUT(NewLUT)) {
+           return FALSE;
+       }
+
        AdjustEndianess32((LPBYTE) &LUT16.offsetB);
        AdjustEndianess32((LPBYTE) &LUT16.offsetMat);
        AdjustEndianess32((LPBYTE) &LUT16.offsetM);
@@ -1242,7 +1381,6 @@
        if (LUT16.offsetMat != 0)
             ReadMatrixOffset(Icc, BaseOffset + LUT16.offsetMat, NewLUT, LUT_HASMATRIX3);
 
-
        if (LUT16.offsetM != 0)
                 ReadSetOfCurves(Icc, BaseOffset + LUT16.offsetM, NewLUT, 3);
 
@@ -1294,7 +1432,7 @@
 
 
     // If is in memory, the LUT is already there, so throw a copy
-    if (!Icc -> stream) {
+    if (Icc -> TagPtrs[n]) {
 
         return cmsDupLUT((LPLUT) Icc ->TagPtrs[n]);
     }
@@ -1308,8 +1446,8 @@
 
 
     NewLUT = cmsAllocLUT();
-    if (!NewLUT)
-    {
+    if (!NewLUT) {
+
        cmsSignalError(LCMS_ERRC_ABORTED, "cmsAllocLUT() failed");
        return NULL;
     }
@@ -1317,11 +1455,29 @@
 
     switch (BaseType) {
 
-    case icSigLut8Type:    ReadLUT8(Icc, NewLUT, sig); break;
-    case icSigLut16Type:   ReadLUT16(Icc, NewLUT);     break;
-
-    case icSiglutAtoBType: ReadLUT_A2B(Icc, NewLUT, offset, sig); break;
-    case icSiglutBtoAType: ReadLUT_B2A(Icc, NewLUT, offset, sig); break;
+    case icSigLut8Type:    if (!ReadLUT8(Icc, NewLUT, sig)) {
+                                cmsFreeLUT(NewLUT);
+                                return NULL;
+                           }
+                           break;
+
+    case icSigLut16Type:   if (!ReadLUT16(Icc, NewLUT)) {
+                                cmsFreeLUT(NewLUT);
+                                return NULL;
+                           }
+                           break;
+
+    case icSiglutAtoBType: if (!ReadLUT_A2B(Icc, NewLUT, offset, sig)) {
+                                cmsFreeLUT(NewLUT);
+                                return NULL;
+                           }
+                           break;
+
+    case icSiglutBtoAType: if (!ReadLUT_B2A(Icc, NewLUT, offset, sig)) {
+                                cmsFreeLUT(NewLUT);
+                                return NULL;
+                           }
+                           break;
 
     default:  cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature %lx found.", BaseType);
               cmsFreeLUT(NewLUT);
@@ -1335,16 +1491,23 @@
 
 // Sets the language & country preferences. Used only in ICC 4.0 profiles
 
-void LCMSEXPORT cmsSetLanguage(int LanguageCode, int CountryCode)
+void LCMSEXPORT cmsSetLanguage(const char LanguageCode[4], const char CountryCode[4])
 {
-    GlobalLanguageCode = LanguageCode;
-    GlobalCountryCode  = CountryCode;
+
+    int LanguageCodeInt = *(int *) LanguageCode;
+    int CountryCodeInt  = *(int *) CountryCode;
+
+    AdjustEndianess32((LPBYTE) &LanguageCodeInt);
+    AdjustEndianess32((LPBYTE) &CountryCodeInt);
+
+    GlobalLanguageCode = LanguageCodeInt;
+    GlobalCountryCode  = CountryCodeInt;
 }
 
 
 
 // Some tags (e.g, 'pseq') can have text tags embedded. This function
-// handles such special case.
+// handles such special case. Returns -1 on error, or the number of bytes left on success.
 
 static
 int ReadEmbeddedTextTag(LPLCMSICCPROFILE Icc, size_t size, char* Name, size_t size_max)
@@ -1353,7 +1516,6 @@
 
 
     BaseType = ReadBase(Icc);
-
     size -= sizeof(icTagBase);
 
     switch (BaseType) {
@@ -1365,50 +1527,54 @@
            icUInt16Number  ScriptCodeCode, Dummy;
            icUInt8Number   ScriptCodeCount;
 
-           Icc ->Read(&AsciiCount, sizeof(icUInt32Number), 1, Icc);
-
-                   if (size < sizeof(icUInt32Number)) return (int) size;
+           if (Icc ->Read(&AsciiCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+
+           if (size < sizeof(icUInt32Number)) return (int) size;
            size -= sizeof(icUInt32Number);
 
            AdjustEndianess32((LPBYTE) &AsciiCount);
            Icc ->Read(Name, 1,
                 (AsciiCount >= size_max) ? (size_max-1) : AsciiCount, Icc);
 
-                   if (size < AsciiCount) return (int) size;
+           if (size < AsciiCount) return (int) size;
            size -= AsciiCount;
 
            // Skip Unicode code
 
-           Icc ->Read(&UnicodeCode,  sizeof(icUInt32Number), 1, Icc);
-                   if (size < sizeof(icUInt32Number)) return (int) size;
+           if (Icc ->Read(&UnicodeCode,  sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+           if (size < sizeof(icUInt32Number)) return (int) size;
            size -= sizeof(icUInt32Number);
 
-           Icc ->Read(&UnicodeCount, sizeof(icUInt32Number), 1, Icc);
-                   if (size < sizeof(icUInt32Number)) return (int) size;
+           if (Icc ->Read(&UnicodeCount, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
+           if (size < sizeof(icUInt32Number)) return (int) size;
            size -= sizeof(icUInt32Number);
 
            AdjustEndianess32((LPBYTE) &UnicodeCount);
 
            if (UnicodeCount > size) return (int) size;
 
-           for (i=0; i < UnicodeCount; i++)
-                Icc ->Read(&Dummy, sizeof(icUInt16Number), 1, Icc);
-
-           size -= UnicodeCount * sizeof(icUInt16Number);
+           for (i=0; i < UnicodeCount; i++) {
+                size_t nread = Icc ->Read(&Dummy, sizeof(icUInt16Number), 1, Icc);
+                if (nread != 1) return (int) size;
+                size -= sizeof(icUInt16Number);
+           }
 
           // Skip ScriptCode code
 
-           Icc ->Read(&ScriptCodeCode,  sizeof(icUInt16Number), 1, Icc);
+           if (Icc ->Read(&ScriptCodeCode,  sizeof(icUInt16Number), 1, Icc) != 1) return -1;
            size -= sizeof(icUInt16Number);
-           Icc ->Read(&ScriptCodeCount, sizeof(icUInt8Number), 1, Icc);
+           if (Icc ->Read(&ScriptCodeCount, sizeof(icUInt8Number), 1, Icc) != 1) return -1;
            size -= sizeof(icUInt8Number);
 
+           // Should remain 67 bytes as filler
+
            if (size < 67) return (int) size;
 
-           for (i=0; i < 67; i++)
-                Icc ->Read(&Dummy, sizeof(icUInt8Number), 1, Icc);
-
-           size -= 67;
+           for (i=0; i < 67; i++) {
+                size_t nread = Icc ->Read(&Dummy, sizeof(icUInt8Number), 1, Icc);
+                if (nread != 1) return (int) size;
+                size --;
+               }
            }
            break;
 
@@ -1425,7 +1591,7 @@
              size = size_max - 1;
          }
 
-         Icc -> Read(Name, 1, size, Icc);
+         if (Icc -> Read(Name, 1, size, Icc) != size) return -1;
 
          for (i=0; i < Missing; i++)
              Icc -> Read(&Dummy, 1, 1, Icc);
@@ -1445,9 +1611,9 @@
         wchar_t*       wchar  = L"";
 
 
-            Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+            if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
             AdjustEndianess32((LPBYTE) &Count);
-            Icc ->Read(&RecLen, sizeof(icUInt32Number), 1, Icc);
+            if (Icc ->Read(&RecLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
             AdjustEndianess32((LPBYTE) &RecLen);
 
             if (RecLen != 12) {
@@ -1458,15 +1624,15 @@
 
             for (i=0; i < Count; i++) {
 
-                Icc ->Read(&Language, sizeof(icUInt16Number), 1, Icc);
+                if (Icc ->Read(&Language, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
                 AdjustEndianess16((LPBYTE) &Language);
-                Icc ->Read(&Country, sizeof(icUInt16Number), 1, Icc);
+                if (Icc ->Read(&Country, sizeof(icUInt16Number), 1, Icc) != 1) return -1;
                 AdjustEndianess16((LPBYTE) &Country);
 
-                Icc ->Read(&ThisLen, sizeof(icUInt32Number), 1, Icc);
+                if (Icc ->Read(&ThisLen, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
                 AdjustEndianess32((LPBYTE) &ThisLen);
 
-                Icc ->Read(&ThisOffset, sizeof(icUInt32Number), 1, Icc);
+                if (Icc ->Read(&ThisOffset, sizeof(icUInt32Number), 1, Icc) != 1) return -1;
                 AdjustEndianess32((LPBYTE) &ThisOffset);
 
                 if (Language == GlobalLanguageCode || Offset == 0) {
@@ -1492,14 +1658,18 @@
             for (i=0; i < Offset; i++) {
 
                     char Discard;
-
-                    Icc ->Read(&Discard, 1, 1, Icc);
+                    if (Icc ->Read(&Discard, 1, 1, Icc) != 1) return -1;
             }
 
-            wchar = (wchar_t*) malloc(Len+2);
+
+            // Bound len
+            if (Len < 0) Len = 0;
+            if (Len > 20*1024) Len = 20 * 1024;
+
+            wchar = (wchar_t*) _cmsMalloc(Len*sizeof(wchar_t)+2);
             if (!wchar) return -1;
 
-            Icc ->Read(wchar, 1, Len, Icc);
+            if (Icc ->Read(wchar, 1, Len, Icc) != Len) return -1;
             AdjustEndianessArray16((LPWORD) wchar, Len / 2);
 
             wchar[Len / 2] = L'\0';
@@ -1509,7 +1679,7 @@
                 Name[0] = 0;    // Error
             }
 
-            free((void*) wchar);
+            _cmsFree((void*) wchar);
             }
             break;
 
@@ -1522,8 +1692,7 @@
 }
 
 
-// Take an ASCII item. Takes at most LCMS_DESC_MAX
-
+// Take an ASCII item. Takes at most size_max bytes
 
 int LCMSEXPORT cmsReadICCTextEx(cmsHPROFILE hProfile, icTagSignature sig, char *Name, size_t size_max)
 {
@@ -1535,19 +1704,27 @@
     if (n < 0)
         return -1;
 
-    if (!Icc -> stream) {
-
-        CopyMemory(Name, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
+     size   = Icc -> TagSizes[n];
+
+    if (Icc -> TagPtrs[n]) {
+
+        if (size > size_max)
+            size = size_max;
+
+        CopyMemory(Name, Icc -> TagPtrs[n], size);
+
         return (int) Icc -> TagSizes[n];
     }
 
     offset = Icc -> TagOffsets[n];
-    size   = Icc -> TagSizes[n];
+
 
     if (Icc -> Seek(Icc, offset))
             return -1;
 
-    return ReadEmbeddedTextTag(Icc, size, Name, size_max);
+    if (ReadEmbeddedTextTag(Icc, size, Name, size_max) < 0) return -1;
+
+        return size;
 }
 
 // Keep compatibility with older versions
@@ -1561,7 +1738,7 @@
 // Take an XYZ item
 
 static
-int ReadICCXYZ(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIEXYZ Value, BOOL lIsFatal)
+int ReadICCXYZ(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIEXYZ Value, LCMSBOOL lIsFatal)
 {
     LPLCMSICCPROFILE    Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
     icTagTypeSignature  BaseType;
@@ -1573,7 +1750,7 @@
     if (n < 0)
             return -1;
 
-    if (!Icc -> stream) {
+    if (Icc -> TagPtrs[n]) {
 
          CopyMemory(Value, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
          return (int) Icc -> TagSizes[n];
@@ -1628,7 +1805,7 @@
     if (n < 0)
             return -1; // Not found
 
-    if (!Icc -> stream) {
+    if (Icc -> TagPtrs[n]) {
 
             CopyMemory(v, Icc -> TagPtrs[n], Icc -> TagSizes[n]);
             return (int) Icc -> TagSizes[n];
@@ -1677,7 +1854,7 @@
 
 // Primaries are to be in xyY notation
 
-BOOL LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile)
 {
        if (ReadICCXYZ(hProfile, icSigRedColorantTag, &Dest -> Red, TRUE) < 0) return FALSE;
        if (ReadICCXYZ(hProfile, icSigGreenColorantTag, &Dest -> Green, TRUE) < 0) return FALSE;
@@ -1687,7 +1864,7 @@
 }
 
 
-BOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile)
+LCMSBOOL cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile)
 {
        cmsCIEXYZTRIPLE Primaries;
 
@@ -1704,7 +1881,7 @@
 
 // Always return a suitable matrix
 
-BOOL cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile)
+LCMSBOOL cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile)
 {
 
     if (ReadICCXYZArray(hProfile, icSigChromaticAdaptationTag, r) < 0) {
@@ -1741,7 +1918,7 @@
        if (n < 0)
            return NULL;
 
-       if (!Icc -> stream) {
+       if (Icc -> TagPtrs[n]) {
 
             return cmsDupGamma((LPGAMMATABLE) Icc -> TagPtrs[n]);
        }
@@ -1769,7 +1946,7 @@
        if (n < 0)
             return NULL;
 
-       if (!Icc -> stream) {
+       if (Icc -> TagPtrs[n]) {
 
             return cmsReverseGamma(256, (LPGAMMATABLE) Icc -> TagPtrs[n]);
        }
@@ -1785,7 +1962,7 @@
 // Check Named color header
 
 static
-BOOL CheckHeader(LPcmsNAMEDCOLORLIST v, icNamedColor2* nc2)
+LCMSBOOL CheckHeader(LPcmsNAMEDCOLORLIST v, icNamedColor2* nc2)
 {
     if (v ->Prefix[0] == 0 && v ->Suffix[0] == 0 && v ->ColorantCount == 0) return TRUE;
 
@@ -1809,13 +1986,13 @@
        if (n < 0)
             return 0;
 
-       if (!Icc -> stream) {
+       if (Icc -> TagPtrs[n]) {
 
             // This replaces actual named color list.
             size_t size   = Icc -> TagSizes[n];
 
             if (v ->NamedColorList) cmsFreeNamedColorList(v ->NamedColorList);
-            v -> NamedColorList = (LPcmsNAMEDCOLORLIST) malloc(size);
+            v -> NamedColorList = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
             CopyMemory(v -> NamedColorList, Icc ->TagPtrs[n], size);
             return v ->NamedColorList->nColors;
        }
@@ -1844,7 +2021,7 @@
                 icNamedColor2 nc2;
                 unsigned int i, j;
 
-                Icc -> Read(&nc2, sizeof(icNamedColor2) - SIZEOF_UINT8_ALIGNED, 1, Icc);
+                if (Icc -> Read(&nc2, sizeof(icNamedColor2) - SIZEOF_UINT8_ALIGNED, 1, Icc) != 1) return 0;
                 AdjustEndianess32((LPBYTE) &nc2.vendorFlag);
                 AdjustEndianess32((LPBYTE) &nc2.count);
                 AdjustEndianess32((LPBYTE) &nc2.nDeviceCoords);
@@ -1854,6 +2031,11 @@
                      return 0;
                 }
 
+                if (nc2.nDeviceCoords > MAXCHANNELS) {
+                          cmsSignalError(LCMS_ERRC_WARNING, "Too many device coordinates.");
+                          return 0;
+                }
+
                 strncpy(v ->NamedColorList->Prefix, (const char*) nc2.prefix, 32);
                 strncpy(v ->NamedColorList->Suffix, (const char*) nc2.suffix, 32);
                 v ->NamedColorList->Prefix[32] = v->NamedColorList->Suffix[32] = 0;
@@ -1900,7 +2082,8 @@
 
 LPcmsNAMEDCOLORLIST LCMSEXPORT cmsReadColorantTable(cmsHPROFILE hProfile, icTagSignature sig)
 {
-    icInt32Number n, Count, i;
+    icInt32Number n;
+    icUInt32Number Count, i;
     size_t offset;
     icTagTypeSignature  BaseType;
     LPLCMSICCPROFILE   Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -1910,10 +2093,12 @@
     if (n < 0)
             return NULL; // Not found
 
-    if (!Icc -> stream) {
+    if (Icc -> TagPtrs[n]) {
 
             size_t size   = Icc -> TagSizes[n];
-            void* v = malloc(size);
+            void* v = _cmsMalloc(size);
+
+            if (v == NULL) return NULL;
             CopyMemory(v, Icc -> TagPtrs[n], size);
             return (LPcmsNAMEDCOLORLIST) v;
     }
@@ -1932,13 +2117,17 @@
     }
 
 
-    Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
+    if (Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc) != 1) return NULL;
     AdjustEndianess32((LPBYTE) &Count);
 
+    if (Count > MAXCHANNELS) {
+        cmsSignalError(LCMS_ERRC_ABORTED, "Too many colorants '%lx'", Count);
+        return NULL;
+    }
+
     List = cmsAllocNamedColorList(Count);
     for (i=0; i < Count; i++) {
 
-
         if (!Icc ->Read(List->List[i].Name, 1, 32 , Icc)) goto Error;
         if (!Icc ->Read(List->List[i].PCS, sizeof(icUInt16Number), 3, Icc)) goto Error;
         AdjustEndianessArray16(List->List[i].PCS, 3);
@@ -1965,7 +2154,7 @@
 
        if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
 
-            cmsReadICCText(hProfile, icSigDeviceMfgDescTag, Manufacturer);
+            cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
        }
 
     return Manufacturer;
@@ -1982,7 +2171,7 @@
 
        if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
 
-            cmsReadICCText(hProfile, icSigDeviceModelDescTag, Model);
+            cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
        }
 
     return Model;
@@ -1995,10 +2184,9 @@
     static char Copyright[LCMS_DESC_MAX] = "";
 
        Copyright[0] = 0;
-
        if (cmsIsTag(hProfile, icSigCopyrightTag)) {
 
-            cmsReadICCText(hProfile, icSigCopyrightTag, Copyright);
+            cmsReadICCTextEx(hProfile, icSigCopyrightTag, Copyright, LCMS_DESC_MAX);
        }
 
     return Copyright;
@@ -2009,7 +2197,7 @@
 
 const char*  LCMSEXPORT cmsTakeProductName(cmsHPROFILE hProfile)
 {
-    static char Name[2048];
+    static char Name[LCMS_DESC_MAX*2+4];
     char Manufacturer[LCMS_DESC_MAX], Model[LCMS_DESC_MAX];
 
     Name[0] = '\0';
@@ -2017,19 +2205,19 @@
 
     if (cmsIsTag(hProfile, icSigDeviceMfgDescTag)) {
 
-        cmsReadICCText(hProfile, icSigDeviceMfgDescTag, Manufacturer);
+        cmsReadICCTextEx(hProfile, icSigDeviceMfgDescTag, Manufacturer, LCMS_DESC_MAX);
     }
 
     if (cmsIsTag(hProfile, icSigDeviceModelDescTag)) {
 
-        cmsReadICCText(hProfile, icSigDeviceModelDescTag, Model);
+        cmsReadICCTextEx(hProfile, icSigDeviceModelDescTag, Model, LCMS_DESC_MAX);
     }
 
     if (!Manufacturer[0] && !Model[0]) {
 
         if (cmsIsTag(hProfile, icSigProfileDescriptionTag)) {
 
-            cmsReadICCText(hProfile, icSigProfileDescriptionTag, Name);
+            cmsReadICCTextEx(hProfile, icSigProfileDescriptionTag, Name, LCMS_DESC_MAX);
             return Name;
         }
         else return "{no name}";
@@ -2129,7 +2317,7 @@
 
 // Extract the target data as a big string. Does not signal if tag is not present.
 
-BOOL LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len)
+LCMSBOOL LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len)
 {
     LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
     int n;
@@ -2142,7 +2330,11 @@
 
 
     *len =  Icc -> TagSizes[n];
-    *Data = (char*) malloc(*len + 1);  // Plus zero marker
+
+    // Make sure that is reasonable (600K)
+    if (*len > 600*1024) *len = 600*1024;
+
+    *Data = (char*) _cmsMalloc(*len + 1);  // Plus zero marker
 
     if (!*Data) {
 
@@ -2162,7 +2354,7 @@
 
 
 
-BOOL LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile)
 {
     LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
     int n;
@@ -2170,8 +2362,8 @@
     n = _cmsSearchTag(Icc, icSigCalibrationDateTimeTag, FALSE);
     if (n < 0) return FALSE;
 
-    if (!Icc ->stream)
-    {
+    if (Icc ->TagPtrs[n]) {
+
         CopyMemory(Dest, Icc ->TagPtrs[n],  sizeof(struct tm));
     }
     else
@@ -2212,9 +2404,10 @@
     size   = Icc -> TagSizes[n];
     if (size < 12)  return NULL;
 
-    if (!Icc -> stream) {
-
-            OutSeq = (LPcmsSEQ) malloc(size);
+    if (Icc -> TagPtrs[n]) {
+
+            OutSeq = (LPcmsSEQ) _cmsMalloc(size);
+            if (OutSeq == NULL) return NULL;
             CopyMemory(OutSeq, Icc ->TagPtrs[n], size);
             return OutSeq;
     }
@@ -2231,8 +2424,13 @@
     Icc ->Read(&Count, sizeof(icUInt32Number), 1, Icc);
     AdjustEndianess32((LPBYTE) &Count);
 
+    if (Count > 1000) {
+         return NULL;
+    }
+
     size = sizeof(int) + Count * sizeof(cmsPSEQDESC);
-    OutSeq = (LPcmsSEQ) malloc(size);
+    OutSeq = (LPcmsSEQ) _cmsMalloc(size);
+    if (OutSeq == NULL) return NULL;
 
     OutSeq ->n = Count;
 
@@ -2268,181 +2466,11 @@
 void LCMSEXPORT cmsFreeProfileSequenceDescription(LPcmsSEQ pseq)
 {
     if (pseq)
-        free(pseq);
+        _cmsFree(pseq);
 }
 
 
 
-// Extended gamut -- an HP extension
-
-
-LPcmsGAMUTEX LCMSEXPORT cmsReadExtendedGamut(cmsHPROFILE hProfile, int index)
-{
-    LPLCMSICCPROFILE  Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-    size_t size, offset;
-    icUInt32Number off_samp, off_desc, off_vc;
-    int n;
-    icTagTypeSignature     BaseType;
-    icColorSpaceSignature  CoordSig;
-    icUInt16Number         Method, Usage;
-    icUInt32Number         GamutCount, SamplesCount;
-    LPcmsGAMUTEX gex;
-    size_t                 Offsets[256];
-    size_t                 i, Actual, Loc;
-    icS15Fixed16Number     Num;
-    icUInt16Number         Surround;
-
-
-    n = _cmsSearchTag(Icc, icSigHPGamutDescTag, FALSE);
-    if (n < 0) return NULL;
-
-    if (!Icc ->stream) return NULL;     // In memory is not supported
-
-    // Read the header
-
-    offset = Icc -> TagOffsets[n];
-
-    if (Icc -> Seek(Icc, offset))
-            return NULL;
-
-    // Here is the beginning of tag
-    Actual   = Icc ->Tell(Icc);
-
-
-    BaseType = ReadBase(Icc);
-
-    if (BaseType != icSigHPGamutDescType) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "Bad tag signature '%lx' found.", BaseType);
-            return NULL;
-    }
-
-
-    // Read the gamut descriptors count
-    Icc ->Read(&GamutCount, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &GamutCount);
-
-
-    if (GamutCount >= 256) {
-            cmsSignalError(LCMS_ERRC_ABORTED, "Too many gamut structures '%d'.", GamutCount);
-            return NULL;
-    }
-
-    // Read the directory
-
-    for (i=0; i < GamutCount; i++) {
-
-        Icc ->Read(&Offsets[i], sizeof(icUInt32Number), 1, Icc);
-        AdjustEndianess32((LPBYTE) &Offsets[i]);
-    }
-
-
-    // Is there such element?
-    if (index >= (int) GamutCount) return NULL;
-    Loc = Actual + Offsets[index];
-
-
-    // Go to specified index
-    if (Icc -> Seek(Icc, Loc))
-            return NULL;
-
-
-    // Read all members
-    Icc ->Read(&CoordSig, sizeof(icColorSpaceSignature), 1, Icc);
-    AdjustEndianess32((LPBYTE) &CoordSig);
-
-    Icc ->Read(&Method, sizeof(icUInt16Number), 1, Icc);
-    AdjustEndianess16((LPBYTE) &Method);
-
-    Icc ->Read(&Usage, sizeof(icUInt16Number), 1, Icc);
-    AdjustEndianess16((LPBYTE) &Usage);
-
-    Icc ->Read(&SamplesCount, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &SamplesCount);
-
-    Icc ->Read(&off_samp, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &off_samp);
-
-    Icc ->Read(&off_desc, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &off_desc);
-
-    Icc ->Read(&off_vc, sizeof(icUInt32Number), 1, Icc);
-    AdjustEndianess32((LPBYTE) &off_vc);
-
-
-    size = sizeof(cmsGAMUTEX) + (SamplesCount - 1) * sizeof(double);
-
-    gex = (LPcmsGAMUTEX) malloc(size);
-        if (gex == NULL) return NULL;
-
-
-    gex ->CoordSig = CoordSig;
-    gex ->Method   = Method;
-    gex ->Usage    = Usage;
-        gex ->Count    = SamplesCount;
-
-
-    // Read data
-    if (Icc -> Seek(Icc, Loc + off_samp))
-            return NULL;
-
-    for (i=0; i < SamplesCount; i++) {
-                Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-                gex ->Data[i] = Convert15Fixed16(Num);
-    }
-
-
-    // Read mluc
-    if (Icc -> Seek(Icc, Loc + off_desc)) {
-
-                        free(gex);
-            return NULL;
-        }
-
-    ReadEmbeddedTextTag(Icc, 256, gex ->Description, LCMS_DESC_MAX);
-
-
-    // Read viewing conditions
-    if (Icc -> Seek(Icc, Loc + off_vc)) {
-                        free(gex);
-            return NULL;
-        }
-
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.whitePoint.X = Convert15Fixed16(Num);
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.whitePoint.Y = Convert15Fixed16(Num);
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.whitePoint.Z = Convert15Fixed16(Num);
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.La = Convert15Fixed16(Num);
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.Yb = Convert15Fixed16(Num);
-
-    Icc -> Read(&Num, sizeof(icS15Fixed16Number), 1, Icc);
-    gex ->Vc.D_value = Convert15Fixed16(Num);
-
-    Icc -> Read(&Surround, sizeof(icUInt16Number), 1, Icc);
-    AdjustEndianess16((LPBYTE) &Surround);
-    gex ->Vc.surround = Surround;
-
-
-    // All OK
-    return gex;
-
-}
-
-
-
-void LCMSEXPORT cmsFreeExtendedGamut(LPcmsGAMUTEX gex)
-{
-    if (gex)
-        free(gex);
-}
 
 
 // Read a few tags that are hardly required
@@ -2564,6 +2592,7 @@
            NewIcc = (LPLCMSICCPROFILE) (LPSTR) hEmpty;
            NewIcc -> IsWrite = TRUE;
            strncpy(NewIcc ->PhysicalFile, lpFileName, MAX_PATH-1);
+           NewIcc ->PhysicalFile[MAX_PATH-1] = 0;
 
            // Save LUT as 8 bit
 
@@ -2609,14 +2638,14 @@
 
 
 
-BOOL LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
 {
        LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
-       BOOL rc = TRUE;
+       LCMSBOOL rc = TRUE;
+       icInt32Number i;
 
        if (!Icc) return FALSE;
 
-
        // Was open in write mode?
        if (Icc ->IsWrite) {
 
@@ -2624,21 +2653,15 @@
            rc = _cmsSaveProfile(hProfile, Icc ->PhysicalFile);
        }
 
-
-       if (Icc -> stream == NULL) {     // Was a memory (i.e. not serialized) profile?
-
-
-              icInt32Number i;          // Yes, free tags
-
-              for (i=0; i < Icc -> TagCount; i++) {
+       for (i=0; i < Icc -> TagCount; i++) {
 
                   if (Icc -> TagPtrs[i])
                             free(Icc -> TagPtrs[i]);
-              }
-
        }
-       else   Icc -> Close(Icc);    // No, close the stream
-
+
+       if (Icc -> stream != NULL) {     // Was a memory (i.e. not serialized) profile?
+                 Icc -> Close(Icc);     // No, close the stream
+       }
 
        free(Icc);   // Free placeholder memory
 
@@ -2652,11 +2675,11 @@
 
 
 static
-BOOL SaveWordsTable(int nEntries, LPWORD Tab, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveWordsTable(int nEntries, LPWORD Tab, LPLCMSICCPROFILE Icc)
 {
    size_t nTabSize = sizeof(WORD) * nEntries;
-   LPWORD PtrW = (LPWORD) malloc(nTabSize);
-   BOOL rc;
+   LPWORD PtrW = (LPWORD) _cmsMalloc(nTabSize);
+   LCMSBOOL rc;
 
    if (!PtrW) return FALSE;
    CopyMemory(PtrW, Tab, nTabSize);
@@ -2672,7 +2695,7 @@
 // Saves profile header
 
 static
-BOOL SaveHeader(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveHeader(LPLCMSICCPROFILE Icc)
 {
   icHeader Header;
   time_t now = time(NULL);
@@ -2727,7 +2750,7 @@
 // Setup base marker
 
 static
-BOOL SetupBase(icTagTypeSignature sig, LPLCMSICCPROFILE Icc)
+LCMSBOOL SetupBase(icTagTypeSignature sig, LPLCMSICCPROFILE Icc)
 {
     icTagBase  Base;
 
@@ -2737,10 +2760,10 @@
 }
 
 
-// Store an XYZ tag
+// Store a XYZ tag
 
 static
-BOOL SaveXYZNumber(LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveXYZNumber(LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
 {
 
     icXYZNumber XYZ;
@@ -2756,72 +2779,97 @@
 }
 
 
+// Store a XYZ array.
+
+static
+LCMSBOOL SaveXYZArray(int n, LPcmsCIEXYZ Value, LPLCMSICCPROFILE Icc)
+{
+    int i;
+    icXYZNumber XYZ;
+
+    if (!SetupBase(icSigS15Fixed16ArrayType, Icc)) return FALSE;
+
+    for (i=0; i < n; i++) {
+
+        XYZ.X = TransportValue32(DOUBLE_TO_FIXED(Value -> X));
+        XYZ.Y = TransportValue32(DOUBLE_TO_FIXED(Value -> Y));
+        XYZ.Z = TransportValue32(DOUBLE_TO_FIXED(Value -> Z));
+
+        if (!Icc -> Write(Icc, sizeof(icXYZNumber), &XYZ)) return FALSE;
+
+        Value++;
+    }
+
+    return TRUE;
+}
+
+
 
 // Save a gamma structure as a table
 
 static
-BOOL SaveGammaTable(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveGammaTable(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
 {
-        icInt32Number Count;
-
-                if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
-                Count = TransportValue32(Gamma->nEntries);
-
-                if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
-                return SaveWordsTable(Gamma->nEntries, Gamma ->GammaTable, Icc);
+    icInt32Number Count;
+
+        if (!SetupBase(icSigCurveType, Icc)) return FALSE;
+
+        Count = TransportValue32(Gamma->nEntries);
+
+        if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
+
+        return SaveWordsTable(Gamma->nEntries, Gamma ->GammaTable, Icc);
 }
 
 
 // Save a gamma structure as a one-value
 
 static
-BOOL SaveGammaOneValue(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveGammaOneValue(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
 {
-        icInt32Number Count;
-        Fixed32 GammaFixed32;
-        WORD    GammaFixed8;
-
-                if (!SetupBase(icSigCurveType, Icc)) return FALSE;
-
-                Count = TransportValue32(1);
-                if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
-
-                GammaFixed32 = DOUBLE_TO_FIXED(Gamma ->Seed.Params[0]);
-                GammaFixed8  = (WORD) ((GammaFixed32 >> 8) & 0xFFFF);
-                GammaFixed8  = TransportValue16(GammaFixed8);
-
-                return Icc ->Write(Icc, sizeof(icInt16Number), &GammaFixed8);
+    icInt32Number Count;
+    Fixed32 GammaFixed32;
+    WORD    GammaFixed8;
+
+        if (!SetupBase(icSigCurveType, Icc)) return FALSE;
+
+        Count = TransportValue32(1);
+        if (!Icc ->Write(Icc, sizeof(icInt32Number), &Count)) return FALSE;
+
+        GammaFixed32 = DOUBLE_TO_FIXED(Gamma ->Seed.Params[0]);
+        GammaFixed8  = (WORD) ((GammaFixed32 >> 8) & 0xFFFF);
+        GammaFixed8  = TransportValue16(GammaFixed8);
+
+        return Icc ->Write(Icc, sizeof(icInt16Number), &GammaFixed8);
 }
 
 // Save a gamma structure as a parametric gamma
 
 static
-BOOL SaveGammaParametric(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveGammaParametric(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
 {
-        icUInt16Number Type, Reserved;
-        int i, nParams;
-        int ParamsByType[] = { 1, 3, 4, 5, 7 };
-
-        if (!SetupBase(icSigParametricCurveType, Icc)) return FALSE;
-
-        nParams = ParamsByType[Gamma -> Seed.Type];
-
-        Type      = (icUInt16Number) TransportValue16((WORD) Gamma -> Seed. Type);
-        Reserved  = (icUInt16Number) TransportValue16((WORD) 0);
-
-        Icc -> Write(Icc, sizeof(icInt16Number),  &Type);
-        Icc -> Write(Icc, sizeof(icUInt16Number), &Reserved);
-
-        for (i=0; i < nParams; i++) {
-
-                icInt32Number val = TransportValue32(DOUBLE_TO_FIXED(Gamma -> Seed.Params[i]));
-                Icc ->Write(Icc, sizeof(icInt32Number), &val);
-        }
-
-
-        return TRUE;
+    icUInt16Number Type, Reserved;
+    int i, nParams;
+    int ParamsByType[] = { 1, 3, 4, 5, 7 };
+
+    if (!SetupBase(icSigParametricCurveType, Icc)) return FALSE;
+
+    nParams = ParamsByType[Gamma -> Seed.Type];
+
+    Type      = (icUInt16Number) TransportValue16((WORD) Gamma -> Seed. Type);
+    Reserved  = (icUInt16Number) TransportValue16((WORD) 0);
+
+    Icc -> Write(Icc, sizeof(icInt16Number),  &Type);
+    Icc -> Write(Icc, sizeof(icUInt16Number), &Reserved);
+
+    for (i=0; i < nParams; i++) {
+
+        icInt32Number val = TransportValue32(DOUBLE_TO_FIXED(Gamma -> Seed.Params[i]));
+        Icc ->Write(Icc, sizeof(icInt32Number), &val);
+    }
+
+
+    return TRUE;
 
 }
 
@@ -2829,29 +2877,29 @@
 // Save a gamma table
 
 static
-BOOL SaveGamma(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveGamma(LPGAMMATABLE Gamma, LPLCMSICCPROFILE Icc)
 {
-                // Is the gamma curve type supported by ICC format?
-
-                if (Gamma -> Seed.Type < 0 || Gamma -> Seed.Type > 5 ||
-
-                        // has been modified by user?
-
-                        _cmsCrc32OfGammaTable(Gamma) != Gamma -> Seed.Crc32) {
-
-                        return SaveGammaTable(Gamma, Icc);
-                }
-
-                if (Gamma -> Seed.Type == 1) return SaveGammaOneValue(Gamma, Icc);
-
-                // Only v4 profiles are allowed to hold parametric curves
-
-                if (cmsGetProfileICCversion((cmsHPROFILE) Icc) >= 0x4000000)
-                                return SaveGammaParametric(Gamma, Icc);
-
-                // Defaults to save as table
-
-                return SaveGammaTable(Gamma, Icc);
+        // Is the gamma curve type supported by ICC format?
+
+        if (Gamma -> Seed.Type < 0 || Gamma -> Seed.Type > 5 ||
+
+            // has been modified by user?
+
+            _cmsCrc32OfGammaTable(Gamma) != Gamma -> Seed.Crc32) {
+
+            return SaveGammaTable(Gamma, Icc);
+        }
+
+        if (Gamma -> Seed.Type == 1) return SaveGammaOneValue(Gamma, Icc);
+
+        // Only v4 profiles are allowed to hold parametric curves
+
+        if (cmsGetProfileICCversion((cmsHPROFILE) Icc) >= 0x4000000)
+                return SaveGammaParametric(Gamma, Icc);
+
+        // Defaults to save as table
+
+        return SaveGammaTable(Gamma, Icc);
 
 }
 
@@ -2861,7 +2909,7 @@
 // Save an DESC Tag
 
 static
-BOOL SaveDescription(const char *Text, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveDescription(const char *Text, LPLCMSICCPROFILE Icc)
 {
 
     icUInt32Number len, Count, TotalSize, AlignedSize;
@@ -2893,6 +2941,11 @@
     if (!Icc ->Write(Icc, len, (LPVOID)Text)) return FALSE;
     AlignedSize -= len;
 
+    if (AlignedSize < 0)
+            AlignedSize = 0;
+    if (AlignedSize > 255)
+            AlignedSize = 255;
+
     ZeroMemory(Filler, AlignedSize);
     if (!Icc ->Write(Icc, AlignedSize, Filler)) return FALSE;
 
@@ -2902,7 +2955,7 @@
 // Save an ASCII Tag
 
 static
-BOOL SaveText(const char *Text, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveText(const char *Text, LPLCMSICCPROFILE Icc)
 {
     size_t len = strlen(Text) + 1;
 
@@ -2915,7 +2968,7 @@
 // Save one of these new chromaticity values
 
 static
-BOOL SaveOneChromaticity(double x, double y, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveOneChromaticity(double x, double y, LPLCMSICCPROFILE Icc)
 {
        Fixed32 xf, yf;
 
@@ -2932,7 +2985,7 @@
 // New tag added in Addendum II of old spec.
 
 static
-BOOL SaveChromaticities(LPcmsCIExyYTRIPLE chrm, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveChromaticities(LPcmsCIExyYTRIPLE chrm, LPLCMSICCPROFILE Icc)
 {
        WORD nChans, Table;
 
@@ -2952,7 +3005,7 @@
 
 
 static
-BOOL SaveSequenceDescriptionTag(LPcmsSEQ seq, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveSequenceDescriptionTag(LPcmsSEQ seq, LPLCMSICCPROFILE Icc)
 {
     icUInt32Number nSeqs;
     icDescStruct   DescStruct;
@@ -2989,7 +3042,7 @@
 // Saves a timestamp tag
 
 static
-BOOL SaveDateTimeNumber(const struct tm *DateTime, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveDateTimeNumber(const struct tm *DateTime, LPLCMSICCPROFILE Icc)
 {
     icDateTimeNumber Dest;
 
@@ -3003,14 +3056,14 @@
 
 // Saves a named color list into a named color profile
 static
-BOOL SaveNamedColorList(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveNamedColorList(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
 {
 
     icUInt32Number      vendorFlag;     // Bottom 16 bits for IC use
     icUInt32Number      count;          // Count of named colors
     icUInt32Number      nDeviceCoords;  // Num of device coordinates
-    icInt8Number        prefix[32];     // Prefix for each color name
-    icInt8Number        suffix[32];     // Suffix for each color name
+    char                prefix[32];     // Prefix for each color name
+    char                suffix[32];     // Suffix for each color name
     int i;
 
     if (!SetupBase(icSigNamedColor2Type, Icc)) return FALSE;
@@ -3019,8 +3072,10 @@
     count         = TransportValue32(NamedColorList ->nColors);
     nDeviceCoords = TransportValue32(NamedColorList ->ColorantCount);
 
-    strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
-    strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
+    strncpy(prefix, (const char*) NamedColorList->Prefix, 31);
+    strncpy(suffix, (const char*) NamedColorList->Suffix, 31);
+
+    suffix[31] = prefix[31] = 0;
 
     if (!Icc ->Write(Icc, sizeof(icUInt32Number), &vendorFlag)) return FALSE;
     if (!Icc ->Write(Icc, sizeof(icUInt32Number), &count)) return FALSE;
@@ -3030,15 +3085,17 @@
 
     for (i=0; i < NamedColorList ->nColors; i++) {
 
-          icUInt16Number PCS[3];
-          icUInt16Number Colorant[MAXCHANNELS];
-          icInt8Number root[32];
+          icUInt16Number  PCS[3];
+          icUInt16Number  Colorant[MAXCHANNELS];
+          char            root[32];
           LPcmsNAMEDCOLOR Color;
           int j;
 
                     Color = NamedColorList ->List + i;
 
-                    strncpy((char*) root, Color ->Name, 32);
+                    strncpy(root, Color ->Name, 32);
+                    Color ->Name[32] = 0;
+
                     if (!Icc ->Write(Icc, 32 , root)) return FALSE;
 
                     for (j=0; j < 3; j++)
@@ -3062,7 +3119,7 @@
 // Saves a colorant table. It is using the named color structure for simplicity sake
 
 static
-BOOL SaveColorantTable(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveColorantTable(LPcmsNAMEDCOLORLIST NamedColorList, LPLCMSICCPROFILE Icc)
 {
      icUInt32Number count;  // Count of named colors
      int i;
@@ -3076,13 +3133,15 @@
      for (i=0; i < NamedColorList ->nColors; i++) {
 
       icUInt16Number PCS[3];
-      icInt8Number root[32];
+      icInt8Number root[33];
       LPcmsNAMEDCOLOR Color;
       int j;
 
             Color = NamedColorList ->List + i;
 
             strncpy((char*) root, Color ->Name, 32);
+            root[32] = 0;
+
             if (!Icc ->Write(Icc, 32 , root)) return FALSE;
 
             for (j=0; j < 3; j++)
@@ -3099,7 +3158,7 @@
 // Does serialization of LUT16 and writes it.
 
 static
-BOOL SaveLUT(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveLUT(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
 {
        icLut16 LUT16;
        unsigned int i;
@@ -3189,7 +3248,7 @@
 // Does serialization of LUT8 and writes it
 
 static
-BOOL SaveLUT8(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveLUT8(const LUT* NewLUT, LPLCMSICCPROFILE Icc)
 {
        icLut8 LUT8;
        unsigned int i, j;
@@ -3323,7 +3382,7 @@
 // Saves Tag directory
 
 static
-BOOL SaveTagDirectory(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveTagDirectory(LPLCMSICCPROFILE Icc)
 {
        icInt32Number i;
        icTag Tag;
@@ -3356,7 +3415,7 @@
 // Dump tag contents
 
 static
-BOOL SaveTags(LPLCMSICCPROFILE Icc)
+LCMSBOOL SaveTags(LPLCMSICCPROFILE Icc, LPLCMSICCPROFILE FileOrig)
 {
 
     LPBYTE Data;
@@ -3384,8 +3443,31 @@
 
        Icc -> TagOffsets[i] = Begin = Icc ->UsedSpace;
        Data = (LPBYTE) Icc -> TagPtrs[i];
-       if (!Data)
+       if (!Data) {
+
+           // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
+           // In this case a blind copy of the block data is performed
+
+           if (Icc -> TagOffsets[i]) {
+
+                    size_t TagSize   = FileOrig -> TagSizes[i];
+                    size_t TagOffset = FileOrig -> TagOffsets[i];
+                    void* Mem;
+
+                    if (FileOrig ->Seek(FileOrig, TagOffset)) return FALSE;
+
+                    Mem = _cmsMalloc(TagSize);
+
+                    if (FileOrig ->Read(Mem, TagSize, 1, FileOrig) != 1) return FALSE;
+                    if (!Icc ->Write(Icc, TagSize, Mem)) return FALSE;
+
+                    Icc -> TagSizes[i] = (Icc ->UsedSpace - Begin);
+                    free(Mem);
+           }
+
               continue;
+       }
+
 
        switch (Icc -> TagNames[i]) {
 
@@ -3464,6 +3546,10 @@
              break;
 
 
+       case icSigChromaticAdaptationTag:
+              if (!SaveXYZArray(3, (LPcmsCIEXYZ) Data, Icc)) return FALSE;
+              break;
+
        default:
               return FALSE;
        }
@@ -3480,9 +3566,9 @@
 
 // Add tags to profile structure
 
-BOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* Tag)
+LCMSBOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* Tag)
 {
-   BOOL rc;
+   LCMSBOOL rc;
 
    switch (sig) {
 
@@ -3543,6 +3629,11 @@
               rc = _cmsAddColorantTableTag(hProfile, sig, (LPcmsNAMEDCOLORLIST) Tag);
               break;
 
+
+       case icSigChromaticAdaptationTag:
+              rc = _cmsAddChromaticAdaptationTag(hProfile, sig, (const cmsCIEXYZ*) Tag);
+              break;
+
        default:
             cmsSignalError(LCMS_ERRC_ABORTED, "cmsAddTag: Tag '%x' is unsupported", sig);
             return FALSE;
@@ -3568,11 +3659,11 @@
 
 // Low-level save to disk. It closes the profile on exit
 
-BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName)
+LCMSBOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName)
 {
        LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
        LCMSICCPROFILE Keep;
-       BOOL rc;
+       LCMSBOOL rc;
 
         CopyMemory(&Keep, Icc, sizeof(LCMSICCPROFILE));
        _cmsSetSaveToDisk(Icc, NULL);
@@ -3581,7 +3672,7 @@
 
        if (!SaveHeader(Icc)) return FALSE;
        if (!SaveTagDirectory(Icc)) return FALSE;
-       if (!SaveTags(Icc)) return FALSE;
+       if (!SaveTags(Icc, &Keep)) return FALSE;
 
 
        _cmsSetSaveToDisk(Icc, FileName);
@@ -3591,7 +3682,7 @@
 
        if (!SaveHeader(Icc)) goto CleanUp;
        if (!SaveTagDirectory(Icc)) goto CleanUp;
-       if (!SaveTags(Icc)) goto CleanUp;
+       if (!SaveTags(Icc, &Keep)) goto CleanUp;
 
        rc = (Icc ->Close(Icc) == 0);
        CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
@@ -3608,7 +3699,7 @@
 
 
 // Low-level save from open stream
-BOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
+LCMSBOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
                                                            size_t* BytesNeeded)
 {
     LPLCMSICCPROFILE Icc = (LPLCMSICCPROFILE) (LPSTR) hProfile;
@@ -3623,20 +3714,20 @@
 
     if (!SaveHeader(Icc)) return FALSE;
     if (!SaveTagDirectory(Icc)) return FALSE;
-    if (!SaveTags(Icc)) return FALSE;
+    if (!SaveTags(Icc, &Keep)) return FALSE;
 
     if (!MemPtr) {
 
         // update BytesSaved so caller knows how many bytes are needed for MemPtr
         *BytesNeeded = Icc ->UsedSpace;
-                CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
+        CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
         return TRUE;
     }
 
     if (*BytesNeeded < Icc ->UsedSpace) {
 
         // need at least UsedSpace in MemPtr to continue
-                CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
+        CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
         return FALSE;
     }
 
@@ -3646,7 +3737,7 @@
     // Pass #2 does save to file into supplied stream
     if (!SaveHeader(Icc)) goto CleanUp;
     if (!SaveTagDirectory(Icc)) goto CleanUp;
-    if (!SaveTags(Icc)) goto CleanUp;
+    if (!SaveTags(Icc, &Keep)) goto CleanUp;
 
     // update BytesSaved so caller knows how many bytes put into stream
     *BytesNeeded = Icc ->UsedSpace;
@@ -3661,3 +3752,4 @@
     CopyMemory(Icc, &Keep, sizeof(LCMSICCPROFILE));
     return FALSE;
 }
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -118,7 +118,7 @@
 {
        LPLUT NewLUT;
 
-       NewLUT = (LPLUT) malloc(sizeof(LUT));
+       NewLUT = (LPLUT) _cmsMalloc(sizeof(LUT));
        if (NewLUT)
               ZeroMemory(NewLUT, sizeof(LUT));
 
@@ -171,9 +171,10 @@
 static
 LPVOID DupBlockTab(LPVOID Org, size_t size)
 {
-    LPVOID mem = malloc(size);
+    LPVOID mem = _cmsMalloc(size);
+    if (mem != NULL)
+        CopyMemory(mem, Org, size);
 
-    CopyMemory(mem, Org, size);
     return mem;
 }
 
@@ -211,6 +212,37 @@
 }
 
 
+LCMSBOOL _cmsValidateLUT(LPLUT NewLUT)
+{
+    unsigned int calc = 1;
+    unsigned int oldCalc;
+    unsigned int power = NewLUT -> InputChan;
+
+    if (NewLUT -> cLutPoints > 100) return FALSE;
+    if (NewLUT -> InputChan > MAXCHANNELS)  return FALSE;
+    if (NewLUT -> OutputChan > MAXCHANNELS) return FALSE;
+
+    if (NewLUT -> cLutPoints == 0) return TRUE;
+
+    for (; power > 0; power--) {
+
+      oldCalc = calc;
+      calc *= NewLUT -> cLutPoints;
+
+      if (calc / NewLUT -> cLutPoints != oldCalc) {
+        return FALSE;
+      }
+    }
+
+    oldCalc = calc;
+    calc *= NewLUT -> OutputChan;
+    if (NewLUT -> OutputChan && calc / NewLUT -> OutputChan != oldCalc) {
+      return FALSE;
+    }
+
+    return TRUE;
+}
+
 LPLUT LCMSEXPORT cmsAlloc3DGrid(LPLUT NewLUT, int clutPoints, int inputChan, int outputChan)
 {
     DWORD nTabSize;
@@ -220,12 +252,17 @@
        NewLUT -> InputChan     = inputChan;
        NewLUT -> OutputChan    = outputChan;
 
+       if (!_cmsValidateLUT(NewLUT)) {
+         return NULL;
+       }
 
-       nTabSize = (NewLUT -> OutputChan * UIpow(NewLUT->cLutPoints,
-                                                NewLUT->InputChan)
-                                                * sizeof(WORD));
+       nTabSize = NewLUT -> OutputChan * UIpow(NewLUT->cLutPoints,
+                                               NewLUT->InputChan);
 
-       NewLUT -> T = (LPWORD) malloc(nTabSize);
+       NewLUT -> T = (LPWORD) _cmsCalloc(sizeof(WORD), nTabSize);
+       nTabSize *= sizeof(WORD);
+       if (NewLUT -> T == NULL) return NULL;
+
        ZeroMemory(NewLUT -> T, nTabSize);
        NewLUT ->Tsize = nTabSize;
 
@@ -254,10 +291,12 @@
 
                for (i=0; i < NewLUT -> InputChan; i++) {
 
-                     PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> InputEntries);
+                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> InputEntries);
+                     if (PtrW == NULL) return NULL;
+
                      NewLUT -> L1[i] = PtrW;
                      CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> InputEntries);
-                                         CopyMemory(&NewLUT -> LCurvesSeed[0][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+                     CopyMemory(&NewLUT -> LCurvesSeed[0][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
                }
 
 
@@ -268,10 +307,12 @@
                NewLUT -> OutputEntries = Tables[0] -> nEntries;
                for (i=0; i < NewLUT -> OutputChan; i++) {
 
-                     PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> OutputEntries);
+                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> OutputEntries);
+                     if (PtrW == NULL) return NULL;
+
                      NewLUT -> L2[i] = PtrW;
                      CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> OutputEntries);
-                                         CopyMemory(&NewLUT -> LCurvesSeed[1][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+                     CopyMemory(&NewLUT -> LCurvesSeed[1][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
                }
                break;
 
@@ -285,10 +326,12 @@
 
                for (i=0; i < NewLUT -> InputChan; i++) {
 
-                     PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> L3Entries);
+                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> L3Entries);
+                     if (PtrW == NULL) return NULL;
+
                      NewLUT -> L3[i] = PtrW;
                      CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> L3Entries);
-                                         CopyMemory(&NewLUT -> LCurvesSeed[2][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+                     CopyMemory(&NewLUT -> LCurvesSeed[2][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
                }
                break;
 
@@ -298,10 +341,12 @@
                NewLUT -> L4Entries = Tables[0] -> nEntries;
                for (i=0; i < NewLUT -> OutputChan; i++) {
 
-                     PtrW = (LPWORD) malloc(sizeof(WORD) * NewLUT -> L4Entries);
+                     PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewLUT -> L4Entries);
+                     if (PtrW == NULL) return NULL;
+
                      NewLUT -> L4[i] = PtrW;
                      CopyMemory(PtrW, Tables[i]->GammaTable, sizeof(WORD) * NewLUT -> L4Entries);
-                                         CopyMemory(&NewLUT -> LCurvesSeed[3][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
+                     CopyMemory(&NewLUT -> LCurvesSeed[3][i], &Tables[i] -> Seed, sizeof(LCMSGAMMAPARAMS));
                }
                break;
 
@@ -580,7 +625,7 @@
    LPL16PARAMS p = &Lut ->CLut16params;
 
 
-   p8 = (LPL8PARAMS) malloc(sizeof(L8PARAMS));
+   p8 = (LPL8PARAMS) _cmsMalloc(sizeof(L8PARAMS));
    if (p8 == NULL) return NULL;
 
   // values comes * 257, so we can safely take first byte (x << 8 + x)
@@ -593,8 +638,8 @@
            if (Lut ->wFlags & LUT_HASTL1) {
 
               for (j=0; j < 3; j++)
-                     StageABC[i] = cmsLinearInterpLUT16(StageABC[i],
-                                                        Lut -> L1[i],
+                     StageABC[j] = cmsLinearInterpLUT16(StageABC[j],
+                                                        Lut -> L1[j],
                                                        &Lut -> In16params);
               Lut ->wFlags &= ~LUT_HASTL1;
            }
@@ -697,7 +742,7 @@
     wIn[3] = FixedK;
 
     cmsEvalLUT(Lut, wIn, wOut);
-        cmsLabEncoded2Float(Out, wOut);
+    cmsLabEncoded2Float(Out, wOut);
 }
 
 // Builds a Jacobian CMY->Lab
@@ -722,9 +767,9 @@
 
         EvalLUTdoubleKLab(Lut, &ColorantD, K, &LabD);
 
-                Jacobian->v[0].n[j] = ((LabD.L - Lab.L) / JACOBIAN_EPSILON);
-                Jacobian->v[1].n[j] = ((LabD.a - Lab.a) / JACOBIAN_EPSILON);
-                Jacobian->v[2].n[j] = ((LabD.b - Lab.b) / JACOBIAN_EPSILON);
+        Jacobian->v[0].n[j] = ((LabD.L - Lab.L) / JACOBIAN_EPSILON);
+        Jacobian->v[1].n[j] = ((LabD.a - Lab.a) / JACOBIAN_EPSILON);
+        Jacobian->v[2].n[j] = ((LabD.b - Lab.b) / JACOBIAN_EPSILON);
 
     }
 }
@@ -797,18 +842,18 @@
         // Obtain slope
         ComputeJacobianLab(Lut, &Jacobian, &x, FixedK);
 
-                // Solve system
-                tmp2.n[0] = fx.L - Goal.L;
-                tmp2.n[1] = fx.a - Goal.a;
-                tmp2.n[2] = fx.b - Goal.b;
+        // Solve system
+        tmp2.n[0] = fx.L - Goal.L;
+        tmp2.n[1] = fx.a - Goal.a;
+        tmp2.n[2] = fx.b - Goal.b;
 
-                if (!MAT3solve(&tmp, &Jacobian, &tmp2))
-                        break;
+        if (!MAT3solve(&tmp, &Jacobian, &tmp2))
+            break;
 
         // Move our guess
-                x.n[0] -= tmp.n[0];
-            x.n[1] -= tmp.n[1];
-                x.n[2] -= tmp.n[2];
+        x.n[0] -= tmp.n[0];
+        x.n[1] -= tmp.n[1];
+        x.n[2] -= tmp.n[2];
 
         // Some clipping....
         VEC3saturate(&x);
@@ -822,3 +867,6 @@
     return LastError;
 
 }
+
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmatsh.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmatsh.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -62,6 +62,7 @@
 // data yet in fixed point, so no additional process is required.
 // Then, we obtain data on 15.16, so we need to shift >> by 1 to
 // obtain 1.15 PCS format.
+
 // On OUTPUT profiles, things are inverse, we must first expand 1 bit
 // by shifting left, and then convert result between 0 and 1.000 to
 // RGB, so FromFixedDomain() must be called before pass values to
@@ -71,6 +72,7 @@
 // input is encoded from 0 to 0xffff, we must first use the shaper and
 // then the matrix, an additional FromFixedDomain() must be used to
 // accomodate output values.
+
 // For a sake of simplicity, I will handle this three behaviours
 // with different routines, so the flags MATSHAPER_INPUT and MATSHAPER_OUTPUT
 // can be conbined to signal smelted matrix-shapers
@@ -89,7 +91,7 @@
        {
         LPWORD PtrW;
 
-        PtrW = (LPWORD) malloc(sizeof(WORD) * p16 -> nSamples);
+        PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * p16 -> nSamples);
 
         if (PtrW == NULL) return -1;  // Signal error
 
@@ -119,7 +121,7 @@
        LPMATSHAPER NewMatShaper;
        int rc;
 
-       NewMatShaper = (LPMATSHAPER) malloc(sizeof(MATSHAPER));
+       NewMatShaper = (LPMATSHAPER) _cmsMalloc(sizeof(MATSHAPER));
        if (NewMatShaper)
               ZeroMemory(NewMatShaper, sizeof(MATSHAPER));
 
@@ -171,7 +173,13 @@
        LPMATSHAPER NewMatShaper;
        int i, AllLinear;
 
-       NewMatShaper = (LPMATSHAPER) malloc(sizeof(MATSHAPER));
+           if (Matrix == NULL) return NULL;
+           for (i=0; i < 3; i++) {
+
+                   if (Tables[i] == NULL) return NULL;
+           }
+
+       NewMatShaper = (LPMATSHAPER) _cmsMalloc(sizeof(MATSHAPER));
        if (NewMatShaper)
               ZeroMemory(NewMatShaper, sizeof(MATSHAPER));
 
@@ -187,17 +195,16 @@
                      NewMatShaper -> dwFlags |= MATSHAPER_HASMATRIX;
 
        // Now, on the table characteristics
-
        cmsCalcL16Params(Tables[0] -> nEntries, &NewMatShaper -> p16);
 
        // Copy tables
 
        AllLinear = 0;
-       for (i=0; i < 3; i++)
-       {
+       for (i=0; i < 3; i++) {
+
         LPWORD PtrW;
 
-        PtrW = (LPWORD) malloc(sizeof(WORD) * NewMatShaper -> p16.nSamples);
+        PtrW = (LPWORD) _cmsMalloc(sizeof(WORD) * NewMatShaper -> p16.nSamples);
 
         if (PtrW == NULL) {
               cmsFreeMatShaper(NewMatShaper);
@@ -235,11 +242,11 @@
 
        for (i=0; i < 3; i++)
        {
-              if (MatShaper -> L[i]) free(MatShaper ->L[i]);
-              if (MatShaper -> L2[i]) free(MatShaper ->L2[i]);
+              if (MatShaper -> L[i]) _cmsFree(MatShaper ->L[i]);
+              if (MatShaper -> L2[i]) _cmsFree(MatShaper ->L2[i]);
        }
 
-       free(MatShaper);
+       _cmsFree(MatShaper);
 }
 
 
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -71,16 +71,16 @@
 double cdecl VEC3distance(LPVEC3 a, LPVEC3 b);
 
 
-void   cdecl MAT3identity(LPMAT3 a);
-void   cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
-int    cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
-BOOL   cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
-double cdecl MAT3det(LPMAT3 m);
-void   cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
-void   cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
-void   cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
-void   cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
-void   cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
+void      cdecl MAT3identity(LPMAT3 a);
+void      cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
+int       cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
+LCMSBOOL  cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
+double    cdecl MAT3det(LPMAT3 m);
+void      cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
+void      cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
+void      cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
+void      cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
+void      cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
 
 // --------------------- Implementation ----------------------------
 
@@ -345,13 +345,13 @@
 // Check id two vectors are the same, allowing tolerance
 
 static
-BOOL RangeCheck(double l, double h, double v)
+LCMSBOOL RangeCheck(double l, double h, double v)
 {
        return (v >= l && v <= h);
 }
 
 
-BOOL VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance)
+LCMSBOOL VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance)
 {
        int i;
        double c;
@@ -367,7 +367,7 @@
        return TRUE;
 }
 
-BOOL VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance)
+LCMSBOOL VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance)
 {
        int i;
        double c;
@@ -462,7 +462,7 @@
 
 // Check if matrix is Identity. Allow a tolerance as %
 
-BOOL MAT3isIdentity(LPWMAT3 a, double Tolerance)
+LCMSBOOL MAT3isIdentity(LPWMAT3 a, double Tolerance)
 {
        int i;
        MAT3 Idd;
@@ -545,16 +545,16 @@
 
 // Solve a system in the form Ax = b
 
-BOOL MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b)
+LCMSBOOL MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b)
 {
-        MAT3 m, a_1;
+    MAT3 m, a_1;
 
-        CopyMemory(&m, a, sizeof(MAT3));
+    CopyMemory(&m, a, sizeof(MAT3));
 
-        if (!MAT3inverse(&m, &a_1)) return FALSE;  // Singular matrix
+    if (!MAT3inverse(&m, &a_1)) return FALSE;  // Singular matrix
 
-        MAT3eval(x, &a_1, b);
-        return TRUE;
+    MAT3eval(x, &a_1, b);
+    return TRUE;
 }
 
 
@@ -839,3 +839,7 @@
        VEC3scaleAndCut(&r -> v[1], &v -> v[1], d);
        VEC3scaleAndCut(&r -> v[2], &v -> v[2], d);
 }
+
+
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -74,7 +74,7 @@
                 NewElements *= 2;
 
         size = sizeof(cmsNAMEDCOLORLIST) + (sizeof(cmsNAMEDCOLOR) * NewElements);
-        TheNewList = (LPcmsNAMEDCOLORLIST) malloc(size);
+        TheNewList = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
 
 
         if (TheNewList == NULL) {
@@ -86,7 +86,7 @@
               CopyMemory(TheNewList, v, sizeof(cmsNAMEDCOLORLIST) + (v ->nColors - 1) * sizeof(cmsNAMEDCOLOR));
               TheNewList -> Allocated = NewElements;
 
-              free(v);
+              _cmsFree(v);
               return TheNewList;
         }
     }
@@ -99,7 +99,7 @@
 {
     size_t size = sizeof(cmsNAMEDCOLORLIST) + (n - 1) * sizeof(cmsNAMEDCOLOR);
 
-    LPcmsNAMEDCOLORLIST v = (LPcmsNAMEDCOLORLIST) malloc(size);
+    LPcmsNAMEDCOLORLIST v = (LPcmsNAMEDCOLORLIST) _cmsMalloc(size);
 
 
     if (v == NULL) {
@@ -124,10 +124,10 @@
         return;
     }
 
-    free(v);
+    _cmsFree(v);
 }
 
-BOOL cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS])
+LCMSBOOL cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS])
 {
     _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
     LPcmsNAMEDCOLORLIST List;
@@ -146,6 +146,7 @@
         List ->List[List ->nColors].PCS[i] = PCS[i];
 
     strncpy(List ->List[List ->nColors].Name, Name, MAX_PATH-1);
+    List ->List[List ->nColors].Name[MAX_PATH-1] = 0;
 
     List ->nColors++;
     return TRUE;
@@ -164,18 +165,17 @@
 }
 
 
-BOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix)
+LCMSBOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix)
 {
     _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) xform;
 
-
      if (v ->NamedColorList == NULL) return FALSE;
 
      if (nColor < 0 || nColor >= cmsNamedColorCount(xform)) return FALSE;
 
-     if (Name) strncpy(Name, v ->NamedColorList->List[nColor].Name, 31);
-     if (Prefix) strncpy(Prefix, v ->NamedColorList->Prefix, 31);
-     if (Suffix) strncpy(Suffix, v ->NamedColorList->Suffix, 31);
+         if (Name)   { strncpy(Name, v ->NamedColorList->List[nColor].Name, 31); Name[31] = 0; }
+         if (Prefix) { strncpy(Prefix, v ->NamedColorList->Prefix, 31); Prefix[31] = 0; }
+         if (Suffix) { strncpy(Suffix, v ->NamedColorList->Suffix, 31); Suffix[31] = 0; }
 
      return TRUE;
 }
@@ -196,3 +196,5 @@
 
         return -1;
 }
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c	Fri Apr 10 13:05:12 2009 -0700
@@ -28,7 +28,7 @@
 // file:
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -639,9 +639,81 @@
 
 
 
+static
+LPBYTE UnrollDouble1Chan(register _LPcmsTRANSFORM info, register WORD wIn[], register LPBYTE accum)
+{
+    double* Inks = (double*) accum;
+    double v;
+
+
+    v = floor(Inks[0] * 65535.0 + 0.5);
+
+    if (v > 65535.0) v = 65535.0;
+    if (v < 0) v = 0;
+
+
+    wIn[0] = wIn[1] = wIn[2] = (WORD) v;
+
+    return accum + sizeof(double);
+}
+
+
 // ----------------------------------------------------------- Packing routines
 
 
+// Generic N-bytes plus dither 16-to-8 conversion. Currently is just a quick hack
+
+static int err[MAXCHANNELS];
+
+static
+LPBYTE PackNBytesDither(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
+{
+       int nChan  = T_CHANNELS(info -> OutputFormat);
+       register int i;
+       unsigned int n, pe, pf;
+
+       for (i=0; i < nChan;  i++) {
+
+              n = wOut[i] + err[i]; // Value
+
+              pe = (n / 257);       // Whole part
+              pf = (n % 257);       // Fractional part
+
+              err[i] = pf;          // Store it for next pixel
+
+              *output++ = (BYTE) pe;
+       }
+
+       return output + T_EXTRA(info ->OutputFormat);
+}
+
+
+
+static
+LPBYTE PackNBytesSwapDither(register _LPcmsTRANSFORM info, register WORD wOut[], register LPBYTE output)
+{
+       int nChan  = T_CHANNELS(info -> OutputFormat);
+       register int i;
+       unsigned int n, pe, pf;
+
+       for (i=nChan-1; i >= 0;  --i) {
+
+              n = wOut[i] + err[i];     // Value
+
+              pe = (n / 257);           // Whole part
+              pf = (n % 257);           // Fractional part
+
+              err[i] = pf;              // Store it for next pixel
+
+              *output++ = (BYTE) pe;
+       }
+
+
+       return output + T_EXTRA(info ->OutputFormat);
+}
+
+
+
 // Generic chunky for byte
 
 static
@@ -1486,7 +1558,10 @@
            case PT_HSV:
            case PT_HLS:
            case PT_Yxy:
-                    FromInput = UnrollDouble;
+                    if (T_CHANNELS(dwInput) == 1)
+                        FromInput = UnrollDouble1Chan;
+                    else
+                        FromInput = UnrollDouble;
                     break;
 
             // Inks (%) 0.0 .. 100.0
@@ -1749,6 +1824,9 @@
                      switch (T_CHANNELS(dwOutput))
                      {
                      case 1:
+                            if (T_DITHER(dwOutput))
+                                    ToOutput = PackNBytesDither;
+                            else
                             ToOutput = Pack1Byte;
                             if (T_EXTRA(dwOutput) == 1) {
                                 if (T_SWAPFIRST(dwOutput))
@@ -1766,8 +1844,12 @@
                                  else
                                      if (T_COLORSPACE(dwOutput) == PT_Lab)
                                         ToOutput = Pack3BytesLab;
+                                     else {
+                                         if (T_DITHER(dwOutput))
+                                                 ToOutput = PackNBytesDither;
                                      else
                                         ToOutput = Pack3Bytes;
+                                     }
                              break;
 
                          case 1:    // TODO: ALab8 should be handled here
@@ -1793,13 +1875,23 @@
 
                      case 4: if (T_EXTRA(dwOutput) == 0) {
 
+
                                 if (T_DOSWAP(dwOutput)) {
 
-                                     if (T_SWAPFIRST(dwOutput))
+
+                                     if (T_SWAPFIRST(dwOutput)) {
                                          ToOutput = Pack4BytesSwapSwapFirst;
-                                     else
+                                     }
+                                     else {
+
+                                           if (T_DITHER(dwOutput)) {
+                                                  ToOutput = PackNBytesSwapDither;
+                                           }
+                                           else {
                                          ToOutput = Pack4BytesSwap;
                                  }
+                                     }
+                                 }
                                  else {
                                      if (T_SWAPFIRST(dwOutput))
                                          ToOutput = Pack4BytesSwapFirst;
@@ -1807,11 +1899,15 @@
 
                                          if (T_FLAVOR(dwOutput))
                                              ToOutput = Pack4BytesReverse;
+                                         else {
+                                             if (T_DITHER(dwOutput))
+                                                 ToOutput = PackNBytesDither;
                                          else
                                              ToOutput = Pack4Bytes;
                                      }
                                  }
                              }
+                             }
                             else {
                                     if (!T_DOSWAP(dwOutput) && !T_SWAPFIRST(dwOutput))
                                              ToOutput = PackNBytes;
@@ -1833,7 +1929,7 @@
                             }
                             break;
 
-                                         case 2:
+                     case 2:
                      case 5:
                      case 7:
                      case 8:
@@ -1849,8 +1945,13 @@
                             {
                                    if (T_DOSWAP(dwOutput))
                                           ToOutput = PackNBytesSwap;
+                                   else {
+
+                                       if (T_DITHER(dwOutput))
+                                                 ToOutput = PackNBytesDither;
                                    else
                                           ToOutput = PackNBytes;
+                                   }
                             }
                             break;
 
@@ -1984,7 +2085,7 @@
                             break;
 
 
-                                         case 2:
+                     case 2:
                      case 5:
                      case 7:
                      case 8:
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -624,3 +624,7 @@
     fXYZ -> Z = XYZ2float(XYZ[2]);
 
 }
+
+
+
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -144,6 +144,8 @@
             /Table [ p p p [<...>]]
             /RangeABC [ 0 1 0 1 0 1]
             /DecodeABC[ <postlinearization> ]
+            /RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]
+               % -128/500 1+127/500 0 1  -127/200 1+128/200
             /MatrixABC [ 1 1 1 1 0 0 0 0 -1]
             /WhitePoint [D50]
             /BlackPoint [BP]
@@ -347,7 +349,8 @@
 static
 LPMEMSTREAM CreateMemStream(LPBYTE Buffer, DWORD dwMax, int MaxCols)
 {
-    LPMEMSTREAM m = (LPMEMSTREAM) malloc(sizeof(MEMSTREAM));
+    LPMEMSTREAM m = (LPMEMSTREAM) _cmsMalloc(sizeof(MEMSTREAM));
+    if (m == NULL) return NULL;
 
     ZeroMemory(m, sizeof(MEMSTREAM));
 
@@ -376,9 +379,9 @@
 static
 BYTE L2Byte(WORD w)
 {
-        int ww = w + 0x0080;
+    int ww = w + 0x0080;
 
-        if (ww > 0xFFFF) return 0xFF;
+    if (ww > 0xFFFF) return 0xFF;
 
     return (BYTE) ((WORD) (ww >> 8) & 0xFF);
 }
@@ -387,7 +390,6 @@
 static
 void WriteRawByte(LPMEMSTREAM m, BYTE b)
 {
-
     if (m -> dwUsed + 1 > m -> dwMax) {
         m -> HasError = 1;
     }
@@ -422,7 +424,7 @@
 
 }
 
-// Does write a formatted string
+// Does write a formatted string. Guaranteed to be 2048 bytes at most.
 static
 void Writef(LPMEMSTREAM m, const char *frm, ...)
 {
@@ -432,7 +434,7 @@
 
         va_start(args, frm);
 
-        vsprintf((char*) Buffer, frm, args);
+        vsnprintf((char*) Buffer, 2048, frm, args);
 
         for (pt = Buffer; *pt; pt++)  {
 
@@ -562,7 +564,7 @@
     Writef(m, "{255 mul 128 sub 200 div } bind\n");
     Writef(m, "]\n");
     Writef(m, "/MatrixABC [ 1 1 1 1 0 0 0 0 -1]\n");
-        Writef(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
+    Writef(m, "/RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]\n");
     Writef(m, "/DecodeLMN [\n");
     Writef(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.964200 mul} bind\n");
     Writef(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse } bind\n");
@@ -584,7 +586,11 @@
     if (nEntries <= 0) return;  // Empty table
 
     // Suppress whole if identity
-    if (cmsIsLinear(Table, nEntries)) return;
+    if (cmsIsLinear(Table, nEntries)) {
+            Writef(m, "{} ");
+            return;
+    }
+
 
     // Check if is really an exponential. If so, emit "exp"
      gamma = cmsEstimateGammaEx(Table, nEntries, 0.001);
@@ -646,7 +652,7 @@
 // Compare gamma table
 
 static
-BOOL GammaTableEquals(LPWORD g1, LPWORD g2, int nEntries)
+LCMSBOOL GammaTableEquals(LPWORD g1, LPWORD g2, int nEntries)
 {
     return memcmp(g1, g2, nEntries* sizeof(WORD)) == 0;
 }
@@ -676,7 +682,7 @@
 // Check whatever a profile has CLUT tables (only on input)
 
 static
-BOOL IsLUTbased(cmsHPROFILE hProfile, int Intent)
+LCMSBOOL IsLUTbased(cmsHPROFILE hProfile, int Intent)
 {
     icTagSignature Tag;
 
@@ -718,10 +724,10 @@
 
     if (sc -> FixWhite) {
 
-        if (In[0] == 0xFFFF) {  // Only in L* = 100
+        if (In[0] == 0xFFFF) {  // Only in L* = 100, ab = [-8..8]
 
-            if ((In[1] >= 0x8000 && In[1] <= 0x87FF) ||
-                (In[2] >= 0x8000 && In[2] <= 0x87FF)) {
+            if ((In[1] >= 0x7800 && In[1] <= 0x8800) &&
+                (In[2] >= 0x7800 && In[2] <= 0x8800)) {
 
                 WORD* Black;
                 WORD* White;
@@ -829,8 +835,8 @@
     sc.PreMaj = PreMaj;
     sc.PostMaj= PostMaj;
 
-    sc.PreMin = PreMin;
-    sc.PostMin= PostMin;
+    sc.PreMin   = PreMin;
+    sc.PostMin  = PostMin;
     sc.lIsInput = lIsInput;
     sc.FixWhite = FixWhite;
     sc.ColorSpace = ColorSpace;
@@ -1231,7 +1237,7 @@
 
         if (!WriteNamedColorCSA(mem, hProfile, Intent)) {
 
-                    free((void*) mem);
+                    _cmsFree((void*) mem);
                     return 0;
         }
     }
@@ -1246,7 +1252,7 @@
         ColorSpace != icSigLabData) {
 
             cmsSignalError(LCMS_ERRC_ABORTED, "Invalid output color space");
-            free((void*) mem);
+            _cmsFree((void*) mem);
             return 0;
     }
 
@@ -1256,7 +1262,7 @@
         // Yes, so handle as LUT-based
         if (!WriteInputLUT(mem, hProfile, Intent)) {
 
-                    free((void*) mem);
+                    _cmsFree((void*) mem);
                     return 0;
         }
     }
@@ -1266,7 +1272,7 @@
 
         if (!WriteInputMatrixShaper(mem, hProfile)) {
 
-                    free((void*) mem);  // Something went wrong
+                    _cmsFree((void*) mem);  // Something went wrong
                     return 0;
         }
     }
@@ -1277,7 +1283,7 @@
     dwBytesUsed = mem ->dwUsed;
 
     // Get rid of memory stream
-    free((void*) mem);
+    _cmsFree((void*) mem);
 
     // Finally, return used byte count
     return dwBytesUsed;
@@ -1350,27 +1356,40 @@
 
 
 static
-void EmitPQRStage(LPMEMSTREAM m, int DoBPC, int lIsAbsolute)
+void EmitPQRStage(LPMEMSTREAM m, cmsHPROFILE hProfile, int DoBPC, int lIsAbsolute)
 {
 
 
+        if (lIsAbsolute) {
+
+            // For absolute colorimetric intent, encode back to relative
+            // and generate a relative LUT
+
+            // Relative encoding is obtained across XYZpcs*(D50/WhitePoint)
+
+            cmsCIEXYZ White;
+
+            cmsTakeMediaWhitePoint(&White, hProfile);
+
+            Writef(m,"/MatrixPQR [1 0 0 0 1 0 0 0 1 ]\n");
+            Writef(m,"/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
+
+            Writef(m, "%% Absolute colorimetric -- encode to relative to maximize LUT usage\n"
+                      "/TransformPQR [\n"
+                      "{0.9642 mul %g div exch pop exch pop exch pop exch pop} bind\n"
+                      "{1.0000 mul %g div exch pop exch pop exch pop exch pop} bind\n"
+                      "{0.8249 mul %g div exch pop exch pop exch pop exch pop} bind\n]\n",
+                      White.X, White.Y, White.Z);
+            return;
+        }
+
+
         Writef(m,"%% Bradford Cone Space\n"
                  "/MatrixPQR [0.8951 -0.7502 0.0389 0.2664 1.7135 -0.0685 -0.1614 0.0367 1.0296 ] \n");
 
         Writef(m, "/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
 
 
-        if (lIsAbsolute) {
-
-            // For absolute colorimetric intent, do nothing
-
-            Writef(m, "%% Absolute colorimetric -- no transformation\n"
-                      "/TransformPQR [\n"
-                      "{exch pop exch pop exch pop exch pop} bind dup dup]\n");
-            return;
-        }
-
-
         // No BPC
 
         if (!DoBPC) {
@@ -1414,6 +1433,7 @@
 static
 void EmitXYZ2Lab(LPMEMSTREAM m)
 {
+    Writef(m, "/RangeLMN [ -0.635 2.0 0 2 -0.635 2.0 ]\n");
     Writef(m, "/EncodeLMN [\n");
     Writef(m, "{ 0.964200  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
     Writef(m, "{ 1.000000  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
@@ -1423,17 +1443,10 @@
     Writef(m, "/EncodeABC [\n");
 
 
-
     Writef(m, "{ 116 mul  16 sub 100 div  } bind\n");
-    Writef(m, "{ 500 mul 128 add 255 div  } bind\n");
-    Writef(m, "{ 200 mul 128 add 255 div  } bind\n");
-
+    Writef(m, "{ 500 mul 128 add 256 div  } bind\n");
+    Writef(m, "{ 200 mul 128 add 256 div  } bind\n");
 
-    /*
-    Writef(m, "{ 116 mul  16 sub 256 mul 25700 div  } bind\n");
-    Writef(m, "{ 500 mul 128 add 256 mul 65535 div  } bind\n");
-    Writef(m, "{ 200 mul 128 add 256 mul 65535 div  } bind\n");
-    */
 
     Writef(m, "]\n");
 
@@ -1458,20 +1471,27 @@
     LPLUT DeviceLink;
     cmsHPROFILE Profiles[3];
     cmsCIEXYZ BlackPointAdaptedToD50;
-    BOOL lFreeDeviceLink = FALSE;
-    BOOL lDoBPC = (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
+    LCMSBOOL lFreeDeviceLink = FALSE;
+    LCMSBOOL lDoBPC = (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
+    LCMSBOOL lFixWhite = !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP);
+    int RelativeEncodingIntent;
 
 
-    // Trick our v4 profile as it were v2. This prevents the ajusting done
-    // in perceptual & saturation. We only neew v4 encoding!
 
-    hLab         = cmsCreateLab4Profile(NULL);
-    cmsSetProfileICCversion(hLab, 0);
+    hLab = cmsCreateLabProfile(NULL);
 
     ColorSpace  =  cmsGetColorSpace(hProfile);
     nChannels   = _cmsChannelsOf(ColorSpace);
     OutputFormat = CHANNELS_SH(nChannels) | BYTES_SH(2);
 
+    // For absolute colorimetric, the LUT is encoded as relative
+    // in order to preserve precission.
+
+    RelativeEncodingIntent = Intent;
+    if (RelativeEncodingIntent == INTENT_ABSOLUTE_COLORIMETRIC)
+        RelativeEncodingIntent = INTENT_RELATIVE_COLORIMETRIC;
+
+
     // Is a devicelink profile?
     if (cmsGetDeviceClass(hProfile) == icSigLinkClass) {
 
@@ -1479,13 +1499,14 @@
 
         if (ColorSpace == icSigLabData) {
 
-              // adjust input to Lab to out v4
+              // adjust input to Lab to our v4
 
             Profiles[0] = hLab;
             Profiles[1] = hProfile;
 
             xform = cmsCreateMultiprofileTransform(Profiles, 2, TYPE_Lab_DBL,
-                                                        OutputFormat, Intent, cmsFLAGS_NOPRELINEARIZATION);
+                                                        OutputFormat, RelativeEncodingIntent,
+                                                        dwFlags|cmsFLAGS_NOWHITEONWHITEFIXUP|cmsFLAGS_NOPRELINEARIZATION);
 
         }
         else {
@@ -1499,7 +1520,7 @@
 
         // This is a normal profile
         xform = cmsCreateTransform(hLab, TYPE_Lab_DBL, hProfile,
-                            OutputFormat, Intent, cmsFLAGS_NOPRELINEARIZATION);
+                            OutputFormat, RelativeEncodingIntent, dwFlags|cmsFLAGS_NOWHITEONWHITEFIXUP|cmsFLAGS_NOPRELINEARIZATION);
     }
 
     if (xform == NULL) {
@@ -1515,7 +1536,7 @@
 
     if (!DeviceLink) {
 
-        DeviceLink = _cmsPrecalculateDeviceLink(xform, 0);
+        DeviceLink = _cmsPrecalculateDeviceLink(xform, cmsFLAGS_NOPRELINEARIZATION);
         lFreeDeviceLink = TRUE;
     }
 
@@ -1527,7 +1548,7 @@
 
     // Emit headers, etc.
     EmitWhiteBlackD50(m, &BlackPointAdaptedToD50);
-    EmitPQRStage(m, lDoBPC, Intent == INTENT_ABSOLUTE_COLORIMETRIC);
+    EmitPQRStage(m, hProfile, lDoBPC, Intent == INTENT_ABSOLUTE_COLORIMETRIC);
     EmitXYZ2Lab(m);
 
     if (DeviceLink ->wFlags & LUT_HASTL1) {
@@ -1544,10 +1565,13 @@
     // zero. This would sacrifice a bit of highlights, but failure to do so would cause
     // scum dot. Ouch.
 
+    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
+            lFixWhite = FALSE;
+
     Writef(m, "/RenderTable ");
 
     WriteCLUT(m, DeviceLink, 8, "<", ">\n", "", "", FALSE,
-                (Intent != INTENT_ABSOLUTE_COLORIMETRIC), ColorSpace);
+                lFixWhite, ColorSpace);
 
     Writef(m, " %d {} bind ", nChannels);
 
@@ -1582,6 +1606,9 @@
     int j;
 
     Colorant[0] = 0;
+    if (nColorant > MAXCHANNELS)
+        nColorant = MAXCHANNELS;
+
     for (j=0; j < nColorant; j++) {
 
                 sprintf(Buff, "%.3f", Out[j] / 65535.0);
@@ -1677,7 +1704,7 @@
 
         if (!WriteNamedColorCRD(mem, hProfile, Intent, dwFlags)) {
 
-                    free((void*) mem);
+                    _cmsFree((void*) mem);
                     return 0;
         }
     }
@@ -1687,7 +1714,7 @@
 
 
     if (!WriteOutputLUT(mem, hProfile, Intent, dwFlags)) {
-        free((void*) mem);
+        _cmsFree((void*) mem);
         return 0;
     }
     }
@@ -1702,7 +1729,7 @@
     dwBytesUsed = mem ->dwUsed;
 
     // Get rid of memory stream
-    free((void*) mem);
+    _cmsFree((void*) mem);
 
     // Finally, return used byte count
     return dwBytesUsed;
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -120,7 +120,7 @@
 // This routine does a sweep on whole input space, and calls its callback
 // function on knots. returns TRUE if all ok, FALSE otherwise.
 
-BOOL LCMSEXPORT cmsSample3DGrid(LPLUT Lut, _cmsSAMPLER Sampler, LPVOID Cargo, DWORD dwFlags)
+LCMSBOOL LCMSEXPORT cmsSample3DGrid(LPLUT Lut, _cmsSAMPLER Sampler, LPVOID Cargo, DWORD dwFlags)
 {
    int i, t, nTotalPoints, Colorant, index;
    WORD In[MAXCHANNELS], Out[MAXCHANNELS];
@@ -145,12 +145,16 @@
                                                 &Lut -> In16params);
         }
 
+        for (t=0; t < (int) Lut -> OutputChan; t++)
+                     Out[t] = Lut->T[index + t];
 
-        // if (dwFlags & SAMPLER_INSPECT) {
+        if (dwFlags & SAMPLER_HASTL2) {
 
              for (t=0; t < (int) Lut -> OutputChan; t++)
-                        Out[t] = Lut->T[index + t];
-        // }
+                     Out[t] = cmsLinearInterpLUT16(Out[t],
+                                                   Lut -> L2[t],
+                                                   &Lut -> Out16params);
+        }
 
 
         if (!Sampler(In, Out, Cargo))
@@ -255,9 +259,11 @@
        LPLUT Grid;
        int nGridPoints;
        DWORD dwFormatIn, dwFormatOut;
+       DWORD SaveFormatIn, SaveFormatOut;
        int ChannelsIn, ChannelsOut;
        LPLUT SaveGamutLUT;
 
+
        // Remove any gamut checking
        SaveGamutLUT = p ->Gamut;
        p ->Gamut = NULL;
@@ -276,8 +282,13 @@
        dwFormatIn   = (CHANNELS_SH(ChannelsIn)|BYTES_SH(2));
        dwFormatOut  = (CHANNELS_SH(ChannelsOut)|BYTES_SH(2));
 
-       p -> FromInput = _cmsIdentifyInputFormat(p, dwFormatIn);
-       p -> ToOutput  = _cmsIdentifyOutputFormat(p, dwFormatOut);
+       SaveFormatIn  = p ->InputFormat;
+       SaveFormatOut = p ->OutputFormat;
+
+       p -> InputFormat  = dwFormatIn;
+       p -> OutputFormat = dwFormatOut;
+       p -> FromInput    = _cmsIdentifyInputFormat(p, dwFormatIn);
+       p -> ToOutput     = _cmsIdentifyOutputFormat(p, dwFormatOut);
 
        // Fix gamut & gamma possible mismatches.
 
@@ -289,7 +300,6 @@
            _cmsComputePrelinearizationTablesFromXFORM(hOne, 1, Grid);
        }
 
-
        // Attention to this typecast! we can take the luxury to
        // do this since cmsHTRANSFORM is only an alias to a pointer
        // to the transform struct.
@@ -297,11 +307,13 @@
        if (!cmsSample3DGrid(Grid, XFormSampler, (LPVOID) p, Grid -> wFlags)) {
 
                 cmsFreeLUT(Grid);
-                return NULL;
+                Grid = NULL;
        }
 
+       p ->Gamut        = SaveGamutLUT;
+       p ->InputFormat  = SaveFormatIn;
+       p ->OutputFormat = SaveFormatOut;
 
-       p ->Gamut = SaveGamutLUT;
        return Grid;
 }
 
@@ -348,7 +360,7 @@
 
 
 
-// That is our K-preserving callback.
+// Preserve all K plane.
 static
 int BlackPreservingSampler(register WORD In[], register WORD Out[], register LPVOID Cargo)
 {
@@ -469,6 +481,7 @@
     return OldVal;
 }
 
+#pragma warning(disable: 4550)
 
 // Get a pointer to callback on depending of strategy
 static
@@ -504,11 +517,10 @@
        if (p -> dwOriginalFlags & cmsFLAGS_BLACKPOINTCOMPENSATION)
            LocalFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION;
 
-
        // Fill in cargo struct
        Cargo.cmyk2cmyk = hCMYK2CMYK;
 
-       // Compute tone curve
+       // Compute tone curve.
        Cargo.KTone  =  _cmsBuildKToneCurve(hCMYK2CMYK, 256);
        if (Cargo.KTone == NULL) return NULL;
        cmsCalcL16Params(Cargo.KTone ->nEntries, &Cargo.KToneParams);
@@ -522,11 +534,11 @@
        Cargo.LabK2cmyk = cmsReadICCLut(p->OutputProfile, Device2PCS[p->Intent]);
 
        // Is there any table available?
-           if (Cargo.LabK2cmyk == NULL) {
+       if (Cargo.LabK2cmyk == NULL) {
 
-                   Grid = NULL;
+           Grid = NULL;
            goto Cleanup;
-           }
+       }
 
        // Setup a roundtrip on output profile for TAC estimation
        Cargo.hRoundTrip = cmsCreateTransform(p ->OutputProfile, TYPE_CMYK_16,
@@ -654,7 +666,7 @@
 
 
 
-BOOL _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p)
+LCMSBOOL _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p)
 {
 
        WORD *WhitePointIn, *WhitePointOut, *BlackPointIn, *BlackPointOut;
@@ -682,3 +694,4 @@
 
        return TRUE;
 }
+
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -320,7 +320,7 @@
     cmsHPROFILE hICC;
     _LPcmsTRANSFORM v = (_LPcmsTRANSFORM) hTransform;
     LPLUT Lut;
-    BOOL MustFreeLUT;
+    LCMSBOOL MustFreeLUT;
     LPcmsNAMEDCOLORLIST InputColorant = NULL;
     LPcmsNAMEDCOLORLIST OutputColorant = NULL;
 
@@ -373,10 +373,8 @@
 
     if (cmsGetDeviceClass(hICC) == icSigOutputClass) {
 
-
         cmsAddTag(hICC, icSigBToA0Tag, (LPVOID) Lut);
     }
-
     else
         cmsAddTag(hICC, icSigAToB0Tag, (LPVOID) Lut);
 
@@ -404,7 +402,7 @@
 
             OutputColorant = cmsReadColorantTable(v ->OutputProfile, icSigColorantTableTag);
         }
-        }
+    }
 
     if (InputColorant)
            cmsAddTag(hICC, icSigColorantTableTag, InputColorant);
@@ -446,6 +444,7 @@
 
        // Creates a LUT with prelinearization step only
        Lut = cmsAllocLUT();
+       if (Lut == NULL) return NULL;
 
        // Set up channels
        Lut ->InputChan = Lut ->OutputChan = _cmsChannelsOf(ColorSpace);
@@ -548,6 +547,10 @@
 
        // Creates a LUT with 3D grid only
        Lut = cmsAllocLUT();
+       if (Lut == NULL) {
+           cmsCloseProfile(hICC);
+           return NULL;
+           }
 
 
        cmsAlloc3DGrid(Lut, 17, _cmsChannelsOf(ColorSpace),
@@ -584,8 +587,9 @@
 LPLUT Create3x3EmptyLUT(void)
 {
         LPLUT AToB0 = cmsAllocLUT();
+        if (AToB0 == NULL) return NULL;
+
         AToB0 -> InputChan = AToB0 -> OutputChan = 3;
-
         return AToB0;
 }
 
@@ -597,8 +601,8 @@
         cmsHPROFILE hProfile;
         LPLUT Lut;
 
-
         hProfile = cmsCreateRGBProfile(WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
+        if (hProfile == NULL) return NULL;
 
         cmsSetDeviceClass(hProfile, icSigAbstractClass);
         cmsSetColorSpace(hProfile,  icSigLabData);
@@ -611,7 +615,10 @@
 
        // An empty LUTs is all we need
        Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) return NULL;
+       if (Lut == NULL) {
+           cmsCloseProfile(hProfile);
+           return NULL;
+           }
 
        cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
        cmsAddTag(hProfile, icSigBToA0Tag,    (LPVOID) Lut);
@@ -628,8 +635,8 @@
         cmsHPROFILE hProfile;
         LPLUT Lut;
 
-
         hProfile = cmsCreateRGBProfile(WhitePoint == NULL ? cmsD50_xyY() : WhitePoint, NULL, NULL);
+        if (hProfile == NULL) return NULL;
 
         cmsSetProfileICCversion(hProfile, 0x4000000);
 
@@ -644,7 +651,10 @@
 
        // An empty LUTs is all we need
        Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) return NULL;
+       if (Lut == NULL) {
+           cmsCloseProfile(hProfile);
+           return NULL;
+           }
 
        Lut -> wFlags |= LUT_V4_INPUT_EMULATE_V2;
        cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
@@ -666,6 +676,7 @@
         LPLUT Lut;
 
         hProfile = cmsCreateRGBProfile(cmsD50_xyY(), NULL, NULL);
+        if (hProfile == NULL) return NULL;
 
         cmsSetDeviceClass(hProfile, icSigAbstractClass);
         cmsSetColorSpace(hProfile, icSigXYZData);
@@ -677,15 +688,16 @@
 
        // An empty LUTs is all we need
        Lut = Create3x3EmptyLUT();
-       if (Lut == NULL) return NULL;
+       if (Lut == NULL) {
+           cmsCloseProfile(hProfile);
+           return NULL;
+           }
 
        cmsAddTag(hProfile, icSigAToB0Tag,    (LPVOID) Lut);
        cmsAddTag(hProfile, icSigBToA0Tag,    (LPVOID) Lut);
        cmsAddTag(hProfile, icSigPreview0Tag, (LPVOID) Lut);
 
        cmsFreeLUT(Lut);
-
-
        return hProfile;
 }
 
@@ -723,6 +735,7 @@
     return cmsBuildParametricGamma(1024, 4, Parameters);
 }
 
+// Create the ICC virtual profile for sRGB space
 cmsHPROFILE LCMSEXPORT cmsCreate_sRGBProfile(void)
 {
        cmsCIExyY       D65;
@@ -739,6 +752,7 @@
 
        hsRGB = cmsCreateRGBProfile(&D65, &Rec709Primaries, Gamma22);
        cmsFreeGamma(Gamma22[0]);
+       if (hsRGB == NULL) return NULL;
 
 
        cmsAddTag(hsRGB, icSigDeviceMfgDescTag,      (LPVOID) "(lcms internal)");
@@ -750,7 +764,6 @@
 
 
 
-
 typedef struct {
                 double Brightness;
                 double Contrast;
@@ -793,7 +806,6 @@
 
     cmsFloat2LabEncoded(Out, &LabOut);
 
-
     return TRUE;
 }
 
@@ -839,7 +851,10 @@
 
        // Creates a LUT with 3D grid only
        Lut = cmsAllocLUT();
-
+       if (Lut == NULL) {
+           cmsCloseProfile(hICC);
+           return NULL;
+           }
 
        cmsAlloc3DGrid(Lut, nLUTPoints, 3, 3);
 
@@ -890,7 +905,10 @@
 
        // An empty LUTs is all we need
        Lut = cmsAllocLUT();
-       if (Lut == NULL) return NULL;
+       if (Lut == NULL) {
+           cmsCloseProfile(hProfile);
+           return NULL;
+           }
 
        Lut -> InputChan = 3;
        Lut -> OutputChan = 1;
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -51,10 +51,6 @@
 
 #include "lcms.h"
 
-// Uncomment this line if you want lcms to use the black point tag in profile,
-// if commented, lcms will compute the black point by its own.
-// It is safer to leve it commented out
-// #define HONOR_BLACK_POINT_TAG
 
 // Conversions
 
@@ -79,10 +75,9 @@
 }
 
 
-
 // Obtains WhitePoint from Temperature
 
-BOOL LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint)
+LCMSBOOL LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint)
 {
        double x, y;
        double T, T2, T3;
@@ -147,7 +142,7 @@
 //            - Then, I apply these coeficients to the original matrix
 
 
-BOOL LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r, LPcmsCIExyY WhitePt,
+LCMSBOOL LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r, LPcmsCIExyY WhitePt,
                                             LPcmsCIExyYTRIPLE Primrs)
 {
         VEC3 WhitePoint, Coef;
@@ -169,14 +164,12 @@
 
 
         // Build Primaries matrix
-
         VEC3init(&Primaries.v[0], xr,        xg,         xb);
         VEC3init(&Primaries.v[1], yr,        yg,         yb);
         VEC3init(&Primaries.v[2], (1-xr-yr), (1-xg-yg),  (1-xb-yb));
 
 
         // Result = Primaries ^ (-1) inverse matrix
-
         if (!MAT3inverse(&Primaries, &Result))
                         return FALSE;
 
@@ -184,11 +177,9 @@
         VEC3init(&WhitePoint, xn/yn, 1.0, (1.0-xn-yn)/yn);
 
         // Across inverse primaries ...
-
         MAT3eval(&Coef, &Result, &WhitePoint);
 
         // Give us the Coefs, then I build transformation matrix
-
         VEC3init(&r -> v[0], Coef.n[VX]*xr,          Coef.n[VY]*xg,          Coef.n[VZ]*xb);
         VEC3init(&r -> v[1], Coef.n[VX]*yr,          Coef.n[VY]*yg,          Coef.n[VZ]*yb);
         VEC3init(&r -> v[2], Coef.n[VX]*(1.0-xr-yr), Coef.n[VY]*(1.0-xg-yg), Coef.n[VZ]*(1.0-xb-yb));
@@ -246,7 +237,7 @@
 // Returns the final chrmatic adaptation from illuminant FromIll to Illuminant ToIll
 // The cone matrix can be specified in ConeMatrix. If NULL, Bradford is assumed
 
-BOOL cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll)
+LCMSBOOL cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll)
 {
      MAT3 LamRigg   = {{ // Bradford matrix
                       {{  0.8951,  0.2664, -0.1614 }},
@@ -265,7 +256,7 @@
 
 // Same as anterior, but assuming D50 destination. White point is given in xyY
 
-BOOL cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt)
+LCMSBOOL cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt)
 {
         cmsCIEXYZ Dn;
         MAT3 Bradford;
@@ -284,7 +275,7 @@
 
 // Same as anterior, but assuming D50 source. White point is given in xyY
 
-BOOL cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt)
+LCMSBOOL cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt)
 {
         cmsCIEXYZ Dn;
         MAT3 Bradford;
@@ -304,7 +295,7 @@
 // Adapts a color to a given illuminant. Original color is expected to have
 // a SourceWhitePt white point.
 
-BOOL LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
+LCMSBOOL LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
                                      LPcmsCIEXYZ SourceWhitePt,
                                      LPcmsCIEXYZ Illuminant,
                                      LPcmsCIEXYZ Value)
@@ -404,8 +395,6 @@
 
         dj = ((vs - vj) - tj * (us - uj)) / sqrt(1 + tj*tj);
 
-
-
         if ((j!=0) && (di/dj < 0.0)) {
             Tc = 1000000.0 / (mi + (di / (di - dj)) * (mj - mi));
             break;
@@ -423,7 +412,7 @@
 
 
 static
-BOOL InRange(LPcmsCIExyY a, LPcmsCIExyY b, double tolerance)
+LCMSBOOL InRange(LPcmsCIExyY a, LPcmsCIExyY b, double tolerance)
 {
        double dist_x, dist_y;
 
@@ -458,6 +447,7 @@
 }
 
 
+// To be removed in future versions
 void _cmsIdentifyWhitePoint(char *Buffer, LPcmsCIEXYZ WhitePt)
 {
        int i, n;
@@ -518,7 +508,6 @@
     cmsCIEXYZ  BlackXYZ, MediaWhite;
 
     // If the profile does not support input direction, assume Black point 0
-
     if (!cmsIsIntentSupported(hInput, Intent, LCMS_USED_AS_INPUT)) {
 
         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
@@ -527,7 +516,6 @@
 
 
     // Try to get black by using black colorant
-
     Space = cmsGetColorSpace(hInput);
 
     if (!_cmsEndPointsBySpace(Space, &White, &Black, &nChannels)) {
@@ -576,7 +564,7 @@
 
 
 // Get a black point of output CMYK profile, discounting any ink-limiting embedded
-// in the profile. Fou doing that, use perceptual intent in input direction:
+// in the profile. For doing that, use perceptual intent in input direction:
 // Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab
 
 static
@@ -651,6 +639,8 @@
             D50BlackPoint.X = PERCEPTUAL_BLACK_X;
             D50BlackPoint.Y = PERCEPTUAL_BLACK_Y;
             D50BlackPoint.Z = PERCEPTUAL_BLACK_Z;
+
+            // Obtain the absolute XYZ. Adapt perceptual black back from D50 to whatever media white
             cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &D50BlackPoint);
         }
 
@@ -662,26 +652,24 @@
 // This function shouldn't exist at all -- there is such quantity of broken
 // profiles on black point tag, that we must somehow fix chromaticity to
 // avoid huge tint when doing Black point compensation. This function does
-// just that. If BP is specified, then forces it to neutral and uses only L
-// component. If does not exist, computes it by taking 400% of ink or RGB=0 This
-// works well on relative intent and is undefined on perceptual & saturation.
-// However, I will support all intents for tricking & trapping.
-
+// just that. There is a special flag for using black point tag, but turned
+// off by default because it is bogus on most profiles. The detection algorithm
+// involves to turn BP to neutral and to use only L component.
 
 int cmsDetectBlackPoint(LPcmsCIEXYZ BlackPoint, cmsHPROFILE hProfile, int Intent, DWORD dwFlags)
 {
 
-    // v4 + perceptual & saturation intents does have its own black point
+    // v4 + perceptual & saturation intents does have its own black point, and it is
+    // well specified enough to use it.
 
     if ((cmsGetProfileICCversion(hProfile) >= 0x4000000) &&
         (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
 
        // Matrix shaper share MRC & perceptual intents
-
        if (_cmsIsMatrixShaper(hProfile))
            return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, cmsFLAGS_NOTPRECALC);
 
-       // Get fixed value
+       // CLUT based - Get perceptual black point (fixed value)
        return GetV4PerceptualBlack(BlackPoint, hProfile, dwFlags);
     }
 
@@ -701,7 +689,6 @@
              cmsTakeMediaWhitePoint(&MediaWhite, hProfile);
 
              // Black point is absolute XYZ, so adapt to D50 to get PCS value
-
              cmsAdaptToIlluminant(&UntrustedBlackPoint, &MediaWhite, cmsD50_XYZ(), &BlackXYZ);
 
              // Force a=b=0 to get rid of any chroma
@@ -713,7 +700,6 @@
              cmsLab2XYZ(NULL, &TrustedBlackPoint, &Lab);
 
              // Return BP as D50 relative or absolute XYZ (depends on flags)
-
              if (!(dwFlags & LCMS_BPFLAGS_D50_ADAPTED))
                     cmsAdaptToIlluminant(BlackPoint, cmsD50_XYZ(), &MediaWhite, &TrustedBlackPoint);
              else
@@ -724,15 +710,15 @@
 
 #endif
 
-    // If output profile, discount ink-limiting
+    // That is about v2 profiles.
 
+    // If output profile, discount ink-limiting and that's all
     if (Intent == INTENT_RELATIVE_COLORIMETRIC &&
             (cmsGetDeviceClass(hProfile) == icSigOutputClass) &&
             (cmsGetColorSpace(hProfile) == icSigCmykData))
                 return BlackPointUsingPerceptualBlack(BlackPoint, hProfile, dwFlags);
 
     // Nope, compute BP using current intent.
-
     return BlackPointAsDarkerColorant(hProfile, Intent, BlackPoint, dwFlags);
 
 }
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -52,7 +52,6 @@
 
 #include "lcms.h"
 
-// #define DEBUG 1
 
 // Transformations stuff
 // -----------------------------------------------------------------------
@@ -85,7 +84,7 @@
 
 void         LCMSEXPORT cmsGetAlarmCodes(int *r, int *g, int *b);
 void         LCMSEXPORT cmsSetAlarmCodes(int r, int g, int b);
-BOOL         LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
+LCMSBOOL     LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
                                                 int Intent, int UsedDirection);
 
 // -------------------------------------------------------------------------
@@ -343,7 +342,7 @@
            p ->DeviceLink ->CLut16params.Interp3D(wIn, wOut,
                                     p ->DeviceLink -> T,
                                     &p ->DeviceLink -> CLut16params);
-                 }
+         }
          else
             cmsEvalLUT(p -> DeviceLink, wIn, wOut);
 
@@ -414,7 +413,7 @@
        register LPBYTE output;
        WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
        register unsigned int i, n;
-           WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
+       WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
 
 
        accum  = (LPBYTE) in;
@@ -427,10 +426,10 @@
        ZeroMemory(wOut, sizeof(WORD) * MAXCHANNELS);
 
 
-           LCMS_READ_LOCK(&p ->rwlock);
-               CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-               CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
-           LCMS_UNLOCK(&p ->rwlock);
+       LCMS_READ_LOCK(&p ->rwlock);
+           CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
+           CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
+       LCMS_UNLOCK(&p ->rwlock);
 
        for (i=0; i < n; i++) {
 
@@ -443,14 +442,14 @@
        }
        else {
 
-                        // Try to speedup things on plain devicelinks
-
-                         if (p ->DeviceLink ->wFlags == LUT_HAS3DGRID) {
+            // Try to speedup things on plain devicelinks
+
+             if (p ->DeviceLink ->wFlags == LUT_HAS3DGRID) {
 
              p ->DeviceLink ->CLut16params.Interp3D(wIn, wOut,
                                     p ->DeviceLink -> T,
                                     &p ->DeviceLink -> CLut16params);
-                     }
+             }
              else
                   cmsEvalLUT(p -> DeviceLink, wIn, wOut);
 
@@ -463,10 +462,10 @@
        }
 
 
-           LCMS_WRITE_LOCK(&p ->rwlock);
-               CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
-               CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
-           LCMS_UNLOCK(&p ->rwlock);
+       LCMS_WRITE_LOCK(&p ->rwlock);
+           CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
+           CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
+       LCMS_UNLOCK(&p ->rwlock);
 
 }
 
@@ -483,7 +482,7 @@
        register LPBYTE output;
        WORD wIn[MAXCHANNELS], wOut[MAXCHANNELS];
        register unsigned int i, n;
-           WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
+       WORD CacheIn[MAXCHANNELS], CacheOut[MAXCHANNELS];
 
 
        accum  = (LPBYTE) in;
@@ -495,10 +494,10 @@
        ZeroMemory(wIn,  sizeof(WORD) * MAXCHANNELS);
        ZeroMemory(wOut, sizeof(WORD) * MAXCHANNELS);
 
-           LCMS_READ_LOCK(&p ->rwlock);
-               CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
-               CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
-           LCMS_UNLOCK(&p ->rwlock);
+       LCMS_READ_LOCK(&p ->rwlock);
+           CopyMemory(CacheIn,  p ->CacheIn, sizeof(WORD) * MAXCHANNELS);
+           CopyMemory(CacheOut, p ->CacheOut, sizeof(WORD) * MAXCHANNELS);
+       LCMS_UNLOCK(&p ->rwlock);
 
 
        for (i=0; i < n; i++) {
@@ -520,10 +519,10 @@
        output = p -> ToOutput(p, wOut, output);
        }
 
-            LCMS_WRITE_LOCK(&p ->rwlock);
-               CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
-               CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
-            LCMS_UNLOCK(&p ->rwlock);
+        LCMS_WRITE_LOCK(&p ->rwlock);
+           CopyMemory(p->CacheIn,  CacheIn, sizeof(WORD) * MAXCHANNELS);
+           CopyMemory(p->CacheOut, CacheOut, sizeof(WORD) * MAXCHANNELS);
+        LCMS_UNLOCK(&p ->rwlock);
 }
 
 
@@ -635,6 +634,8 @@
        MAT3 Scale;
 
        GrayTRC = cmsReadICCGamma(hProfile, icSigGrayTRCTag);        // Y
+       if (GrayTRC == NULL) return NULL;
+
        cmsTakeIluminant(&Illuminant, hProfile);
 
        if (cmsGetPCS(hProfile) == icSigLabData) {
@@ -789,6 +790,10 @@
        InverseShapes[1] = cmsReadICCGammaReversed(OutputProfile, icSigGreenTRCTag);
        InverseShapes[2] = cmsReadICCGammaReversed(OutputProfile, icSigBlueTRCTag);
 
+       if (InverseShapes[0] == NULL ||
+           InverseShapes[1] == NULL ||
+           InverseShapes[2] == NULL) return NULL;
+
        OutMatSh = cmsAllocMatShaper(&DoubleInv, InverseShapes, MATSHAPER_OUTPUT);
 
        cmsFreeGammaTriple(InverseShapes);
@@ -801,7 +806,7 @@
 // This function builds a transform matrix chaining parameters
 
 static
-BOOL cmsBuildSmeltMatShaper(_LPcmsTRANSFORM p)
+LCMSBOOL cmsBuildSmeltMatShaper(_LPcmsTRANSFORM p)
 {
        MAT3 From, To, ToInv, Transfer;
        LPGAMMATABLE In[3], InverseOut[3];
@@ -814,7 +819,6 @@
        if (!cmsReadICCMatrixRGB2XYZ(&To, p -> OutputProfile))
                      return FALSE;
 
-
        // invert dest
 
        if (MAT3inverse(&To, &ToInv) < 0)
@@ -838,10 +842,14 @@
         InverseOut[1] = cmsReadICCGammaReversed(p -> OutputProfile, icSigGreenTRCTag);
         InverseOut[2] = cmsReadICCGammaReversed(p -> OutputProfile, icSigBlueTRCTag);
 
+        if (!InverseOut[0] || !InverseOut[1] || !InverseOut[2]) {
+                     cmsFreeGammaTriple(In);
+                     return FALSE;
+        }
+
         p -> SmeltMatShaper = cmsAllocMatShaper2(&Transfer, In, InverseOut, MATSHAPER_ALLSMELTED);
 
         cmsFreeGammaTriple(In);
-
         cmsFreeGammaTriple(InverseOut);
 
         return (p -> SmeltMatShaper != NULL);
@@ -1029,7 +1037,7 @@
 // Check colorspace
 
 static
-BOOL IsProperColorSpace(cmsHPROFILE hProfile, DWORD dwFormat, BOOL lUsePCS)
+LCMSBOOL IsProperColorSpace(cmsHPROFILE hProfile, DWORD dwFormat, LCMSBOOL lUsePCS)
 {
        int Space = T_COLORSPACE(dwFormat);
 
@@ -1049,10 +1057,10 @@
 {
     // Allocate needed memory
 
-    _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) malloc(sizeof(_cmsTRANSFORM));
+    _LPcmsTRANSFORM p = (_LPcmsTRANSFORM) _cmsMalloc(sizeof(_cmsTRANSFORM));
     if (!p) {
 
-          cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateTransform: malloc() failed");
+          cmsSignalError(LCMS_ERRC_ABORTED, "cmsCreateTransform: _cmsMalloc() failed");
           return NULL;
     }
 
@@ -1078,7 +1086,7 @@
     p -> ExitColorSpace  = (icColorSpaceSignature) 0;
     p -> AdaptationState = GlobalAdaptationState;
 
-        LCMS_CREATE_LOCK(&p->rwlock);
+    LCMS_CREATE_LOCK(&p->rwlock);
 
     return p;
 }
@@ -1269,12 +1277,12 @@
         else {
                 // Can we optimize matrix-shaper only transform?
 
-                   if (*FromTagPtr == 0 &&
-                       *ToTagPtr == 0 &&
-                       !p->PreviewProfile  &&
-                       p -> Intent != INTENT_ABSOLUTE_COLORIMETRIC &&
+                   if ((*FromTagPtr == 0) &&
+                       (*ToTagPtr == 0) &&
+                       (!p->PreviewProfile) &&
+                       (p -> Intent != INTENT_ABSOLUTE_COLORIMETRIC) &&
                        (p -> EntryColorSpace == icSigRgbData) &&
-                       (p -> ExitColorSpace == icSigRgbData) &&
+                       (p -> ExitColorSpace == icSigRgbData)  &&
                        !(p -> dwOriginalFlags & cmsFLAGS_BLACKPOINTCOMPENSATION)) {
 
                           // Yes... try to smelt matrix-shapers
@@ -1530,7 +1538,6 @@
 
        TakeConversionRoutines(p, dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
 
-
        if (!(p -> dwOriginalFlags & cmsFLAGS_NOTPRECALC)) {
 
                LPLUT DeviceLink;
@@ -1553,7 +1560,8 @@
                     DeviceLink = _cmsPrecalculateDeviceLink((cmsHTRANSFORM) p, dwFlags);
                }
 
-               if (p -> dwOriginalFlags & cmsFLAGS_GAMUTCHECK) {
+               // Allow to specify cmsFLAGS_GAMUTCHECK, even if no proofing profile is given
+               if ((p ->PreviewProfile != NULL) && (p -> dwOriginalFlags & cmsFLAGS_GAMUTCHECK)) {
 
                    GamutCheck = _cmsPrecalculateGamutCheck((cmsHTRANSFORM) p);
                }
@@ -1561,7 +1569,6 @@
                // If input colorspace is Rgb, Cmy, then use tetrahedral interpolation
                // for speed reasons (it only works well on spaces on Luma is diagonal, and
                // not if luma is in separate channel)
-
                if (p ->EntryColorSpace == icSigRgbData ||
                    p ->EntryColorSpace == icSigCmyData) {
 
@@ -1663,12 +1670,12 @@
               cmsFreeMatShaper(p -> SmeltMatShaper);
        if (p ->NamedColorList)
               cmsFreeNamedColorList(p ->NamedColorList);
-           if (p -> GamutCheck)
-                        cmsFreeLUT(p -> GamutCheck);
-
-           LCMS_FREE_LOCK(&p->rwlock);
-
-       free((void *) p);
+       if (p -> GamutCheck)
+            cmsFreeLUT(p -> GamutCheck);
+
+       LCMS_FREE_LOCK(&p->rwlock);
+
+       _cmsFree((void *) p);
 }
 
 
@@ -1704,7 +1711,7 @@
 
 // Returns TRUE if the profile is implemented as matrix-shaper
 
-BOOL LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile)
+LCMSBOOL LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile)
 {
     switch (cmsGetColorSpace(hProfile)) {
 
@@ -1728,7 +1735,7 @@
 }
 
 
-BOOL LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
+LCMSBOOL LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
                                                 int Intent, int UsedDirection)
 {
 
@@ -1774,6 +1781,16 @@
 }
 
 
+static
+int IsAllowedInSingleXform(icProfileClassSignature aClass)
+{
+    return (aClass == icSigInputClass) ||
+           (aClass == icSigDisplayClass) ||
+           (aClass == icSigOutputClass) ||
+           (aClass == icSigColorSpaceClass);
+}
+
+
 // A multiprofile transform does chain several profiles into a single
 // devicelink. It couls also be used to merge named color profiles into
 // a single database.
@@ -1805,10 +1822,16 @@
     // There is a simple case with just two profiles, try to catch it in order of getting
     // black preservation to work on this function, at least with two profiles.
 
+
     if (nProfiles == 2) {
 
-        if ((cmsGetDeviceClass(hProfiles[0]) != icSigLinkClass) &&
-            (cmsGetDeviceClass(hProfiles[1]) != icSigLinkClass))
+        icProfileClassSignature Class1 = cmsGetDeviceClass(hProfiles[0]);
+        icProfileClassSignature Class2 = cmsGetDeviceClass(hProfiles[1]);
+
+        // Only input, output and display are allowed
+
+        if (IsAllowedInSingleXform(Class1) &&
+            IsAllowedInSingleXform(Class2))
                    return cmsCreateTransform(hProfiles[0], dwInput, hProfiles[1], dwOutput, Intent, dwFlags);
     }
 
@@ -1984,6 +2007,14 @@
     if (hLab) cmsCloseProfile(hLab);
     if (hXYZ) cmsCloseProfile(hXYZ);
 
+
+    if (p ->EntryColorSpace == icSigRgbData ||
+        p ->EntryColorSpace == icSigCmyData) {
+
+                    p->DeviceLink -> CLut16params.Interp3D = cmsTetrahedralInterp16;
+    }
+
+
     if ((Intent != INTENT_ABSOLUTE_COLORIMETRIC) &&
         !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP))
                             _cmsFixWhiteMisalignment(p);
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/icc34.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/icc34.h	Fri Apr 10 13:05:12 2009 -0700
@@ -206,6 +206,11 @@
 
 #if defined(__sun) || defined(__hpux) || defined (__MINGW) || defined(__MINGW32__)
 
+#if defined (__MINGW) || defined(__MINGW32__)
+#include <stdint.h>
+#endif
+
+
 typedef uint8_t   icUInt8Number;
 typedef uint16_t  icUInt16Number;
 typedef uint32_t  icUInt32Number;
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms.h	Fri Apr 10 13:05:12 2009 -0700
@@ -29,7 +29,7 @@
 //
 //
 //  Little cms
-//  Copyright (C) 1998-2006 Marti Maria
+//  Copyright (C) 1998-2007 Marti Maria
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -49,8 +49,8 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
-// Version 1.16
-#undef DEBUG
+// Version 1.18
+
 #ifndef __cms_H
 
 // ********** Configuration toggles ****************************************
@@ -62,13 +62,8 @@
 // virtually any machine.
 
 //#define USE_FLOAT        1
-#ifdef _WIN64
-#define USE_C            1
-#undef USE_ASSEMBLER
-#else
-#undef USE_C
+// #define USE_C            1
 #define USE_ASSEMBLER    1
-#endif
 
 // Define this if you are using this package as a DLL (windows only)
 
@@ -77,15 +72,11 @@
 
 // Uncomment if you are trying the engine in a non-windows environment
 // like linux, SGI, VAX, FreeBSD, BeOS, etc.
-#if !defined(_WIN32) || !defined(_WIN64)
 #define NON_WINDOWS  1
-#endif
 
 // Uncomment this one if you are using big endian machines (only meaningful
 // when NON_WINDOWS is used)
-#ifndef _LITTLE_ENDIAN
-#define USE_BIG_ENDIAN   1
-#endif
+// #define USE_BIG_ENDIAN   1
 
 // Uncomment this one if your compiler/machine does support the
 // "long long" type This will speedup fixed point math. (USE_C only)
@@ -104,18 +95,24 @@
 // Uncomment this line on multithreading environments
 // #define USE_PTHREADS    1
 
+// Uncomment this line if you want lcms to use the black point tag in profile,
+// if commented, lcms will compute the black point by its own.
+// It is safer to leve it commented out
+// #define HONOR_BLACK_POINT_TAG    1
+
 // ********** End of configuration toggles ******************************
 
-#define LCMS_VERSION        116
+#define LCMS_VERSION        118
 
 // Microsoft VisualC++
 
 // Deal with Microsoft's attempt at deprecating C standard runtime functions
-
 #ifdef _MSC_VER
 #    undef NON_WINDOWS
 #    if (_MSC_VER >= 1400)
+#      ifndef _CRT_SECURE_NO_DEPRECATE
 #        define _CRT_SECURE_NO_DEPRECATE 1
+#      endif
 #    endif
 #endif
 
@@ -125,7 +122,6 @@
 #    undef NON_WINDOWS
 #endif
 
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <math.h>
@@ -134,11 +130,11 @@
 #include <time.h>
 
 // Metroworks CodeWarrior
-
 #ifdef __MWERKS__
 #   define unlink remove
 #   if WIN32
 #       define USE_CUSTOM_SWAB 1
+#       undef  NON_WINDOWS
 #   else
 #       define NON_WINDOWS   1
 #   endif
@@ -172,15 +168,21 @@
 #   define USE_BIG_ENDIAN      1
 #endif
 
-#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(sparc) || defined(__ppc__)
+#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(sparc) || defined(__ppc__) || defined(__s390__) || defined(__s390x__)
 #   define USE_BIG_ENDIAN      1
 #endif
 
-#ifdef TARGET_CPU_PPC
+#if TARGET_CPU_PPC
 #   define USE_BIG_ENDIAN   1
 #endif
 
-#ifdef macintosh
+#if macintosh
+# ifndef __LITTLE_ENDIAN__
+#   define USE_BIG_ENDIAN      1
+# endif
+#endif
+
+#ifdef __BIG_ENDIAN__
 #   define USE_BIG_ENDIAN      1
 #endif
 
@@ -217,11 +219,8 @@
 typedef unsigned char BYTE, *LPBYTE;
 typedef unsigned short WORD, *LPWORD;
 typedef unsigned long DWORD, *LPDWORD;
-typedef int BOOL;
 typedef char *LPSTR;
 typedef void *LPVOID;
-typedef void* LCMSHANDLE;
-
 
 #define ZeroMemory(p,l)     memset((p),0,(l))
 #define CopyMemory(d,s,l)   memcpy((d),(s),(l))
@@ -263,8 +262,12 @@
 
 #include <windows.h>
 
-typedef HANDLE LCMSHANDLE;
-
+#ifdef _WIN64
+# ifdef USE_ASSEMBLER
+#    undef  USE_ASSEMBLER
+#    define USE_C           1
+# endif
+#endif
 
 #ifdef  USE_INT64
 #  ifndef LCMSULONGLONG
@@ -296,6 +299,10 @@
 #   define LCMS_UNLOCK(x)
 #endif
 
+// Base types
+
+typedef int   LCMSBOOL;
+typedef void* LCMSHANDLE;
 
 #include "icc34.h"          // ICC header file
 
@@ -322,16 +329,10 @@
 #define icSigMCHEData                  ((icColorSpaceSignature) 0x4d434845L)  // MCHE
 #define icSigMCHFData                  ((icColorSpaceSignature) 0x4d434846L)  // MCHF
 
-#define icSigCAM97JABData              ((icColorSpaceSignature) 0x4A616231L)  // 'Jab1' H. Zeng
-#define icSigCAM02JABData              ((icColorSpaceSignature) 0x4A616232L)  // 'Jab2' H. Zeng
-#define icSigCAM02JCHData              ((icColorSpaceSignature) 0x4A636A32L)  // 'Jch2' H. Zeng
-
 #define icSigChromaticityTag            ((icTagSignature) 0x6368726dL) // As per Addendum 2 to Spec. ICC.1:1998-09
 #define icSigChromaticAdaptationTag     ((icTagSignature) 0x63686164L) // 'chad'
 #define icSigColorantTableTag           ((icTagSignature) 0x636c7274L) // 'clrt'
 #define icSigColorantTableOutTag        ((icTagSignature) 0x636c6f74L) // 'clot'
-#define icSigHPGamutDescTag             ((icTagSignature) 0x676D7441L) // 'gmtA' H. Zeng
-
 
 #define icSigParametricCurveType        ((icTagTypeSignature) 0x70617261L)  // parametric (ICC 4.0)
 #define icSigMultiLocalizedUnicodeType  ((icTagTypeSignature) 0x6D6C7563L)
@@ -340,7 +341,6 @@
 #define icSiglutAtoBType                ((icTagTypeSignature) 0x6d414220L)  // mAB
 #define icSiglutBtoAType                ((icTagTypeSignature) 0x6d424120L)  // mBA
 #define icSigColorantTableType          ((icTagTypeSignature) 0x636c7274L)  // clrt
-#define icSigHPGamutDescType            ((icTagTypeSignature) 0x676D7441L)  // gmtA H. Zeng
 
 
 typedef struct {
@@ -438,9 +438,6 @@
 #ifndef itoa
 #       define itoa   _itoa
 #endif
-#ifndef filelength
-#       define filelength _filelength
-#endif
 #ifndef fileno
 #       define fileno   _fileno
 #endif
@@ -450,6 +447,14 @@
 #ifndef hypot
 #       define hypot    _hypot
 #endif
+#ifndef snprintf
+#       define snprintf  _snprintf
+#endif
+#ifndef vsnprintf
+#       define vsnprintf  _vsnprintf
+#endif
+
+
 #endif
 
 
@@ -470,8 +475,9 @@
 
 // Format of pixel is defined by one DWORD, using bit fields as follows
 //
-//            TTTTT U Y F P X S EEE CCCC BBB
+//            D TTTTT U Y F P X S EEE CCCC BBB
 //
+//            D: Use dither (8 bits only)
 //            T: Pixeltype
 //            F: Flavor  0=MinIsBlack(Chocolate) 1=MinIsWhite(Vanilla)
 //            P: Planar? 0=Chunky, 1=Planar
@@ -483,6 +489,7 @@
 //            Y: Swap first - changes ABGR to BGRA and KCMY to CMYK
 
 
+#define DITHER_SH(s)           ((s) << 22)
 #define COLORSPACE_SH(s)       ((s) << 16)
 #define SWAPFIRST_SH(s)        ((s) << 14)
 #define FLAVOR_SH(s)           ((s) << 13)
@@ -711,20 +718,20 @@
 
 typedef struct {
 
-        unsigned int Crc32;  // Has my table been touched?
-
-        // Keep initial parameters for further serialization
+    unsigned int Crc32;  // Has my table been touched?
+
+    // Keep initial parameters for further serialization
 
     int          Type;
     double       Params[10];
 
-        }  LCMSGAMMAPARAMS, FAR* LPLCMSGAMMAPARAMS;
+    }  LCMSGAMMAPARAMS, FAR* LPLCMSGAMMAPARAMS;
 
 // Gamma tables.
 
 typedef struct {
 
-        LCMSGAMMAPARAMS Seed;   // Parameters used for table creation
+    LCMSGAMMAPARAMS Seed;       // Parameters used for table creation
 
     // Table-based representation follows
 
@@ -858,7 +865,7 @@
 
 LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess);
 LCMSAPI cmsHPROFILE   LCMSEXPORT cmsOpenProfileFromMem(LPVOID MemPtr, DWORD dwSize);
-LCMSAPI BOOL          LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile);
 
 // Predefined run-time profiles
 
@@ -915,14 +922,14 @@
 
 LCMSAPI void          LCMSEXPORT cmsClampLab(LPcmsCIELab Lab, double amax, double amin, double bmax, double bmin);
 
-LCMSAPI BOOL          LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint);
-
-LCMSAPI BOOL          LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsWhitePointFromTemp(int TempK, LPcmsCIExyY WhitePoint);
+
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsAdaptToIlluminant(LPcmsCIEXYZ Result,
                                                         LPcmsCIEXYZ SourceWhitePt,
                                                         LPcmsCIEXYZ Illuminant,
                                                         LPcmsCIEXYZ Value);
 
-LCMSAPI BOOL          LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r,
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsBuildRGB2XYZtransferMatrix(LPMAT3 r,
                                                         LPcmsCIExyY WhitePoint,
                                                         LPcmsCIExyYTRIPLE Primaries);
 
@@ -976,7 +983,7 @@
 LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsReverseGamma(int nResultSamples, LPGAMMATABLE InGamma);
 LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsJoinGamma(LPGAMMATABLE InGamma,  LPGAMMATABLE OutGamma);
 LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsJoinGammaEx(LPGAMMATABLE InGamma,  LPGAMMATABLE OutGamma, int nPoints);
-LCMSAPI BOOL          LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsSmoothGamma(LPGAMMATABLE Tab, double lambda);
 LCMSAPI double        LCMSEXPORT cmsEstimateGamma(LPGAMMATABLE t);
 LCMSAPI double        LCMSEXPORT cmsEstimateGammaEx(LPWORD Table, int nEntries, double Thereshold);
 LCMSAPI LPGAMMATABLE  LCMSEXPORT cmsReadICCGamma(cmsHPROFILE hProfile, icTagSignature sig);
@@ -984,14 +991,14 @@
 
 // Access to Profile data.
 
-LCMSAPI BOOL          LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI BOOL          LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI BOOL          LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
-LCMSAPI BOOL          LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeMediaWhitePoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeMediaBlackPoint(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeIluminant(LPcmsCIEXYZ Dest, cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeColorants(LPcmsCIEXYZTRIPLE Dest, cmsHPROFILE hProfile);
 LCMSAPI DWORD         LCMSEXPORT cmsTakeHeaderFlags(cmsHPROFILE hProfile);
 LCMSAPI DWORD         LCMSEXPORT cmsTakeHeaderAttributes(cmsHPROFILE hProfile);
 
-LCMSAPI void          LCMSEXPORT cmsSetLanguage(int LanguageCode, int CountryCode);
+LCMSAPI void          LCMSEXPORT cmsSetLanguage(const char LanguageCode[4], const char CountryCode[4]);
 LCMSAPI const char*   LCMSEXPORT cmsTakeProductName(cmsHPROFILE hProfile);
 LCMSAPI const char*   LCMSEXPORT cmsTakeProductDesc(cmsHPROFILE hProfile);
 LCMSAPI const char*   LCMSEXPORT cmsTakeProductInfo(cmsHPROFILE hProfile);
@@ -1000,13 +1007,13 @@
 LCMSAPI const char*   LCMSEXPORT cmsTakeCopyright(cmsHPROFILE hProfile);
 LCMSAPI const BYTE*   LCMSEXPORT cmsTakeProfileID(cmsHPROFILE hProfile);
 
-LCMSAPI BOOL          LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
-LCMSAPI BOOL          LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
-
-LCMSAPI BOOL          LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCreationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCalibrationDateTime(struct tm *Dest, cmsHPROFILE hProfile);
+
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsIsTag(cmsHPROFILE hProfile, icTagSignature sig);
 LCMSAPI int           LCMSEXPORT cmsTakeRenderingIntent(cmsHPROFILE hProfile);
 
-LCMSAPI BOOL          LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len);
+LCMSAPI LCMSBOOL      LCMSEXPORT cmsTakeCharTargetData(cmsHPROFILE hProfile, char** Data, size_t* len);
 
 LCMSAPI int           LCMSEXPORT cmsReadICCTextEx(cmsHPROFILE hProfile, icTagSignature sig, char *Text, size_t size);
 LCMSAPI int           LCMSEXPORT cmsReadICCText(cmsHPROFILE hProfile, icTagSignature sig, char *Text);
@@ -1038,50 +1045,18 @@
 LCMSAPI void          LCMSEXPORT cmsFreeProfileSequenceDescription(LPcmsSEQ pseq);
 
 
-// Extended gamut tag -- an HP extension
-
-#define LCMSGAMUTMETHOD_SEGMENTMAXIMA   0
-#define LCMSGAMUTMETHOD_CONVEXHULL      1
-#define LCMSGAMUTMETHOD_ALPHASHAPE      2
-
-
-#define LCMSGAMUT_PHYSICAL                              0
-#define LCMSGAMUT_HP1                                   1
-#define LCMSGAMUT_HP2                                   2
-
-typedef struct {
-
-                        icColorSpaceSignature  CoordSig;        // Gamut coordinates signature
-                        icUInt16Number         Method;          // Method used to generate gamut
-                        icUInt16Number         Usage;       // Gamut usage or intent
-
-                        char Description[LCMS_DESC_MAX];        // Textual description
-
-                        cmsViewingConditions   Vc;                      // The viewing conditions
-
-                        icUInt32Number         Count;           // Number of entries
-                        double                             Data[1];         // The current data
-
-        } cmsGAMUTEX, FAR* LPcmsGAMUTEX;
-
-
-LCMSAPI LPcmsGAMUTEX LCMSEXPORT cmsReadExtendedGamut(cmsHPROFILE hProfile, int index);
-LCMSAPI void         LCMSEXPORT cmsFreeExtendedGamut(LPcmsGAMUTEX gex);
-
-
-
-
 // Translate form/to our notation to ICC
 LCMSAPI icColorSpaceSignature LCMSEXPORT _cmsICCcolorSpace(int OurNotation);
-LCMSAPI                   int LCMSEXPORT _cmsLCMScolorSpace(icColorSpaceSignature ProfileSpace);
-LCMSAPI                   int LCMSEXPORT _cmsChannelsOf(icColorSpaceSignature ColorSpace);
-LCMSAPI BOOL                  LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile);
-
+LCMSAPI int                   LCMSEXPORT _cmsLCMScolorSpace(icColorSpaceSignature ProfileSpace);
+LCMSAPI int                   LCMSEXPORT _cmsChannelsOf(icColorSpaceSignature ColorSpace);
+LCMSAPI LCMSBOOL              LCMSEXPORT _cmsIsMatrixShaper(cmsHPROFILE hProfile);
+
+// How profiles may be used
 #define LCMS_USED_AS_INPUT      0
 #define LCMS_USED_AS_OUTPUT     1
 #define LCMS_USED_AS_PROOF      2
 
-LCMSAPI BOOL         LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile, int Intent, int UsedDirection);
+LCMSAPI LCMSBOOL                LCMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile, int Intent, int UsedDirection);
 
 LCMSAPI icColorSpaceSignature   LCMSEXPORT cmsGetPCS(cmsHPROFILE hProfile);
 LCMSAPI icColorSpaceSignature   LCMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile);
@@ -1141,7 +1116,7 @@
 
 // CRD special
 
-#define cmsFLAGS_NODEFAULTRESOURCEDEF     0x00010000
+#define cmsFLAGS_NODEFAULTRESOURCEDEF     0x01000000
 
 // Gridpoints
 
@@ -1220,9 +1195,9 @@
 
 // Named color support
 
-LCMSAPI int  LCMSEXPORT cmsNamedColorCount(cmsHTRANSFORM xform);
-LCMSAPI BOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix);
-LCMSAPI int  LCMSEXPORT cmsNamedColorIndex(cmsHTRANSFORM xform, const char* Name);
+LCMSAPI int      LCMSEXPORT cmsNamedColorCount(cmsHTRANSFORM xform);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsNamedColorInfo(cmsHTRANSFORM xform, int nColor, char* Name, char* Prefix, char* Suffix);
+LCMSAPI int      LCMSEXPORT cmsNamedColorIndex(cmsHTRANSFORM xform, const char* Name);
 
 // Colorant tables
 
@@ -1230,7 +1205,7 @@
 
 // Profile creation
 
-LCMSAPI BOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* data);
+LCMSAPI LCMSBOOL LCMSEXPORT cmsAddTag(cmsHPROFILE hProfile, icTagSignature sig, const void* data);
 
 // Converts a transform to a devicelink profile
 LCMSAPI cmsHPROFILE LCMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, DWORD dwFlags);
@@ -1240,8 +1215,8 @@
 
 
 // Save profile
-LCMSAPI BOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName);
-LCMSAPI BOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
+LCMSAPI LCMSBOOL LCMSEXPORT _cmsSaveProfile(cmsHPROFILE hProfile, const char* FileName);
+LCMSAPI LCMSBOOL LCMSEXPORT _cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr,
                                                                 size_t* BytesNeeded);
 
 
@@ -1286,6 +1261,7 @@
 LCMSAPI LPLUT  LCMSEXPORT cmsReadICCLut(cmsHPROFILE hProfile, icTagSignature sig);
 LCMSAPI LPLUT  LCMSEXPORT cmsDupLUT(LPLUT Orig);
 
+
 // LUT Sampling
 
 typedef int (* _cmsSAMPLER)(register WORD In[],
@@ -1325,35 +1301,37 @@
 // Persistence
 LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromFile(const char* cFileName);
 LCMSAPI LCMSHANDLE      LCMSEXPORT cmsIT8LoadFromMem(void *Ptr, size_t len);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToFile(LCMSHANDLE IT8, const char* cFileName);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SaveToMem(LCMSHANDLE hIT8, void *MemPtr, size_t* BytesNeeded);
 
 // Properties
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetSheetType(LCMSHANDLE hIT8);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
-
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
-
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
-
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetSheetType(LCMSHANDLE hIT8, const char* Type);
+
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetComment(LCMSHANDLE hIT8, const char* cComment);
+
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyStr(LCMSHANDLE hIT8, const char* cProp, const char *Str);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyDbl(LCMSHANDLE hIT8, const char* cProp, double Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyHex(LCMSHANDLE hIT8, const char* cProp, int Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char* cSubProp, const char *Val);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetPropertyUncooked(LCMSHANDLE hIT8, const char* Key, const char* Buffer);
 
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetProperty(LCMSHANDLE hIT8, const char* cProp);
 LCMSAPI double          LCMSEXPORT cmsIT8GetPropertyDbl(LCMSHANDLE hIT8, const char* cProp);
-LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE IT8, char ***PropertyNames);
+LCMSAPI const char*     LCMSEXPORT cmsIT8GetPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char *cSubProp);
+LCMSAPI int             LCMSEXPORT cmsIT8EnumProperties(LCMSHANDLE hIT8, const char ***PropertyNames);
+LCMSAPI int             LCMSEXPORT cmsIT8EnumPropertyMulti(LCMSHANDLE hIT8, const char* cProp, const char*** SubpropertyNames);
 
 // Datasets
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetDataRowCol(LCMSHANDLE IT8, int row, int col);
 LCMSAPI double          LCMSEXPORT cmsIT8GetDataRowColDbl(LCMSHANDLE IT8, int row, int col);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowCol(LCMSHANDLE hIT8, int row, int col,
                                                 const char* Val);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataRowColDbl(LCMSHANDLE hIT8, int row, int col,
                                                 double Val);
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetData(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
@@ -1361,25 +1339,28 @@
 
 LCMSAPI double          LCMSEXPORT cmsIT8GetDataDbl(LCMSHANDLE IT8, const char* cPatch, const char* cSample);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetData(LCMSHANDLE IT8, const char* cPatch,
                                                 const char* cSample,
                                                 const char *Val);
 
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataDbl(LCMSHANDLE hIT8, const char* cPatch,
                                                 const char* cSample,
                                                 double Val);
 
 LCMSAPI int             LCMSEXPORT cmsIT8GetDataFormat(LCMSHANDLE hIT8, const char* cSample);
-LCMSAPI BOOL            LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetDataFormat(LCMSHANDLE IT8, int n, const char *Sample);
 LCMSAPI int             LCMSEXPORT cmsIT8EnumDataFormat(LCMSHANDLE IT8, char ***SampleNames);
 
 
 LCMSAPI const char*     LCMSEXPORT cmsIT8GetPatchName(LCMSHANDLE hIT8, int nPatch, char* buffer);
+LCMSAPI int             LCMSEXPORT cmsIT8GetPatchByName(LCMSHANDLE hIT8, const char *cSample);
 
 // The LABEL extension
 
 LCMSAPI int             LCMSEXPORT cmsIT8SetTableByLabel(LCMSHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType);
 
+LCMSAPI LCMSBOOL        LCMSEXPORT cmsIT8SetIndexColumn(LCMSHANDLE hIT8, const char* cSample);
+
 // Formatter for double
 LCMSAPI void            LCMSEXPORT cmsIT8DefineDblFormat(LCMSHANDLE IT8, const char* Formatter);
 
@@ -1405,15 +1386,16 @@
 
 // Profiling Extensions --- Would be removed from API in future revisions
 
-LCMSAPI BOOL LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile,  icTagSignature sig, const char* Text);
-LCMSAPI BOOL LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile,   icTagSignature sig, const cmsCIEXYZ* XYZ);
-LCMSAPI BOOL LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile,   icTagSignature sig, const void* lut);
-LCMSAPI BOOL LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction);
-LCMSAPI BOOL LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm);
-LCMSAPI BOOL LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ PSeq);
-LCMSAPI BOOL LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
-LCMSAPI BOOL LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime);
-LCMSAPI BOOL LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddTextTag(cmsHPROFILE hProfile,  icTagSignature sig, const char* Text);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddXYZTag(cmsHPROFILE hProfile,   icTagSignature sig, const cmsCIEXYZ* XYZ);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddLUTTag(cmsHPROFILE hProfile,   icTagSignature sig, const void* lut);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddGammaTag(cmsHPROFILE hProfile, icTagSignature sig, LPGAMMATABLE TransferFunction);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddChromaticityTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsCIExyYTRIPLE Chrm);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddSequenceDescriptionTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsSEQ PSeq);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddNamedColorTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddDateTimeTag(cmsHPROFILE hProfile, icTagSignature sig, struct tm *DateTime);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddColorantTableTag(cmsHPROFILE hProfile, icTagSignature sig, LPcmsNAMEDCOLORLIST nc);
+LCMSAPI LCMSBOOL      LCMSEXPORT _cmsAddChromaticAdaptationTag(cmsHPROFILE hProfile, icTagSignature sig, const cmsCIEXYZ* mat);
 
 // --------------------------------------------------------------------------------------------------- Inline functions
 
@@ -1455,6 +1437,38 @@
        return (WORD) in;
 }
 
+#ifndef LCMS_USER_ALLOC
+
+// Low-level alloc hook
+
+LCMS_INLINE void* _cmsMalloc(size_t size)
+{
+    if (size > ((size_t) 1024*1024*500)) return NULL;  // Never allow over 500Mb
+    if (size < 0) return NULL;              // Prevent signed size_t exploits
+
+    return (void*) malloc(size);
+}
+
+LCMS_INLINE void* _cmsCalloc(size_t nmemb, size_t size)
+{
+    size_t alloc = nmemb * size;
+
+        if (size == 0) {
+                return _cmsMalloc(0);
+        }
+        if (alloc / size != nmemb) {
+        return NULL;
+    }
+    return _cmsMalloc(alloc);
+}
+
+LCMS_INLINE void _cmsFree(void *Ptr)
+{
+    if (Ptr) free(Ptr);
+}
+
+#endif
+
 // ------------------------------------------------------------------------------------------- end of inline functions
 
 // Signal error from inside lcms code
@@ -1531,36 +1545,36 @@
 
 
 
-void   cdecl VEC3init(LPVEC3 r, double x, double y, double z);   // double version
-void   cdecl VEC3initF(LPWVEC3 r, double x, double y, double z); // Fix32 version
-void   cdecl VEC3toFix(LPWVEC3 r, LPVEC3 v);
-void   cdecl VEC3fromFix(LPVEC3 r, LPWVEC3 v);
-void   cdecl VEC3scaleFix(LPWORD r, LPWVEC3 Scale);
-void   cdecl VEC3swap(LPVEC3 a, LPVEC3 b);
-void   cdecl VEC3divK(LPVEC3 r, LPVEC3 v, double d);
-void   cdecl VEC3perK(LPVEC3 r, LPVEC3 v, double d);
-void   cdecl VEC3minus(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-void   cdecl VEC3perComp(LPVEC3 r, LPVEC3 a, LPVEC3 b);
-BOOL   cdecl VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance);
-BOOL   cdecl VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance);
-void   cdecl VEC3scaleAndCut(LPWVEC3 r, LPVEC3 v, double d);
-void   cdecl VEC3cross(LPVEC3 r, LPVEC3 u, LPVEC3 v);
-void   cdecl VEC3saturate(LPVEC3 v);
-double cdecl VEC3distance(LPVEC3 a, LPVEC3 b);
-double cdecl VEC3length(LPVEC3 a);
-
-void   cdecl MAT3identity(LPMAT3 a);
-void   cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
-void   cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
-int    cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
-BOOL   cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
-double cdecl MAT3det(LPMAT3 m);
-void   cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
-void   cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
-void   cdecl MAT3fromFix(LPMAT3 r, LPWMAT3 v);
-void   cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
-BOOL   cdecl MAT3isIdentity(LPWMAT3 a, double Tolerance);
-void   cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
+void      cdecl VEC3init(LPVEC3 r, double x, double y, double z);   // double version
+void      cdecl VEC3initF(LPWVEC3 r, double x, double y, double z); // Fix32 version
+void      cdecl VEC3toFix(LPWVEC3 r, LPVEC3 v);
+void      cdecl VEC3fromFix(LPVEC3 r, LPWVEC3 v);
+void      cdecl VEC3scaleFix(LPWORD r, LPWVEC3 Scale);
+void      cdecl VEC3swap(LPVEC3 a, LPVEC3 b);
+void      cdecl VEC3divK(LPVEC3 r, LPVEC3 v, double d);
+void      cdecl VEC3perK(LPVEC3 r, LPVEC3 v, double d);
+void      cdecl VEC3minus(LPVEC3 r, LPVEC3 a, LPVEC3 b);
+void      cdecl VEC3perComp(LPVEC3 r, LPVEC3 a, LPVEC3 b);
+LCMSBOOL  cdecl VEC3equal(LPWVEC3 a, LPWVEC3 b, double Tolerance);
+LCMSBOOL  cdecl VEC3equalF(LPVEC3 a, LPVEC3 b, double Tolerance);
+void      cdecl VEC3scaleAndCut(LPWVEC3 r, LPVEC3 v, double d);
+void      cdecl VEC3cross(LPVEC3 r, LPVEC3 u, LPVEC3 v);
+void      cdecl VEC3saturate(LPVEC3 v);
+double    cdecl VEC3distance(LPVEC3 a, LPVEC3 b);
+double    cdecl VEC3length(LPVEC3 a);
+
+void      cdecl MAT3identity(LPMAT3 a);
+void      cdecl MAT3per(LPMAT3 r, LPMAT3 a, LPMAT3 b);
+void      cdecl MAT3perK(LPMAT3 r, LPMAT3 v, double d);
+int       cdecl MAT3inverse(LPMAT3 a, LPMAT3 b);
+LCMSBOOL  cdecl MAT3solve(LPVEC3 x, LPMAT3 a, LPVEC3 b);
+double    cdecl MAT3det(LPMAT3 m);
+void      cdecl MAT3eval(LPVEC3 r, LPMAT3 a, LPVEC3 v);
+void      cdecl MAT3toFix(LPWMAT3 r, LPMAT3 v);
+void      cdecl MAT3fromFix(LPMAT3 r, LPWMAT3 v);
+void      cdecl MAT3evalW(LPWVEC3 r, LPWMAT3 a, LPWVEC3 v);
+LCMSBOOL  cdecl MAT3isIdentity(LPWMAT3 a, double Tolerance);
+void      cdecl MAT3scaleAndCut(LPWMAT3 r, LPMAT3 v, double d);
 
 // Is a table linear?
 
@@ -1608,7 +1622,7 @@
 void    cdecl cmsCalcL16Params(int nSamples, LPL16PARAMS p);
 void    cdecl cmsCalcCLUT16Params(int nSamples, int InputChan, int OutputChan, LPL16PARAMS p);
 void    cdecl cmsCalcCLUT16ParamsEx(int nSamples, int InputChan, int OutputChan,
-                                            BOOL lUseTetrahedral, LPL16PARAMS p);
+                                            LCMSBOOL lUseTetrahedral, LPL16PARAMS p);
 
 WORD    cdecl cmsLinearInterpLUT16(WORD Value, WORD LutTable[], LPL16PARAMS p);
 Fixed32 cdecl cmsLinearInterpFixed(WORD Value1, WORD LutTable[], LPL16PARAMS p);
@@ -1692,18 +1706,18 @@
 
                // Gray axes fixup. Only on v2 8-bit Lab LUT
 
-               BOOL FixGrayAxes;
-
-
-                           // Parameters used for curve creation
-
-                           LCMSGAMMAPARAMS LCurvesSeed[4][MAXCHANNELS];
+               LCMSBOOL FixGrayAxes;
+
+
+               // Parameters used for curve creation
+
+               LCMSGAMMAPARAMS LCurvesSeed[4][MAXCHANNELS];
 
 
                }; // LUT, FAR* LPLUT;
 
 
-BOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nEntries);
+LCMSBOOL         cdecl _cmsSmoothEndpoints(LPWORD Table, int nEntries);
 
 
 // CRC of gamma tables
@@ -1721,7 +1735,7 @@
 
 void           cdecl cmsEndpointsOfSampledCurve(LPSAMPLEDCURVE p, double* Min, double* Max);
 void           cdecl cmsClampSampledCurve(LPSAMPLEDCURVE p, double Min, double Max);
-BOOL           cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
+LCMSBOOL       cdecl cmsSmoothSampledCurve(LPSAMPLEDCURVE Tab, double SmoothingLambda);
 void           cdecl cmsRescaleSampledCurve(LPSAMPLEDCURVE p, double Min, double Max, int nPoints);
 
 LPSAMPLEDCURVE cdecl cmsJoinSampledCurves(LPSAMPLEDCURVE X, LPSAMPLEDCURVE Y, int nResultingPoints);
@@ -1755,19 +1769,19 @@
 void        cdecl cmsFreeMatShaper(LPMATSHAPER MatShaper);
 void        cdecl cmsEvalMatShaper(LPMATSHAPER MatShaper, WORD In[], WORD Out[]);
 
-BOOL         cdecl cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile);
-
-LPMATSHAPER  cdecl cmsBuildInputMatrixShaper(cmsHPROFILE InputProfile);
-LPMATSHAPER  cdecl cmsBuildOutputMatrixShaper(cmsHPROFILE OutputProfile);
+LCMSBOOL    cdecl cmsReadICCMatrixRGB2XYZ(LPMAT3 r, cmsHPROFILE hProfile);
+
+LPMATSHAPER cdecl cmsBuildInputMatrixShaper(cmsHPROFILE InputProfile);
+LPMATSHAPER cdecl cmsBuildOutputMatrixShaper(cmsHPROFILE OutputProfile);
 
 
 
 // White Point & Primary chromas handling
-BOOL cdecl cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll);
-BOOL cdecl cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt);
-BOOL cdecl cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt);
-
-BOOL cdecl cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile);
+LCMSBOOL cdecl cmsAdaptationMatrix(LPMAT3 r, LPMAT3 ConeMatrix, LPcmsCIEXYZ FromIll, LPcmsCIEXYZ ToIll);
+LCMSBOOL cdecl cmsAdaptMatrixToD50(LPMAT3 r, LPcmsCIExyY SourceWhitePt);
+LCMSBOOL cdecl cmsAdaptMatrixFromD50(LPMAT3 r, LPcmsCIExyY DestWhitePt);
+
+LCMSBOOL cdecl cmsReadChromaticAdaptationMatrix(LPMAT3 r, cmsHPROFILE hProfile);
 
 // Inter-PCS conversion routines. They assume D50 as white point.
 void cdecl cmsXYZ2LabEncoded(WORD XYZ[3], WORD Lab[3]);
@@ -1782,7 +1796,7 @@
 LPcmsNAMEDCOLORLIST  cdecl cmsAllocNamedColorList(int n);
 int                  cdecl cmsReadICCnamedColorList(cmsHTRANSFORM xform, cmsHPROFILE hProfile, icTagSignature sig);
 void                 cdecl cmsFreeNamedColorList(LPcmsNAMEDCOLORLIST List);
-BOOL                 cdecl cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS]);
+LCMSBOOL             cdecl cmsAppendNamedColor(cmsHTRANSFORM xform, const char* Name, WORD PCS[3], WORD Colorant[MAXCHANNELS]);
 
 
 // I/O
@@ -1804,7 +1818,7 @@
                icColorSpaceSignature   PCS;
                icRenderingIntent       RenderingIntent;
                icUInt32Number          flags;
-                           icUInt32Number          attributes;
+               icUInt32Number          attributes;
                cmsCIEXYZ               Illuminant;
 
                // Additions for V4 profiles
@@ -1826,22 +1840,23 @@
 
                char                    PhysicalFile[MAX_PATH];
 
-               BOOL                    IsWrite;
-               BOOL                    SaveAs8Bits;
+               LCMSBOOL                IsWrite;
+               LCMSBOOL                SaveAs8Bits;
 
                struct tm               Created;
 
                // I/O handlers
 
-               size_t (* Read)(void *buffer, size_t size, size_t count, struct _lcms_iccprofile_struct* Icc);
-
-               BOOL   (* Seek)(struct _lcms_iccprofile_struct* Icc, size_t offset);
-               BOOL   (* Close)(struct _lcms_iccprofile_struct* Icc);
-               size_t (* Tell)(struct _lcms_iccprofile_struct* Icc);
+               size_t   (* Read)(void *buffer, size_t size, size_t count, struct _lcms_iccprofile_struct* Icc);
+
+               LCMSBOOL (* Seek)(struct _lcms_iccprofile_struct* Icc, size_t offset);
+               LCMSBOOL (* Close)(struct _lcms_iccprofile_struct* Icc);
+               size_t   (* Tell)(struct _lcms_iccprofile_struct* Icc);
+               LCMSBOOL  (* Grow)(struct _lcms_iccprofile_struct* Icc, size_t amount);
 
                // Writting
 
-               BOOL   (* Write)(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr);
+               LCMSBOOL (* Write)(struct _lcms_iccprofile_struct* Icc, size_t size, LPVOID Ptr);
 
                size_t UsedSpace;
 
@@ -1853,7 +1868,7 @@
 cmsHPROFILE cdecl _cmsCreateProfilePlaceholder(void);
 
 // Search into tag dictionary
-icInt32Number cdecl _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, BOOL lSignalError);
+icInt32Number cdecl _cmsSearchTag(LPLCMSICCPROFILE Profile, icTagSignature sig, LCMSBOOL lSignalError);
 
 // Search for a particular tag, replace if found or add new one else
 LPVOID _cmsInitTag(LPLCMSICCPROFILE Icc, icTagSignature sig, size_t size, const void* Init);
@@ -1869,6 +1884,7 @@
 
 // These macros unpack format specifiers into integers
 
+#define T_DITHER(s)           (((s)>>22)&1)
 #define T_COLORSPACE(s)       (((s)>>16)&31)
 #define T_SWAPFIRST(s)        (((s)>>14)&1)
 #define T_FLAVOR(s)           (((s)>>13)&1)
@@ -1965,7 +1981,7 @@
 
                     // Flag for transform involving v4 profiles
 
-                    BOOL lInputV4Lab, lOutputV4Lab;
+                    LCMSBOOL lInputV4Lab, lOutputV4Lab;
 
 
                     // 1-pixel cache
@@ -1975,7 +1991,7 @@
 
                     double AdaptationState; // Figure for v4 incomplete state of adaptation
 
-                                        LCMS_RWLOCK_T rwlock;
+                    LCMS_RWLOCK_T rwlock;
 
                    } _cmsTRANSFORM,FAR *_LPcmsTRANSFORM;
 
@@ -2012,7 +2028,7 @@
 
 // Clamping & Gamut handling
 
-BOOL cdecl   _cmsEndPointsBySpace(icColorSpaceSignature Space,
+LCMSBOOL cdecl   _cmsEndPointsBySpace(icColorSpaceSignature Space,
                             WORD **White, WORD **Black, int *nOutputs);
 
 WORD * cdecl _cmsWhiteBySpace(icColorSpaceSignature Space);
@@ -2041,7 +2057,7 @@
 LPLUT cdecl _cmsPrecalculateGamutCheck(cmsHTRANSFORM h);
 
 // Hot fixes bad profiles
-BOOL cdecl _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p);
+LCMSBOOL cdecl _cmsFixWhiteMisalignment(_LPcmsTRANSFORM p);
 
 // Marks LUT as 8 bit on input
 LPLUT cdecl _cmsBlessLUT8(LPLUT Lut);
@@ -2059,6 +2075,10 @@
 // Build a tone curve for K->K' if possible (only works on CMYK)
 LPGAMMATABLE _cmsBuildKToneCurve(cmsHTRANSFORM hCMYK2CMYK, int nPoints);
 
+// Validates a LUT
+LCMSBOOL cdecl _cmsValidateLUT(LPLUT NewLUT);
+
+
 // These are two VITAL macros, from converting between 8 and 16 bit
 // representation.
 
@@ -2076,3 +2096,4 @@
 #endif
 
 #endif
+
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -89,21 +89,24 @@
 
     /* load CK_DATE class */
     jDateClass = (*env)->FindClass(env, CLASS_DATE);
-    assert(jDateClass != 0);
+    if (jDateClass == NULL) { return NULL; }
 
     /* load CK_DATE constructor */
     jCtrId = (*env)->GetMethodID(env, jDateClass, "<init>", "([C[C[C)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jYear = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->year), 4);
+    if (jYear == NULL) { return NULL; }
     jMonth = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->month), 2);
+    if (jMonth == NULL) { return NULL; }
     jDay = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->day), 2);
+    if (jDay == NULL) { return NULL; }
 
     /* create new CK_DATE object */
     jDateObject =
       (*env)->NewObject(env, jDateClass, jCtrId, jYear, jMonth, jDay);
-    assert(jDateObject != 0);
+    if (jDateObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jDateClass);
@@ -131,11 +134,11 @@
 
     /* load CK_VERSION class */
     jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
-    assert(jVersionClass != 0);
+    if (jVersionClass == NULL) { return NULL; }
 
     /* load CK_VERSION constructor */
     jCtrId = (*env)->GetMethodID(env, jVersionClass, "<init>", "(II)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep both fields */
     jMajor = ckpVersion->major;
@@ -144,7 +147,7 @@
     /* create new CK_VERSION object */
     jVersionObject =
       (*env)->NewObject(env, jVersionClass, jCtrId, jMajor, jMinor);
-    assert(jVersionObject != 0);
+    if (jVersionObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jVersionClass);
@@ -171,11 +174,11 @@
 
     /* load CK_SESSION_INFO class */
     jSessionInfoClass = (*env)->FindClass(env, CLASS_SESSION_INFO);
-    assert(jSessionInfoClass != 0);
+    if (jSessionInfoClass == NULL) { return NULL; }
 
     /* load CK_SESSION_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jSessionInfoClass, "<init>", "(JJJJ)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jSlotID = ckULongToJLong(ckpSessionInfo->slotID);
@@ -187,7 +190,7 @@
     jSessionInfoObject =
       (*env)->NewObject(env, jSessionInfoClass, jCtrId, jSlotID, jState,
                         jFlags, jDeviceError);
-    assert(jSessionInfoObject != 0);
+    if (jSessionInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jSessionInfoClass);
@@ -211,20 +214,21 @@
     jobject jPValue = NULL;
 
     jAttributeClass = (*env)->FindClass(env, CLASS_ATTRIBUTE);
-    assert(jAttributeClass != 0);
+    if (jAttributeClass == NULL) { return NULL; }
 
     /* load CK_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jAttributeClass, "<init>", "(JLjava/lang/Object;)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep both fields */
     jType = ckULongToJLong(ckpAttribute->type);
     jPValue = ckAttributeValueToJObject(env, ckpAttribute);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     /* create new CK_ATTRIBUTE object */
     jAttributeObject =
       (*env)->NewObject(env, jAttributeClass, jCtrId, jType, jPValue);
-    assert(jAttributeObject != 0);
+    if (jAttributeObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jAttributeClass);
@@ -252,23 +256,27 @@
         return NULL;
     }
 
-    /* allocate memory for CK_VERSION pointer */
-    ckpVersion = (CK_VERSION_PTR) malloc(sizeof(CK_VERSION));
-
     /* get CK_VERSION class */
     jVersionClass = (*env)->GetObjectClass(env, jVersion);
-    assert(jVersionClass != 0);
+    if (jVersionClass == NULL) { return NULL; }
 
     /* get Major */
     jFieldID = (*env)->GetFieldID(env, jVersionClass, "major", "B");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jMajor = (*env)->GetByteField(env, jVersion, jFieldID);
-    ckpVersion->major = jByteToCKByte(jMajor);
 
     /* get Minor */
     jFieldID = (*env)->GetFieldID(env, jVersionClass, "minor", "B");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jMinor = (*env)->GetByteField(env, jVersion, jFieldID);
+
+    /* allocate memory for CK_VERSION pointer */
+    ckpVersion = (CK_VERSION_PTR) malloc(sizeof(CK_VERSION));
+    if (ckpVersion == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
+    ckpVersion->major = jByteToCKByte(jMajor);
     ckpVersion->minor = jByteToCKByte(jMinor);
 
     return ckpVersion ;
@@ -292,18 +300,36 @@
     jchar *jTempChars;
     CK_ULONG i;
 
-    /* allocate memory for CK_DATE pointer */
-    ckpDate = (CK_DATE *) malloc(sizeof(CK_DATE));
+    if (jDate == NULL) {
+        return NULL;
+    }
 
     /* get CK_DATE class */
     jDateClass = (*env)->FindClass(env, CLASS_DATE);
-    assert(jDateClass != 0);
+    if (jDateClass == NULL) { return NULL; }
 
     /* get Year */
     jFieldID = (*env)->GetFieldID(env, jDateClass, "year", "[C");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jYear = (*env)->GetObjectField(env, jDate, jFieldID);
 
+    /* get Month */
+    jFieldID = (*env)->GetFieldID(env, jDateClass, "month", "[C");
+    if (jFieldID == NULL) { return NULL; }
+    jMonth = (*env)->GetObjectField(env, jDate, jFieldID);
+
+    /* get Day */
+    jFieldID = (*env)->GetFieldID(env, jDateClass, "day", "[C");
+    if (jFieldID == NULL) { return NULL; }
+    jDay = (*env)->GetObjectField(env, jDate, jFieldID);
+
+    /* allocate memory for CK_DATE pointer */
+    ckpDate = (CK_DATE *) malloc(sizeof(CK_DATE));
+    if (ckpDate == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
+
     if (jYear == NULL) {
         ckpDate->year[0] = 0;
         ckpDate->year[1] = 0;
@@ -312,43 +338,66 @@
     } else {
         ckLength = (*env)->GetArrayLength(env, jYear);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jYear, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->year[i] = jCharToCKChar(jTempChars[i]);
         }
         free(jTempChars);
     }
 
-    /* get Month */
-    jFieldID = (*env)->GetFieldID(env, jDateClass, "month", "[C");
-    assert(jFieldID != 0);
-    jMonth = (*env)->GetObjectField(env, jDate, jFieldID);
-
     if (jMonth == NULL) {
         ckpDate->month[0] = 0;
         ckpDate->month[1] = 0;
     } else {
         ckLength = (*env)->GetArrayLength(env, jMonth);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jMonth, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->month[i] = jCharToCKChar(jTempChars[i]);
         }
         free(jTempChars);
     }
 
-    /* get Day */
-    jFieldID = (*env)->GetFieldID(env, jDateClass, "day", "[C");
-    assert(jFieldID != 0);
-    jDay = (*env)->GetObjectField(env, jDate, jFieldID);
-
     if (jDay == NULL) {
         ckpDate->day[0] = 0;
         ckpDate->day[1] = 0;
     } else {
         ckLength = (*env)->GetArrayLength(env, jDay);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jDay, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->day[i] = jCharToCKChar(jTempChars[i]);
         }
@@ -374,23 +423,25 @@
     jlong jType;
     jobject jPValue;
 
+    // TBD: what if jAttribute == NULL?!
+
     TRACE0("\nDEBUG: jAttributeToCKAttribute");
     /* get CK_ATTRIBUTE class */
     TRACE0(", getting attribute object class");
     jAttributeClass = (*env)->GetObjectClass(env, jAttribute);
-    assert(jAttributeClass != 0);
+    if (jAttributeClass == NULL) { return ckAttribute; }
 
     /* get type */
     TRACE0(", getting type field");
     jFieldID = (*env)->GetFieldID(env, jAttributeClass, "type", "J");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return ckAttribute; }
     jType = (*env)->GetLongField(env, jAttribute, jFieldID);
     TRACE1(", type=0x%X", jType);
 
     /* get pValue */
     TRACE0(", getting pValue field");
     jFieldID = (*env)->GetFieldID(env, jAttributeClass, "pValue", "Ljava/lang/Object;");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return ckAttribute; }
     jPValue = (*env)->GetObjectField(env, jAttribute, jFieldID);
     TRACE1(", pValue=%p", jPValue);
 
@@ -417,36 +468,50 @@
 {
     // XXX don't return structs
     // XXX prefetch class and field ids
-    jclass jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    jclass jSsl3MasterKeyDeriveParamsClass;
     CK_SSL3_MASTER_KEY_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jobject jObject;
     jclass jSsl3RandomDataClass;
-    jobject jRandomInfo;
+    jobject jRandomInfo, jRIClientRandom, jRIServerRandom, jVersion;
 
     /* get RandomInfo */
-    jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3MasterKeyDeriveParamsClass, "RandomInfo", "Lsun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jRandomInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pClientRandom and ulClientRandomLength out of RandomInfo */
+    jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    if (jSsl3RandomDataClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pClientRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIClientRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pServerRandom and ulServerRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pServerRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIServerRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pVersion */
     fieldID = (*env)->GetFieldID(env, jSsl3MasterKeyDeriveParamsClass, "pVersion",  "Lsun/security/pkcs11/wrapper/CK_VERSION;");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    ckParam.pVersion = jVersionToCKVersionPtr(env, jObject);
+    if (fieldID == NULL) { return ckParam; }
+    jVersion = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.pVersion = jVersionToCKVersionPtr(env, jVersion);
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jRIClientRandom, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pVersion);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jRIServerRandom, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pVersion);
+        free(ckParam.RandomInfo.pClientRandom);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -457,27 +522,52 @@
  */
 CK_TLS_PRF_PARAMS jTlsPrfParamsToCKTlsPrfParam(JNIEnv *env, jobject jParam)
 {
-    jclass jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    jclass jTlsPrfParamsClass;
     CK_TLS_PRF_PARAMS ckParam;
     jfieldID fieldID;
-    jobject jObject;
+    jobject jSeed, jLabel, jOutput;
+
+    // TBD: what if jParam == NULL?!
 
+    /* get pSeed */
+    jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    if (jTlsPrfParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pSeed", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSeed), &(ckParam.ulSeedLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSeed = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* get pLabel */
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pLabel", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pLabel), &(ckParam.ulLabelLen));
+    if (fieldID == NULL) { return ckParam; }
+    jLabel = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get pOutput */
+    fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pOutput", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jOutput = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* populate java values */
+    jByteArrayToCKByteArray(env, jSeed, &(ckParam.pSeed), &(ckParam.ulSeedLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jLabel, &(ckParam.pLabel), &(ckParam.ulLabelLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSeed);
+        return ckParam;
+    }
     ckParam.pulOutputLen = malloc(sizeof(CK_ULONG));
-
-    fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pOutput", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOutput), ckParam.pulOutputLen);
+    if (ckParam.pulOutputLen == NULL) {
+        free(ckParam.pSeed);
+        free(ckParam.pLabel);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jOutput, &(ckParam.pOutput), ckParam.pulOutputLen);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSeed);
+        free(ckParam.pLabel);
+        free(ckParam.pulOutputLen);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -493,68 +583,91 @@
 {
     // XXX don't return structs
     // XXX prefetch class and field ids
-    jclass jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    jclass jSsl3KeyMatParamsClass, jSsl3RandomDataClass, jSsl3KeyMatOutClass;
     CK_SSL3_KEY_MAT_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jboolean jBoolean;
-    jobject jObject;
-    jobject jRandomInfo;
-    jobject jReturnedKeyMaterial;
-    jclass jSsl3RandomDataClass;
-    jclass jSsl3KeyMatOutClass;
+    jlong jMacSizeInBits, jKeySizeInBits, jIVSizeInBits;
+    jboolean jIsExport;
+    jobject jRandomInfo, jRIClientRandom, jRIServerRandom;
+    jobject jReturnedKeyMaterial, jRMIvClient, jRMIvServer;
     CK_ULONG ckTemp;
 
     /* get ulMacSizeInBits */
+    jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    if (jSsl3KeyMatParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulMacSizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulMacSizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMacSizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulKeySizeInBits */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulKeySizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulKeySizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKeySizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulIVSizeInBits */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulIVSizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulIVSizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIVSizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get bIsExport */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "bIsExport", "Z");
-    assert(fieldID != 0);
-    jBoolean = (*env)->GetBooleanField(env, jParam, fieldID);
-    ckParam.bIsExport = jBooleanToCKBBool(jBoolean);
+    if (fieldID == NULL) { return ckParam; }
+    jIsExport = (*env)->GetBooleanField(env, jParam, fieldID);
 
     /* get RandomInfo */
     jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    if (jSsl3RandomDataClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "RandomInfo",  "Lsun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jRandomInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pClientRandom and ulClientRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pClientRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIClientRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pServerRandom and ulServerRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pServerRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIServerRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pReturnedKeyMaterial */
     jSsl3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+    if (jSsl3KeyMatOutClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "pReturnedKeyMaterial",  "Lsun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jReturnedKeyMaterial = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* get pIVClient out of pReturnedKeyMaterial */
+    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVClient", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jRMIvClient = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
+
+    /* get pIVServer out of pReturnedKeyMaterial */
+    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVServer", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jRMIvServer = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
+
+    /* populate java values */
+    ckParam.ulMacSizeInBits = jLongToCKULong(jMacSizeInBits);
+    ckParam.ulKeySizeInBits = jLongToCKULong(jKeySizeInBits);
+    ckParam.ulIVSizeInBits = jLongToCKULong(jIVSizeInBits);
+    ckParam.bIsExport = jBooleanToCKBBool(jIsExport);
+    jByteArrayToCKByteArray(env, jRIClientRandom, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jRIServerRandom, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        return ckParam;
+    }
     /* allocate memory for pRetrunedKeyMaterial */
     ckParam.pReturnedKeyMaterial = (CK_SSL3_KEY_MAT_OUT_PTR) malloc(sizeof(CK_SSL3_KEY_MAT_OUT));
+    if (ckParam.pReturnedKeyMaterial == NULL) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return ckParam;
+    }
 
     // the handles are output params only, no need to fetch them from Java
     ckParam.pReturnedKeyMaterial->hClientMacSecret = 0;
@@ -562,17 +675,21 @@
     ckParam.pReturnedKeyMaterial->hClientKey = 0;
     ckParam.pReturnedKeyMaterial->hServerKey = 0;
 
-    /* get pIVClient out of pReturnedKeyMaterial */
-    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVClient", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pReturnedKeyMaterial->pIVClient), &ckTemp);
-
-    /* get pIVServer out of pReturnedKeyMaterial */
-    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVServer", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pReturnedKeyMaterial->pIVServer), &ckTemp);
+    jByteArrayToCKByteArray(env, jRMIvClient, &(ckParam.pReturnedKeyMaterial->pIVClient), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        free(ckParam.pReturnedKeyMaterial);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jRMIvServer, &(ckParam.pReturnedKeyMaterial->pIVServer), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        free(ckParam.pReturnedKeyMaterial);
+        free(ckParam.pReturnedKeyMaterial->pIVClient);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -811,7 +928,7 @@
         *ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
         *ckpLength = sizeof(CK_ULONG);
     } else {
-        /* printf("slow path jMechanismParameterToCKMechanismParameter\n"); */
+        TRACE0("\nSLOW PATH jMechanismParameterToCKMechanismParameter\n");
         jMechanismParameterToCKMechanismParameterSlow(env, jParam, ckpParamPtr, ckpLength);
     }
 }
@@ -819,40 +936,24 @@
 void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength)
 {
     /* get all Java mechanism parameter classes */
-    jclass jVersionClass    = (*env)->FindClass(env, CLASS_VERSION);
-    jclass jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
-    jclass jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    jclass jVersionClass, jSsl3MasterKeyDeriveParamsClass, jSsl3KeyMatParamsClass;
+    jclass jTlsPrfParamsClass, jRsaPkcsOaepParamsClass, jPbeParamsClass;
+    jclass jPkcs5Pbkd2ParamsClass, jRsaPkcsPssParamsClass;
+    jclass jEcdh1DeriveParamsClass, jEcdh2DeriveParamsClass;
+    jclass jX942Dh1DeriveParamsClass, jX942Dh2DeriveParamsClass;
 
-    jclass jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
-    jclass jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
-    jclass jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
-    jclass jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
-    jclass jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
-
-    jclass jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-    jclass jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
-    jclass jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
-
+    /* get all Java mechanism parameter classes */
     TRACE0("\nDEBUG: jMechanismParameterToCKMechanismParameter");
 
-    /* first check the most common cases */
-/*
-    if (jParam == NULL) {
-        *ckpParamPtr = NULL;
-        *ckpLength = 0;
-    } else if ((*env)->IsInstanceOf(env, jParam, jByteArrayClass)) {
-        jByteArrayToCKByteArray(env, jParam, (CK_BYTE_PTR *)ckpParamPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jParam, jLongClass)) {
-        *ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
-        *ckpLength = sizeof(CK_ULONG);
-    } else if ((*env)->IsInstanceOf(env, jParam, jVersionClass)) {
-*/
+    /* most common cases, i.e. NULL/byte[]/long, are already handled by
+     * jMechanismParameterToCKMechanismParameter before calling this method.
+     */
+    jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+    if (jVersionClass == NULL) { return; }
     if ((*env)->IsInstanceOf(env, jParam, jVersionClass)) {
         /*
          * CK_VERSION used by CKM_SSL3_PRE_MASTER_KEY_GEN
          */
-
         CK_VERSION_PTR ckpParam;
 
         /* convert jParameter to CKParameter */
@@ -861,190 +962,311 @@
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_VERSION);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jSsl3MasterKeyDeriveParamsClass)) {
+    jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jSsl3MasterKeyDeriveParamsClass)) {
         /*
          * CK_SSL3_MASTER_KEY_DERIVE_PARAMS
          */
-
         CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR) malloc(sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jSsl3KeyMatParamsClass)) {
+    jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    if (jSsl3KeyMatParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jSsl3KeyMatParamsClass)) {
         /*
          * CK_SSL3_KEY_MAT_PARAMS
          */
-
         CK_SSL3_KEY_MAT_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_SSL3_KEY_MAT_PARAMS_PTR) malloc(sizeof(CK_SSL3_KEY_MAT_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jSsl3KeyMatParamToCKSsl3KeyMatParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_SSL3_KEY_MAT_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jTlsPrfParamsClass)) {
-        //
-        // CK_TLS_PRF_PARAMS
-        //
-
+    jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    if (jTlsPrfParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jTlsPrfParamsClass)) {
+        /*
+         * CK_TLS_PRF_PARAMS
+         */
         CK_TLS_PRF_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_TLS_PRF_PARAMS_PTR) malloc(sizeof(CK_TLS_PRF_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
-        // convert jParameter to CKParameter
+        /* convert jParameter to CKParameter */
         *ckpParam = jTlsPrfParamsToCKTlsPrfParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
-        // get length and pointer of parameter
+        /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_TLS_PRF_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
+    jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    if (jRsaPkcsOaepParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
         /*
          * CK_RSA_PKCS_OAEP_PARAMS
          */
-
         CK_RSA_PKCS_OAEP_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_RSA_PKCS_OAEP_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_OAEP_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jRsaPkcsOaepParamToCKRsaPkcsOaepParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_RSA_PKCS_OAEP_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jPbeParamsClass)) {
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jPbeParamsClass)) {
         /*
          * CK_PBE_PARAMS
          */
-
         CK_PBE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_PBE_PARAMS_PTR) malloc(sizeof(CK_PBE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jPbeParamToCKPbeParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_PBE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jPkcs5Pbkd2ParamsClass)) {
+    jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    if (jPkcs5Pbkd2ParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jPkcs5Pbkd2ParamsClass)) {
         /*
          * CK_PKCS5_PBKD2_PARAMS
          */
-
         CK_PKCS5_PBKD2_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_PKCS5_PBKD2_PARAMS_PTR) malloc(sizeof(CK_PKCS5_PBKD2_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_PKCS5_PBKD2_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsPssParamsClass)) {
+    jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    if (jRsaPkcsPssParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsPssParamsClass)) {
         /*
          * CK_RSA_PKCS_PSS_PARAMS
          */
-
         CK_RSA_PKCS_PSS_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_RSA_PKCS_PSS_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_PSS_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jRsaPkcsPssParamToCKRsaPkcsPssParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_RSA_PKCS_PSS_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jEcdh1DeriveParamsClass)) {
+    jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    if (jEcdh1DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jEcdh1DeriveParamsClass)) {
         /*
          * CK_ECDH1_DERIVE_PARAMS
          */
-
         CK_ECDH1_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_ECDH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH1_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jEcdh1DeriveParamToCKEcdh1DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_ECDH1_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jEcdh2DeriveParamsClass)) {
+    jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    if (jEcdh2DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jEcdh2DeriveParamsClass)) {
         /*
          * CK_ECDH2_DERIVE_PARAMS
          */
-
         CK_ECDH2_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_ECDH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH2_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jEcdh2DeriveParamToCKEcdh2DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_ECDH2_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jX942Dh1DeriveParamsClass)) {
+    jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    if (jX942Dh1DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jX942Dh1DeriveParamsClass)) {
         /*
          * CK_X9_42_DH1_DERIVE_PARAMS
          */
-
         CK_X9_42_DH1_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_X9_42_DH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jX942Dh1DeriveParamToCKX942Dh1DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_X9_42_DH1_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jX942Dh2DeriveParamsClass)) {
+    jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    if (jX942Dh2DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jX942Dh2DeriveParamsClass)) {
         /*
          * CK_X9_42_DH2_DERIVE_PARAMS
          */
-
         CK_X9_42_DH2_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_X9_42_DH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jX942Dh2DeriveParamToCKX942Dh2DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_X9_42_DH2_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else {
-        /* if everything faild up to here */
-        /* try if the parameter is a primitive Java type */
-        jObjectToPrimitiveCKObjectPtrPtr(env, jParam, ckpParamPtr, ckpLength);
-        /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
-        /* *ckpLength = 1; */
-    }
+    /* if everything faild up to here */
+    /* try if the parameter is a primitive Java type */
+    jObjectToPrimitiveCKObjectPtrPtr(env, jParam, ckpParamPtr, ckpLength);
+    /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
+    /* *ckpLength = 1; */
 
     TRACE0("FINISHED\n");
 }
@@ -1061,36 +1283,41 @@
  */
 CK_RSA_PKCS_OAEP_PARAMS jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam)
 {
-    jclass jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    jclass jRsaPkcsOaepParamsClass;
     CK_RSA_PKCS_OAEP_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jHashAlg, jMgf, jSource;
+    jobject jSourceData;
     CK_BYTE_PTR ckpByte;
 
     /* get hashAlg */
+    jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    if (jRsaPkcsOaepParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "hashAlg", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hashAlg = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "mgf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.mgf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get source */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "source", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.source = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sourceData and sourceDataLength */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "pSourceData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &ckpByte, &(ckParam.ulSourceDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSourceData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.hashAlg = jLongToCKULong(jHashAlg);
+    ckParam.mgf = jLongToCKULong(jMgf);
+    ckParam.source = jLongToCKULong(jSource);
+    jByteArrayToCKByteArray(env, jSourceData, & ckpByte, &(ckParam.ulSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
     ckParam.pSourceData = (CK_VOID_PTR) ckpByte;
 
     return ckParam ;
@@ -1105,36 +1332,50 @@
  */
 CK_PBE_PARAMS jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam)
 {
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    jclass jPbeParamsClass;
     CK_PBE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jIteration;
+    jobject jInitVector, jPassword, jSalt;
     CK_ULONG ckTemp;
 
     /* get pInitVector */
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pInitVector", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pInitVector), &ckTemp);
+    if (fieldID == NULL) { return ckParam; }
+    jInitVector = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPassword and ulPasswordLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pPassword", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pPassword), &(ckParam.ulPasswordLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPassword = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pSalt and ulSaltLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pSalt", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pSalt), &(ckParam.ulSaltLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSalt = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulIteration */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "ulIteration", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulIteration = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIteration = (*env)->GetLongField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.ulIteration = jLongToCKULong(jIteration);
+    jCharArrayToCKCharArray(env, jInitVector, &(ckParam.pInitVector), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jCharArrayToCKCharArray(env, jPassword, &(ckParam.pPassword), &(ckParam.ulPasswordLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pInitVector);
+        return ckParam;
+    }
+    jCharArrayToCKCharArray(env, jSalt, &(ckParam.pSalt), &(ckParam.ulSaltLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pInitVector);
+        free(ckParam.pPassword);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1147,8 +1388,7 @@
  */
 void copyBackPBEInitializationVector(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-    jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    jclass jMechanismClass, jPbeParamsClass;
     CK_PBE_PARAMS *ckParam;
     jfieldID fieldID;
     CK_MECHANISM_TYPE ckMechanismType;
@@ -1161,8 +1401,10 @@
     jchar* jInitVectorChars;
 
     /* get mechanism */
+    jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (jMechanismClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
     if (ckMechanismType != ckMechanism->mechanism) {
@@ -1170,21 +1412,25 @@
         return;
     }
 
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return; }
     ckParam = (CK_PBE_PARAMS *) ckMechanism->pParameter;
     if (ckParam != NULL_PTR) {
         initVector = ckParam->pInitVector;
         if (initVector != NULL_PTR) {
             /* get pParameter */
             fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-            assert(fieldID != 0);
+            if (fieldID == NULL) { return; }
             jParameter = (*env)->GetObjectField(env, jMechanism, fieldID);
             fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pInitVektor", "[C");
-            assert(fieldID != 0);
+            if (fieldID == NULL) { return; }
             jInitVector = (*env)->GetObjectField(env, jParameter, fieldID);
 
             if (jInitVector != NULL) {
                 jInitVectorLength = (*env)->GetArrayLength(env, jInitVector);
                 jInitVectorChars = (*env)->GetCharArrayElements(env, jInitVector, NULL);
+                if (jInitVectorChars == NULL) { return; }
+
                 /* copy the chars to the Java buffer */
                 for (i=0; i < jInitVectorLength; i++) {
                     jInitVectorChars[i] = ckCharToJChar(initVector[i]);
@@ -1205,41 +1451,50 @@
  */
 CK_PKCS5_PBKD2_PARAMS jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam)
 {
-    jclass jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    jclass jPkcs5Pbkd2ParamsClass;
     CK_PKCS5_PBKD2_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jSaltSource, jIteration, jPrf;
+    jobject jSaltSourceData, jPrfData;
 
     /* get saltSource */
+    jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    if (jPkcs5Pbkd2ParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "saltSource", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.saltSource = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSaltSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSaltSourceData */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pSaltSourceData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR *) &(ckParam.pSaltSourceData), &(ckParam.ulSaltSourceDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSaltSourceData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get iterations */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "iterations", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.iterations = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIteration = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get prf */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "prf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.prf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPrfData and ulPrfDataLength in byte */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pPrfData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR *) &(ckParam.pPrfData), &(ckParam.ulPrfDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPrfData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.saltSource = jLongToCKULong(jSaltSource);
+    jByteArrayToCKByteArray(env, jSaltSourceData, (CK_BYTE_PTR *) &(ckParam.pSaltSourceData), &(ckParam.ulSaltSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    ckParam.iterations = jLongToCKULong(jIteration);
+    ckParam.prf = jLongToCKULong(jPrf);
+    jByteArrayToCKByteArray(env, jPrfData, (CK_BYTE_PTR *) &(ckParam.pPrfData), &(ckParam.ulPrfDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSaltSourceData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1253,28 +1508,32 @@
  */
 CK_RSA_PKCS_PSS_PARAMS jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam)
 {
-    jclass jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    jclass jRsaPkcsPssParamsClass;
     CK_RSA_PKCS_PSS_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
+    jlong jHashAlg, jMgf, jSLen;
 
     /* get hashAlg */
+    jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    if (jRsaPkcsPssParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "hashAlg", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hashAlg = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "mgf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.mgf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sLen */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "sLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.sLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSLen = (*env)->GetLongField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.hashAlg = jLongToCKULong(jHashAlg);
+    ckParam.mgf = jLongToCKULong(jMgf);
+    ckParam.sLen = jLongToCKULong(jSLen);
 
     return ckParam ;
 }
@@ -1288,29 +1547,39 @@
  */
 CK_ECDH1_DERIVE_PARAMS jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    jclass jEcdh1DeriveParamsClass;
     CK_ECDH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jLong;
-    jobject jObject;
+    jobject jSharedData, jPublicData;
 
     /* get kdf */
+    jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    if (jEcdh1DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jLong = (*env)->GetLongField(env, jParam, fieldID);
     ckParam.kdf = jLongToCKULong(jLong);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pSharedData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jLong);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1324,48 +1593,61 @@
  */
 CK_ECDH2_DERIVE_PARAMS jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    jclass jEcdh2DeriveParamsClass;
     CK_ECDH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf, jPrivateDataLen, jPrivateData;
+    jobject jSharedData, jPublicData, jPublicData2;
 
     /* get kdf */
+    jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    if (jEcdh2DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pSharedData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulPrivateDataLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "hPrivateData", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hPrivateData = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData2", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        return ckParam;
+    }
+    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        free(ckParam.pPublicData);
+        return ckParam;
+    }
     return ckParam ;
 }
 
@@ -1378,29 +1660,38 @@
  */
 CK_X9_42_DH1_DERIVE_PARAMS jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    jclass jX942Dh1DeriveParamsClass;
     CK_X9_42_DH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf;
+    jobject jOtherInfo, jPublicData;
 
     /* get kdf */
+    jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    if (jX942Dh1DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pOtherInfo", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if (fieldID == NULL) { return ckParam; }
+    jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1414,47 +1705,61 @@
  */
 CK_X9_42_DH2_DERIVE_PARAMS jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    jclass jX942Dh2DeriveParamsClass;
     CK_X9_42_DH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf, jPrivateDataLen, jPrivateData;
+    jobject jOtherInfo, jPublicData, jPublicData2;
 
     /* get kdf */
+    jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    if (jX942Dh2DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pOtherInfo", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if (fieldID == NULL) { return ckParam; }
+    jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulPrivateDataLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "hPrivateData", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hPrivateData = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData2", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        return ckParam;
+    }
+    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        free(ckParam.pPublicData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -81,6 +81,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, &ckMechanism,
                                         ckKeyHandle);
@@ -126,14 +127,29 @@
 
     if (jInLen > MAX_STACK_BUFFER_LEN) {
       inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+      if (inBufP == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       inBufP = IBUF;
     }
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+      if (inBufP != IBUF) { free(inBufP); }
+      return 0;
+    }
 
     ckEncryptedPartLen = jOutLen;
     if (jOutLen > MAX_STACK_BUFFER_LEN) {
       outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+      if (outBufP == NULL) {
+        if (inBufP != IBUF) {
+          free(inBufP);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       outBufP = OBUF;
     }
@@ -193,10 +209,18 @@
     } else {
       if (jInLen > MAX_STACK_BUFFER_LEN) {
         inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         inBufP = IBUF;
       }
       (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+      if ((*env)->ExceptionCheck(env)) {
+        if (directIn == 0 && inBufP != IBUF) { free(inBufP); }
+        return 0;
+      }
     }
 
     ckEncryptedPartLen = jOutLen;
@@ -205,6 +229,13 @@
     } else {
       if (jOutLen > MAX_STACK_BUFFER_LEN) {
         outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+        if (outBufP == NULL) {
+          if (directIn == 0 && inBufP != IBUF) {
+            free(inBufP);
+          }
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         outBufP = OBUF;
       }
@@ -317,6 +348,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, &ckMechanism,
                                         ckKeyHandle);
@@ -362,14 +394,29 @@
 
     if (jInLen > MAX_STACK_BUFFER_LEN) {
       inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+      if (inBufP == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       inBufP = IBUF;
     }
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+      if (inBufP != IBUF) { free(inBufP); }
+      return 0;
+    }
 
     ckPartLen = jOutLen;
     if (jOutLen > MAX_STACK_BUFFER_LEN) {
       outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+      if (outBufP == NULL) {
+        if (inBufP != IBUF) {
+          free(inBufP);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       outBufP = OBUF;
     }
@@ -429,10 +476,18 @@
     } else {
       if (jInLen > MAX_STACK_BUFFER_LEN) {
         inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         inBufP = IBUF;
       }
       (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+      if ((*env)->ExceptionCheck(env)) {
+        if (directIn == 0 && inBufP != IBUF) { free(inBufP); }
+        return 0;
+      }
     }
 
     ckDecryptedPartLen = jOutLen;
@@ -441,6 +496,13 @@
     } else {
       if (jOutLen > MAX_STACK_BUFFER_LEN) {
         outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+        if (outBufP == NULL) {
+          if (directIn == 0 && inBufP != IBUF) {
+            free(inBufP);
+          }
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+      }
       } else {
         outBufP = OBUF;
       }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -75,6 +75,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
 
@@ -82,7 +83,7 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -114,6 +115,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0; }
 
     rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
 
@@ -121,29 +123,32 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
 
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         bufP = BUF;
     } else {
         /* always use single part op, even for large data */
-        bufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)bufP);
-    rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-        if (bufP != BUF) {
-            free(bufP);
-        }
+    if ((*env)->ExceptionCheck(env)) {
+        if (bufP != BUF) { free(bufP); }
         return 0;
     }
 
-    (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
+    rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
+    }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
+
     return ckDigestLength;
 }
 #endif
@@ -183,17 +188,23 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
         rv = (*ckpFunctions->C_DigestUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) {
-                free(bufP);
-            }
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+            if (bufP != BUF) { free(bufP); }
             return;
         }
         jInOfs += chunkLen;
@@ -229,7 +240,7 @@
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_DigestKey)(ckSessionHandle, ckKeyHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -257,10 +268,9 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_DigestFinal)(ckSessionHandle, BUF, &ckDigestLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0 ; }
-
-    (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)BUF);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)BUF);
+    }
     return ckDigestLength;
 }
 #endif
@@ -288,12 +298,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jSeed, &ckpSeed, &ckSeedLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_SeedRandom)(ckSessionHandle, ckpSeed, ckSeedLength);
 
     free(ckpSeed);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -322,6 +333,7 @@
 
     jRandomBufferLength = (*env)->GetArrayLength(env, jRandomData);
     jRandomBuffer = (*env)->GetByteArrayElements(env, jRandomData, NULL);
+    if (jRandomBuffer == NULL) { return; }
 
     rv = (*ckpFunctions->C_GenerateRandom)(ckSessionHandle,
                                          (CK_BYTE_PTR) jRandomBuffer,
@@ -330,6 +342,6 @@
     /* copy back generated bytes */
     (*env)->ReleaseByteArrayElements(env, jRandomData, jRandomBuffer, 0);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -73,7 +73,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart = NULL_PTR, ckpEncryptedPart;
     CK_ULONG ckPartLength, ckEncryptedPartLength = 0;
-    jbyteArray jEncryptedPart;
+    jbyteArray jEncryptedPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -81,20 +81,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jPart, &ckpPart, &ckPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DigestEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, NULL_PTR, &ckEncryptedPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpPart);
+        return NULL;
+    }
 
     ckpEncryptedPart = (CK_BYTE_PTR) malloc(ckEncryptedPartLength * sizeof(CK_BYTE));
+    if (ckpEncryptedPart == NULL) {
+        free(ckpPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DigestEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, ckpEncryptedPart, &ckEncryptedPartLength);
-
-    jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    }
     free(ckpPart);
     free(ckpEncryptedPart);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jEncryptedPart ;
 }
 #endif
@@ -117,7 +125,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart, ckpEncryptedPart = NULL_PTR;
     CK_ULONG ckPartLength = 0, ckEncryptedPartLength;
-    jbyteArray jPart;
+    jbyteArray jPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -125,19 +133,27 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jEncryptedPart, &ckpEncryptedPart, &ckEncryptedPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DecryptDigestUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, NULL_PTR, &ckPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpEncryptedPart);
+        return NULL;
+    }
 
     ckpPart = (CK_BYTE_PTR) malloc(ckPartLength * sizeof(CK_BYTE));
+    if (ckpPart == NULL) {
+        free(ckpEncryptedPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DecryptDigestUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, ckpPart, &ckPartLength);
-
-    jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    }
+    free(ckpEncryptedPart);
     free(ckpPart);
-    free(ckpEncryptedPart);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     return jPart ;
 }
@@ -161,7 +177,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart = NULL_PTR, ckpEncryptedPart;
     CK_ULONG ckPartLength, ckEncryptedPartLength = 0;
-    jbyteArray jEncryptedPart;
+    jbyteArray jEncryptedPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -169,20 +185,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jPart, &ckpPart, &ckPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_SignEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, NULL_PTR, &ckEncryptedPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpPart);
+        return NULL;
+    }
 
     ckpEncryptedPart = (CK_BYTE_PTR) malloc(ckEncryptedPartLength * sizeof(CK_BYTE));
+    if (ckpEncryptedPart == NULL) {
+        free(ckpPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_SignEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, ckpEncryptedPart, &ckEncryptedPartLength);
-
-    jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    }
     free(ckpPart);
     free(ckpEncryptedPart);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jEncryptedPart ;
 }
 #endif
@@ -205,7 +229,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart, ckpEncryptedPart = NULL_PTR;
     CK_ULONG ckPartLength = 0, ckEncryptedPartLength;
-    jbyteArray jPart;
+    jbyteArray jPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -213,19 +237,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jEncryptedPart, &ckpEncryptedPart, &ckEncryptedPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DecryptVerifyUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, NULL_PTR, &ckPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpEncryptedPart);
+        return NULL;
+    }
 
     ckpPart = (CK_BYTE_PTR) malloc(ckPartLength * sizeof(CK_BYTE));
+    if (ckpPart == NULL) {
+        free(ckpEncryptedPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DecryptVerifyUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, ckpPart, &ckPartLength);
 
-    jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
-    free(ckpPart);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    }
     free(ckpEncryptedPart);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    free(ckpPart);
 
     return jPart ;
 }
@@ -252,7 +285,7 @@
 
     /* C_GetFunctionStatus should always return CKR_FUNCTION_NOT_PARALLEL */
     rv = (*ckpFunctions->C_GetFunctionStatus)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -277,6 +310,6 @@
 
     /* C_GetFunctionStatus should always return CKR_FUNCTION_NOT_PARALLEL */
     rv = (*ckpFunctions->C_CancelFunction)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -102,6 +102,7 @@
 
 jclass fetchClass(JNIEnv *env, const char *name) {
     jclass tmpClass = (*env)->FindClass(env, name);
+    if (tmpClass == NULL) { return NULL; }
     return (*env)->NewGlobalRef(env, tmpClass);
 }
 
@@ -110,14 +111,18 @@
 
     /* PKCS11 */
     pNativeDataID = (*env)->GetFieldID(env, thisClass, "pNativeData", "J");
+    if (pNativeDataID == NULL) { return; }
 
     /* CK_MECHANISM */
     tmpClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (tmpClass == NULL) { return; }
     mech_mechanismID = (*env)->GetFieldID(env, tmpClass, "mechanism", "J");
+    if (mech_mechanismID == NULL) { return; }
     mech_pParameterID = (*env)->GetFieldID(env, tmpClass, "pParameter",
                                            "Ljava/lang/Object;");
-
+    if (mech_pParameterID == NULL) { return; }
     jByteArrayClass = fetchClass(env, "[B");
+    if (jByteArrayClass == NULL) { return; }
     jLongClass = fetchClass(env, "java/lang/Long");
 }
 
@@ -252,10 +257,9 @@
     if (ckpFunctions == NULL) { return NULL; }
 
     rv = (*ckpFunctions->C_GetInfo)(&ckLibInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jInfoObject = ckInfoPtrToJInfo(env, &ckLibInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jInfoObject = ckInfoPtrToJInfo(env, &ckLibInfo);
+    }
     return jInfoObject ;
 }
 
@@ -279,28 +283,31 @@
 
     /* load CK_INFO class */
     jInfoClass = (*env)->FindClass(env, CLASS_INFO);
-    assert(jInfoClass != 0);
+    if (jInfoClass == NULL) { return NULL; };
 
     /* load CK_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jInfoClass, "<init>",
        "(Lsun/security/pkcs11/wrapper/CK_VERSION;[CJ[CLsun/security/pkcs11/wrapper/CK_VERSION;)V");
-
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jCryptokiVer = ckVersionPtrToJVersion(env, &(ckpInfo->cryptokiVersion));
+    if (jCryptokiVer == NULL) { return NULL; }
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL) { return NULL; }
     jFlags = ckULongToJLong(ckpInfo->flags);
     jLibraryDesc =
       ckUTF8CharArrayToJCharArray(env, &(ckpInfo->libraryDescription[0]), 32);
+    if (jLibraryDesc == NULL) { return NULL; }
     jLibraryVer = ckVersionPtrToJVersion(env, &(ckpInfo->libraryVersion));
+    if (jLibraryVer == NULL) { return NULL; }
 
     /* create new CK_INFO object */
     jInfoObject = (*env)->NewObject(env, jInfoClass, jCtrId, jCryptokiVer,
                                     jVendor, jFlags, jLibraryDesc, jLibraryVer);
-    assert(jInfoObject != 0);
+    if (jInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jInfoClass);
@@ -343,15 +350,18 @@
     if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     ckpSlotList = (CK_SLOT_ID_PTR) malloc(ckTokenNumber * sizeof(CK_SLOT_ID));
+    if (ckpSlotList == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetSlotList)(ckTokenPresent, ckpSlotList,
                                         &ckTokenNumber);
-
-    jSlotList = ckULongArrayToJLongArray(env, ckpSlotList, ckTokenNumber);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotList = ckULongArrayToJLongArray(env, ckpSlotList, ckTokenNumber);
+    }
     free(ckpSlotList);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jSlotList ;
 }
 #endif
@@ -380,10 +390,9 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_GetSlotInfo)(ckSlotID, &ckSlotInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jSlotInfoObject = ckSlotInfoPtrToJSlotInfo(env, &ckSlotInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotInfoObject = ckSlotInfoPtrToJSlotInfo(env, &ckSlotInfo);
+    }
     return jSlotInfoObject ;
 }
 
@@ -410,28 +419,32 @@
 
     /* load CK_SLOT_INFO class */
     jSlotInfoClass = (*env)->FindClass(env, CLASS_SLOT_INFO);
-    assert(jSlotInfoClass != 0);
+    if (jSlotInfoClass == NULL) { return NULL; };
 
     /* load CK_SLOT_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jSlotInfoClass, "<init>",
        "([C[CJLsun/security/pkcs11/wrapper/CK_VERSION;Lsun/security/pkcs11/wrapper/CK_VERSION;)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jSlotDesc =
       ckUTF8CharArrayToJCharArray(env, &(ckpSlotInfo->slotDescription[0]), 64);
+    if (jSlotDesc == NULL) { return NULL; }
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpSlotInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL) { return NULL; }
     jFlags = ckULongToJLong(ckpSlotInfo->flags);
     jHardwareVer = ckVersionPtrToJVersion(env, &(ckpSlotInfo->hardwareVersion));
+    if (jHardwareVer == NULL) { return NULL; }
     jFirmwareVer = ckVersionPtrToJVersion(env, &(ckpSlotInfo->firmwareVersion));
+    if (jFirmwareVer == NULL) { return NULL; }
 
     /* create new CK_SLOT_INFO object */
     jSlotInfoObject = (*env)->NewObject
       (env, jSlotInfoClass, jCtrId, jSlotDesc, jVendor, jFlags,
        jHardwareVer, jFirmwareVer);
-    assert(jSlotInfoObject != 0);
+    if (jSlotInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jSlotInfoClass);
@@ -460,7 +473,7 @@
 {
     CK_SLOT_ID ckSlotID;
     CK_TOKEN_INFO ckTokenInfo;
-    jobject jInfoTokenObject;
+    jobject jInfoTokenObject = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -469,10 +482,9 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_GetTokenInfo)(ckSlotID, &ckTokenInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jInfoTokenObject = ckTokenInfoPtrToJTokenInfo(env, &ckTokenInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jInfoTokenObject = ckTokenInfoPtrToJTokenInfo(env, &ckTokenInfo);
+    }
     return jInfoTokenObject ;
 }
 
@@ -512,21 +524,25 @@
 
     /* load CK_TOKEN_INFO class */
     jTokenInfoClass = (*env)->FindClass(env, CLASS_TOKEN_INFO);
-    assert(jTokenInfoClass != 0);
+    if (jTokenInfoClass == NULL)  { return NULL; };
 
     /* load CK_TOKEN_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jTokenInfoClass, "<init>",
        "([C[C[C[CJJJJJJJJJJJLsun/security/pkcs11/wrapper/CK_VERSION;Lsun/security/pkcs11/wrapper/CK_VERSION;[C)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL)  { return NULL; };
 
     /* prep all fields */
     jLabel = ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->label[0]), 32);
+    if (jLabel == NULL)  { return NULL; };
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL)  { return NULL; };
     jModel = ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->model[0]), 16);
+    if (jModel == NULL)  { return NULL; };
     jSerialNo =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->serialNumber[0]), 16);
+    if (jSerialNo == NULL)  { return NULL; };
     jFlags = ckULongToJLong(ckpTokenInfo->flags);
     jMaxSnCnt = ckULongSpecialToJLong(ckpTokenInfo->ulMaxSessionCount);
     jSnCnt = ckULongSpecialToJLong(ckpTokenInfo->ulSessionCount);
@@ -540,10 +556,13 @@
     jFreePrivMem = ckULongSpecialToJLong(ckpTokenInfo->ulFreePrivateMemory);
     jHardwareVer =
       ckVersionPtrToJVersion(env, &(ckpTokenInfo->hardwareVersion));
+    if (jHardwareVer == NULL) { return NULL; }
     jFirmwareVer =
       ckVersionPtrToJVersion(env, &(ckpTokenInfo->firmwareVersion));
+    if (jFirmwareVer == NULL) { return NULL; }
     jUtcTime =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->utcTime[0]), 16);
+    if (jUtcTime == NULL) { return NULL; }
 
     /* create new CK_TOKEN_INFO object */
     jTokenInfoObject =
@@ -553,7 +572,7 @@
                         jMaxPinLen, jMinPinLen,
                         jTotalPubMem, jFreePubMem, jTotalPrivMem, jFreePrivMem,
                         jHardwareVer, jFirmwareVer, jUtcTime);
-    assert(jTokenInfoObject != 0);
+    if (jTokenInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jTokenInfoClass);
@@ -584,7 +603,7 @@
 {
     CK_FLAGS ckFlags;
     CK_SLOT_ID ckSlotID;
-    jlong jSlotID;
+    jlong jSlotID = 0L;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -593,9 +612,9 @@
     ckFlags = jLongToCKULong(jFlags);
 
     rv = (*ckpFunctions->C_WaitForSlotEvent)(ckFlags, &ckSlotID, NULL_PTR);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L; }
-
-    jSlotID = ckULongToJLong(ckSlotID);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotID = ckULongToJLong(ckSlotID);
+    }
 
     return jSlotID ;
 }
@@ -632,16 +651,19 @@
 
     ckpMechanismList = (CK_MECHANISM_TYPE_PTR)
       malloc(ckMechanismNumber * sizeof(CK_MECHANISM_TYPE));
+    if (ckpMechanismList == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetMechanismList)(ckSlotID, ckpMechanismList,
                                              &ckMechanismNumber);
-
-    jMechanismList = ckULongArrayToJLongArray(env, ckpMechanismList,
-                                              ckMechanismNumber);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jMechanismList = ckULongArrayToJLongArray(env, ckpMechanismList,
+                                                  ckMechanismNumber);
+    }
     free(ckpMechanismList);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jMechanismList ;
 }
 #endif
@@ -663,7 +685,7 @@
     CK_SLOT_ID ckSlotID;
     CK_MECHANISM_TYPE ckMechanismType;
     CK_MECHANISM_INFO ckMechanismInfo;
-    jobject jMechanismInfo;
+    jobject jMechanismInfo = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -674,10 +696,9 @@
 
     rv = (*ckpFunctions->C_GetMechanismInfo)(ckSlotID, ckMechanismType,
                                              &ckMechanismInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jMechanismInfo = ckMechanismInfoPtrToJMechanismInfo(env, &ckMechanismInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jMechanismInfo = ckMechanismInfoPtrToJMechanismInfo(env, &ckMechanismInfo);
+    }
     return jMechanismInfo ;
 }
 
@@ -703,11 +724,11 @@
 
     /* load CK_MECHANISM_INFO class */
     jMechanismInfoClass = (*env)->FindClass(env, CLASS_MECHANISM_INFO);
-    assert(jMechanismInfoClass != 0);
+    if (jMechanismInfoClass == NULL) { return NULL; };
 
     /* load CK_MECHANISM_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jMechanismInfoClass, "<init>", "(JJJ)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; };
 
     /* prep all fields */
     jMinKeySize = ckULongToJLong(ckpMechanismInfo->ulMinKeySize);
@@ -717,7 +738,7 @@
     /* create new CK_MECHANISM_INFO object */
     jMechanismInfoObject = (*env)->NewObject(env, jMechanismInfoClass, jCtrId,
                                              jMinKeySize, jMaxKeySize, jFlags);
-    assert(jMechanismInfoObject != 0);
+    if (jMechanismInfoObject == NULL) { return NULL; };
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jMechanismInfoClass);
@@ -753,8 +774,13 @@
 
     ckSlotID = jLongToCKULong(jSlotID);
     jCharArrayToCKCharArray(env, jPin, &ckpPin, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+    /* ckLabelLength <= 32 !!! */
     jCharArrayToCKUTF8CharArray(env, jLabel, &ckpLabel, &ckLabelLength);
-    /* ckLabelLength <= 32 !!! */
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpPin);
+        return;
+    }
 
     rv = (*ckpFunctions->C_InitToken)(ckSlotID, ckpPin, ckPinLength, ckpLabel);
     TRACE1("InitToken return code: %d", rv);
@@ -790,6 +816,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jCharArrayToCKCharArray(env, jPin, &ckpPin, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_InitPIN)(ckSessionHandle, ckpPin, ckPinLength);
 
@@ -828,7 +855,12 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jCharArrayToCKCharArray(env, jOldPin, &ckpOldPin, &ckOldPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
     jCharArrayToCKCharArray(env, jNewPin, &ckpNewPin, &ckNewPinLength);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpOldPin);
+        return;
+    }
 
     rv = (*ckpFunctions->C_SetPIN)(ckSessionHandle, ckpOldPin, ckOldPinLength,
                                    ckpNewPin, ckNewPinLength);
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -74,7 +74,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jlong jKeyHandle;
+    jlong jKeyHandle = 0L;
     CK_ULONG i;
     CK_RV rv;
 
@@ -83,21 +83,23 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
-    if ((*env)->ExceptionOccurred(env)) { return 0L ; }
+    if ((*env)->ExceptionCheck(env)) { return 0L ; }
+
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
 
     rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, &ckMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
-    jKeyHandle = ckULongToJLong(ckKeyHandle);
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandle = ckULongToJLong(ckKeyHandle);
 
-    /* cheack, if we must give a initialization vector back to Java */
-    switch (ckMechanism.mechanism) {
+        /* cheack, if we must give a initialization vector back to Java */
+        switch (ckMechanism.mechanism) {
         case CKM_PBE_MD2_DES_CBC:
         case CKM_PBE_MD5_DES_CBC:
         case CKM_PBE_MD5_CAST_CBC:
@@ -109,13 +111,13 @@
             /* we must copy back the initialization vector to the jMechanism object */
             copyBackPBEInitializationVector(env, &ckMechanism, jMechanism);
             break;
+        }
     }
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     return jKeyHandle ;
 }
@@ -158,40 +160,53 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
-    jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
-    jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
+
     ckpKeyHandles = (CK_OBJECT_HANDLE_PTR) malloc(2 * sizeof(CK_OBJECT_HANDLE));
+    if (ckpKeyHandles == NULL) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     ckpPublicKeyHandle = ckpKeyHandles;   /* first element of array is Public Key */
     ckpPrivateKeyHandle = (ckpKeyHandles + 1);  /* second element of array is Private Key */
 
+    jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpKeyHandles);
+        return NULL;
+    }
+
+    jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpKeyHandles);
+        freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
+        return NULL;
+    }
+
     rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, &ckMechanism,
                      ckpPublicKeyAttributes, ckPublicKeyAttributesLength,
                      ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength,
                      ckpPublicKeyHandle, ckpPrivateKeyHandle);
 
-    jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
-
-    for(i=0; i<ckPublicKeyAttributesLength; i++) {
-        if(ckpPublicKeyAttributes[i].pValue != NULL_PTR) {
-            free(ckpPublicKeyAttributes[i].pValue);
-        }
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
     }
-    free(ckpPublicKeyAttributes);
-
-    for(i=0; i<ckPrivateKeyAttributesLength; i++) {
-        if(ckpPrivateKeyAttributes[i].pValue != NULL_PTR) {
-            free(ckpPrivateKeyAttributes[i].pValue);
-        }
-    }
-    free(ckpPrivateKeyAttributes);
 
     if(ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
     free(ckpKeyHandles);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL; }
+    freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
+    freeCKAttributeArray(ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength);
 
     return jKeyHandles ;
 }
@@ -217,7 +232,7 @@
     CK_MECHANISM ckMechanism;
     CK_OBJECT_HANDLE ckWrappingKeyHandle;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jbyteArray jWrappedKey;
+    jbyteArray jWrappedKey = NULL;
     CK_RV rv;
     CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
     CK_BYTE_PTR ckpWrappedKey = BUF;
@@ -228,24 +243,32 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
+
     ckWrappingKeyHandle = jLongToCKULong(jWrappingKeyHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     if (rv == CKR_BUFFER_TOO_SMALL) {
         ckpWrappedKey = (CK_BYTE_PTR) malloc(ckWrappedKeyLength);
+        if (ckpWrappedKey == NULL) {
+            if (ckMechanism.pParameter != NULL_PTR) {
+                free(ckMechanism.pParameter);
+            }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
+
         rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jWrappedKey = ckByteArrayToJByteArray(env, ckpWrappedKey, ckWrappedKeyLength);
     }
 
-    if (ckpWrappedKey != BUF) {
-        free(ckpWrappedKey);
+    if (ckpWrappedKey != BUF) { free(ckpWrappedKey); }
+    if (ckMechanism.pParameter != NULL_PTR) {
+        free(ckMechanism.pParameter);
     }
-    if(ckMechanism.pParameter != NULL_PTR)
-        free(ckMechanism.pParameter);
-
     return jWrappedKey ;
 }
 #endif
@@ -277,7 +300,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jlong jKeyHandle;
+    jlong jKeyHandle = 0L;
     CK_ULONG i;
     CK_RV rv;
 
@@ -286,37 +309,48 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
+
     ckUnwrappingKeyHandle = jLongToCKULong(jUnwrappingKeyHandle);
     jByteArrayToCKByteArray(env, jWrappedKey, &ckpWrappedKey, &ckWrappedKeyLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
+
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpWrappedKey);
+        return 0L;
+    }
+
 
     rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism, ckUnwrappingKeyHandle,
                  ckpWrappedKey, ckWrappedKeyLength,
                  ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
-    jKeyHandle = ckLongToJLong(ckKeyHandle);
-
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandle = ckLongToJLong(ckKeyHandle);
 
 #if 0
-    /* cheack, if we must give a initialization vector back to Java */
-    if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
-        /* we must copy back the unwrapped key info to the jMechanism object */
-        copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
+        /* cheack, if we must give a initialization vector back to Java */
+        if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
+            /* we must copy back the unwrapped key info to the jMechanism object */
+            copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
+        }
+#endif
     }
-#endif
 
-    free(ckpWrappedKey);
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+    free(ckpWrappedKey);
 
     return jKeyHandle ;
 }
@@ -360,8 +394,7 @@
  */
 void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-    jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-    jclass jTLSPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    jclass jMechanismClass, jTLSPrfParamsClass;
     CK_TLS_PRF_PARAMS *ckTLSPrfParams;
     jobject jTLSPrfParams;
     jfieldID fieldID;
@@ -374,8 +407,10 @@
     int i;
 
     /* get mechanism */
+    jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (jMechanismClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
     if (ckMechanismType != ckMechanism->mechanism) {
@@ -388,12 +423,14 @@
     if (ckTLSPrfParams != NULL_PTR) {
         /* get the Java CK_TLS_PRF_PARAMS object (pParameter) */
         fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-        assert(fieldID != 0);
+        if (fieldID == NULL) { return; }
         jTLSPrfParams = (*env)->GetObjectField(env, jMechanism, fieldID);
 
         /* copy back the client IV */
+        jTLSPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+        if (jTLSPrfParamsClass == NULL) { return; }
         fieldID = (*env)->GetFieldID(env, jTLSPrfParamsClass, "pOutput", "[B");
-        assert(fieldID != 0);
+        if (fieldID == NULL) { return; }
         jOutput = (*env)->GetObjectField(env, jTLSPrfParams, fieldID);
         output = ckTLSPrfParams->pOutput;
 
@@ -402,26 +439,21 @@
         if (jOutput != NULL) {
             jLength = (*env)->GetArrayLength(env, jOutput);
             jBytes = (*env)->GetByteArrayElements(env, jOutput, NULL);
+            if (jBytes == NULL) { return; }
+
             /* copy the bytes to the Java buffer */
             for (i=0; i < jLength; i++) {
                 jBytes[i] = ckByteToJByte(output[i]);
             }
             /* copy back the Java buffer to the object */
             (*env)->ReleaseByteArrayElements(env, jOutput, jBytes, 0);
-            // free malloc'd data
-            free(output);
         }
 
         // free malloc'd data
-        if (ckTLSPrfParams->pSeed != NULL) {
-            free(ckTLSPrfParams->pSeed);
-        }
-        if (ckTLSPrfParams->pLabel != NULL) {
-            free(ckTLSPrfParams->pLabel);
-        }
-        if (ckTLSPrfParams->pulOutputLen != NULL) {
-            free(ckTLSPrfParams->pulOutputLen);
-        }
+        free(ckTLSPrfParams->pSeed);
+        free(ckTLSPrfParams->pLabel);
+        free(ckTLSPrfParams->pulOutputLen);
+        free(ckTLSPrfParams->pOutput);
     }
 }
 
@@ -456,8 +488,16 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
+
     ckBaseKeyHandle = jLongToCKULong(jBaseKeyHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
 
     switch (ckMechanism.mechanism) {
     case CKM_SSL3_KEY_AND_MAC_DERIVE:
@@ -476,14 +516,8 @@
                  ckpAttributes, ckAttributesLength, phKey);
 
     jKeyHandle = ckLongToJLong(ckKeyHandle);
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    if (ckpAttributes != NULL) {
-        free(ckpAttributes);
-    }
+
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     switch (ckMechanism.mechanism) {
     case CKM_SSL3_MASTER_KEY_DERIVE:
@@ -512,11 +546,10 @@
         break;
     }
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     return jKeyHandle ;
 }
@@ -529,9 +562,7 @@
  */
 void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-  jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-  jclass jSSL3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-  jclass jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+  jclass jMechanismClass, jSSL3MasterKeyDeriveParamsClass, jVersionClass;
   CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ckSSL3MasterKeyDeriveParams;
   CK_VERSION *ckVersion;
   jfieldID fieldID;
@@ -541,8 +572,10 @@
   jobject jVersion;
 
   /* get mechanism */
+  jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+  if (jMechanismClass == NULL) { return; }
   fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-  assert(fieldID != 0);
+  if (fieldID == NULL) { return; }
   jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
   ckMechanismType = jLongToCKULong(jMechanismType);
   if (ckMechanismType != ckMechanism->mechanism) {
@@ -558,27 +591,31 @@
     if (ckVersion != NULL_PTR) {
       /* get the Java CK_SSL3_MASTER_KEY_DERIVE_PARAMS (pParameter) */
       fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
+
       jSSL3MasterKeyDeriveParams = (*env)->GetObjectField(env, jMechanism, fieldID);
 
       /* get the Java CK_VERSION */
+      jSSL3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+      if (jSSL3MasterKeyDeriveParamsClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3MasterKeyDeriveParamsClass, "pVersion", "L"CLASS_VERSION";");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jVersion = (*env)->GetObjectField(env, jSSL3MasterKeyDeriveParams, fieldID);
 
       /* now copy back the version from the native structure to the Java structure */
 
       /* copy back the major version */
+      jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+      if (jVersionClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jVersionClass, "major", "B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetByteField(env, jVersion, fieldID, ckByteToJByte(ckVersion->major));
 
       /* copy back the minor version */
       fieldID = (*env)->GetFieldID(env, jVersionClass, "minor", "B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetByteField(env, jVersion, fieldID, ckByteToJByte(ckVersion->minor));
     }
-
   }
 }
 
@@ -591,9 +628,7 @@
  */
 void copyBackSSLKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-  jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-  jclass jSSL3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
-  jclass jSSL3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+  jclass jMechanismClass, jSSL3KeyMatParamsClass, jSSL3KeyMatOutClass;
   CK_SSL3_KEY_MAT_PARAMS *ckSSL3KeyMatParam;
   CK_SSL3_KEY_MAT_OUT *ckSSL3KeyMatOut;
   jfieldID fieldID;
@@ -608,8 +643,10 @@
   int i;
 
   /* get mechanism */
+  jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
+  if (jMechanismClass == NULL) { return; }
   fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-  assert(fieldID != 0);
+  if (fieldID == NULL) { return; }
   jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
   ckMechanismType = jLongToCKULong(jMechanismType);
   if (ckMechanismType != ckMechanism->mechanism) {
@@ -633,74 +670,78 @@
     if (ckSSL3KeyMatOut != NULL_PTR) {
       /* get the Java CK_SSL3_KEY_MAT_PARAMS (pParameter) */
       fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jSSL3KeyMatParam = (*env)->GetObjectField(env, jMechanism, fieldID);
 
       /* get the Java CK_SSL3_KEY_MAT_OUT */
+      jSSL3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+      if (jSSL3KeyMatParamsClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatParamsClass, "pReturnedKeyMaterial", "L"CLASS_SSL3_KEY_MAT_OUT";");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jSSL3KeyMatOut = (*env)->GetObjectField(env, jSSL3KeyMatParam, fieldID);
 
       /* now copy back all the key handles and the initialization vectors */
       /* copy back client MAC secret handle */
+      jSSL3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+      if (jSSL3KeyMatOutClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hClientMacSecret", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hClientMacSecret));
 
       /* copy back server MAC secret handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hServerMacSecret", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hServerMacSecret));
 
       /* copy back client secret key handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hClientKey", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hClientKey));
 
       /* copy back server secret key handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hServerKey", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hServerKey));
 
       /* copy back the client IV */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "pIVClient", "[B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jIV = (*env)->GetObjectField(env, jSSL3KeyMatOut, fieldID);
       iv = ckSSL3KeyMatOut->pIVClient;
 
       if (jIV != NULL) {
         jLength = (*env)->GetArrayLength(env, jIV);
         jBytes = (*env)->GetByteArrayElements(env, jIV, NULL);
+        if (jBytes == NULL) { return; }
         /* copy the bytes to the Java buffer */
         for (i=0; i < jLength; i++) {
           jBytes[i] = ckByteToJByte(iv[i]);
         }
         /* copy back the Java buffer to the object */
         (*env)->ReleaseByteArrayElements(env, jIV, jBytes, 0);
-        // free malloc'd data
-        free(iv);
       }
+      // free malloc'd data
+      free(ckSSL3KeyMatOut->pIVClient);
 
       /* copy back the server IV */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "pIVServer", "[B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jIV = (*env)->GetObjectField(env, jSSL3KeyMatOut, fieldID);
       iv = ckSSL3KeyMatOut->pIVServer;
 
       if (jIV != NULL) {
         jLength = (*env)->GetArrayLength(env, jIV);
         jBytes = (*env)->GetByteArrayElements(env, jIV, NULL);
+        if (jBytes == NULL) { return; }
         /* copy the bytes to the Java buffer */
         for (i=0; i < jLength; i++) {
           jBytes[i] = ckByteToJByte(iv[i]);
         }
         /* copy back the Java buffer to the object */
         (*env)->ReleaseByteArrayElements(env, jIV, jBytes, 0);
-        // free malloc'd data
-        free(iv);
       }
-
       // free malloc'd data
+      free(ckSSL3KeyMatOut->pIVServer);
       free(ckSSL3KeyMatOut);
     }
   }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -76,7 +76,7 @@
 CK_C_INITIALIZE_ARGS_PTR makeCKInitArgsAdapter(JNIEnv *env, jobject jInitArgs)
 {
     CK_C_INITIALIZE_ARGS_PTR ckpInitArgs;
-    jclass jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    jclass jInitArgsClass;
     jfieldID fieldID;
     jlong jFlags;
     jobject jReserved;
@@ -91,10 +91,20 @@
 
     /* convert the Java InitArgs object to a pointer to a CK_C_INITIALIZE_ARGS structure */
     ckpInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
+    if (ckpInitArgs == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL_PTR;
+    }
 
     /* Set the mutex functions that will call the Java mutex functions, but
      * only set it, if the field is not null.
      */
+    jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) {
+        free(ckpInitArgs);
+        return NULL;
+    }
+
 #ifdef NO_CALLBACKS
     ckpInitArgs->CreateMutex = NULL_PTR;
     ckpInitArgs->DestroyMutex = NULL_PTR;
@@ -102,22 +112,22 @@
     ckpInitArgs->UnlockMutex = NULL_PTR;
 #else
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "CreateMutex", "Lsun/security/pkcs11/wrapper/CK_CREATEMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->CreateMutex = (jMutexHandler != NULL) ? &callJCreateMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "DestroyMutex", "Lsun/security/pkcs11/wrapper/CK_DESTROYMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->DestroyMutex = (jMutexHandler != NULL) ? &callJDestroyMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "LockMutex", "Lsun/security/pkcs11/wrapper/CK_LOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->LockMutex = (jMutexHandler != NULL) ? &callJLockMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->UnlockMutex = (jMutexHandler != NULL) ? &callJUnlockMutex : NULL_PTR;
 
@@ -129,19 +139,25 @@
         /* set the global object jInitArgs so that the right Java mutex functions will be called */
         jInitArgsObject = (*env)->NewGlobalRef(env, jInitArgs);
         ckpGlobalInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
+        if (ckpGlobalInitArgs == NULL) {
+            free(ckpInitArgs);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL_PTR;
+        }
+
         memcpy(ckpGlobalInitArgs, ckpInitArgs, sizeof(CK_C_INITIALIZE_ARGS));
     }
 #endif /* NO_CALLBACKS */
 
     /* convert and set the flags field */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "flags", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jFlags = (*env)->GetLongField(env, jInitArgs, fieldID);
     ckpInitArgs->flags = jLongToCKULong(jFlags);
 
     /* pReserved should be NULL_PTR in this version */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "pReserved", "Ljava/lang/Object;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jReserved = (*env)->GetObjectField(env, jInitArgs, fieldID);
 
     /* we try to convert the reserved parameter also */
@@ -201,20 +217,21 @@
         wasAttached = 1;
     }
 
-
     jCreateMutexClass = (*env)->FindClass(env, CLASS_CREATEMUTEX);
+    if (jCreateMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* get the CreateMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "CreateMutex", "Lsun/security/pkcs11/wrapper/CK_CREATEMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jCreateMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jCreateMutex != 0);
 
     /* call the CK_CREATEMUTEX function of the CreateMutex object */
     /* and get the new Java mutex object */
     methodID = (*env)->GetMethodID(env, jCreateMutexClass, "CK_CREATEMUTEX", "()Ljava/lang/Object;");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     jMutex = (*env)->CallObjectMethod(env, jCreateMutex, methodID);
 
     /* set a global reference on the Java mutex */
@@ -227,10 +244,13 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
+
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -292,22 +312,23 @@
         wasAttached = 1;
     }
 
-
     jDestroyMutexClass = (*env)->FindClass(env, CLASS_DESTROYMUTEX);
+    if (jDestroyMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the DestroyMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "DestroyMutex", "Lsun/security/pkcs11/wrapper/CK_DESTROYMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jDestroyMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jDestroyMutex != 0);
 
     /* call the CK_DESTROYMUTEX method of the DestroyMutex object */
     methodID = (*env)->GetMethodID(env, jDestroyMutexClass, "CK_DESTROYMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jDestroyMutex, methodID, jMutex);
 
     /* delete the global reference on the Java mutex */
@@ -318,10 +339,12 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -383,33 +406,35 @@
         wasAttached = 1;
     }
 
-
     jLockMutexClass = (*env)->FindClass(env, CLASS_LOCKMUTEX);
+    if (jLockMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the LockMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "LockMutex", "Lsun/security/pkcs11/wrapper/CK_LOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jLockMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jLockMutex != 0);
 
     /* call the CK_LOCKMUTEX method of the LockMutex object */
     methodID = (*env)->GetMethodID(env, jLockMutexClass, "CK_LOCKMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jLockMutex, methodID, jMutex);
 
-
     /* check, if callback threw an exception */
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -471,33 +496,35 @@
         wasAttached = 1;
     }
 
-
     jUnlockMutexClass = (*env)->FindClass(env, CLASS_UNLOCKMUTEX);
+    if (jUnlockMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK-type mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the UnlockMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jUnlockMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jUnlockMutex != 0);
 
     /* call the CK_UNLOCKMUTEX method of the UnLockMutex object */
     methodID = (*env)->GetMethodID(env, jUnlockMutexClass, "CK_UNLOCKMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jUnlockMutex, methodID, jMutex);
 
-
     /* check, if callback threw an exception */
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -81,16 +81,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     rv = (*ckpFunctions->C_CreateObject)(ckSessionHandle, ckpAttributes, ckAttributesLength, &ckObjectHandle);
 
     jObjectHandle = ckULongToJLong(ckObjectHandle);
-    for(i=0; i<ckAttributesLength; i++)
-        if(ckpAttributes[i].pValue != NULL_PTR)
-            free(ckpAttributes[i].pValue);
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     return jObjectHandle ;
 }
@@ -126,14 +124,12 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     rv = (*ckpFunctions->C_CopyObject)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength, &ckNewObjectHandle);
 
     jNewObjectHandle = ckULongToJLong(ckNewObjectHandle);
-    for(i=0; i<ckAttributesLength; i++)
-        if(ckpAttributes[i].pValue != NULL_PTR)
-            free(ckpAttributes[i].pValue);
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
@@ -164,7 +160,7 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
 
     rv = (*ckpFunctions->C_DestroyObject)(ckSessionHandle, ckObjectHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -194,7 +190,7 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
 
     rv = (*ckpFunctions->C_GetObjectSize)(ckSessionHandle, ckObjectHandle, &ckObjectSize);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     jObjectSize = ckULongToJLong(ckObjectSize);
 
@@ -221,7 +217,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_ULONG ckBufferLength;
-    CK_ULONG i;
+    CK_ULONG i, j;
     jobject jAttribute;
     CK_RV rv;
 
@@ -238,19 +234,20 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     TRACE1("jAttributeArrayToCKAttributeArray now with jTemplate = %d", jTemplate);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     TRACE2("DEBUG: jAttributeArrayToCKAttributeArray finished with ckpAttribute = %d, Length = %d\n", ckpAttributes, ckAttributesLength);
 
     /* first set all pValue to NULL, to get the needed buffer length */
     for(i = 0; i < ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
+        if (ckpAttributes[i].pValue != NULL_PTR) {
             free(ckpAttributes[i].pValue);
+            ckpAttributes[i].pValue = NULL_PTR;
         }
     }
-    for (i = 0; i < ckAttributesLength; i++) {
-        ckpAttributes[i].pValue = NULL_PTR;
-    }
+
     rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
         free(ckpAttributes);
         return ;
     }
@@ -261,27 +258,34 @@
     for (i = 0; i < ckAttributesLength; i++) {
         ckBufferLength = sizeof(CK_BYTE) * ckpAttributes[i].ulValueLen;
         ckpAttributes[i].pValue = (void *) malloc(ckBufferLength);
+        if (ckpAttributes[i].pValue == NULL) {
+            freeCKAttributeArray(ckpAttributes, i);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
         ckpAttributes[i].ulValueLen = ckBufferLength;
     }
 
     /* now get the attributes with all values */
     rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
 
-    /* copy back the values to the Java attributes */
-    for (i = 0; i < ckAttributesLength; i++) {
-        jAttribute = ckAttributePtrToJAttribute(env, &(ckpAttributes[i]));
-        (*env)->SetObjectArrayElement(env, jTemplate, i, jAttribute);
-    }
-
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        /* copy back the values to the Java attributes */
+        for (i = 0; i < ckAttributesLength; i++) {
+            jAttribute = ckAttributePtrToJAttribute(env, &(ckpAttributes[i]));
+            if (jAttribute == NULL) {
+                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+                return;
+            }
+            (*env)->SetObjectArrayElement(env, jTemplate, i, jAttribute);
+            if ((*env)->ExceptionCheck(env)) {
+                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+                return;
+            }
         }
     }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
     TRACE0("FINISHED\n");
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return ; }
 }
 #endif
 
@@ -312,15 +316,11 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_SetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
 
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
@@ -355,15 +355,11 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_FindObjectsInit)(ckSessionHandle, ckpAttributes, ckAttributesLength);
 
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
     TRACE0("FINISHED\n");
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
@@ -397,14 +393,18 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckMaxObjectLength = jLongToCKULong(jMaxObjectCount);
     ckpObjectHandleArray = (CK_OBJECT_HANDLE_PTR) malloc(sizeof(CK_OBJECT_HANDLE) * ckMaxObjectLength);
+    if (ckpObjectHandleArray == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_FindObjects)(ckSessionHandle, ckpObjectHandleArray, ckMaxObjectLength, &ckActualObjectCount);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jObjectHandleArray = ckULongArrayToJLongArray(env, ckpObjectHandleArray, ckActualObjectCount);
+    }
 
-    jObjectHandleArray = ckULongArrayToJLongArray(env, ckpObjectHandleArray, ckActualObjectCount);
     free(ckpObjectHandleArray);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jObjectHandleArray ;
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -97,6 +97,10 @@
 #ifndef NO_CALLBACKS
     if (jNotify != NULL) {
         notifyEncapsulation = (NotifyEncapsulation *) malloc(sizeof(NotifyEncapsulation));
+        if (notifyEncapsulation == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0L;
+        }
         notifyEncapsulation->jApplicationData = (jApplication != NULL)
                 ? (*env)->NewGlobalRef(env, jApplication)
                 : NULL;
@@ -118,7 +122,18 @@
     TRACE0(" ... ");
 
     rv = (*ckpFunctions->C_OpenSession)(ckSlotID, ckFlags, ckpApplication, ckNotify, &ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+#ifndef NO_CALLBACKS
+        if (notifyEncapsulation != NULL) {
+            if (notifyEncapsulation->jApplicationData != NULL) {
+                (*env)->DeleteGlobalRef(env, jApplication);
+            }
+            (*env)->DeleteGlobalRef(env, jNotify);
+            free(notifyEncapsulation);
+        }
+#endif /* NO_CALLBACKS */
+        return 0L;
+    }
 
     TRACE0("got session");
     TRACE1(", SessionHandle=%u", ckSessionHandle);
@@ -163,7 +178,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_CloseSession)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 
 #ifndef NO_CALLBACKS
     notifyEncapsulation = removeNotifyEntry(env, ckSessionHandle);
@@ -208,7 +223,7 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_CloseAllSessions)(ckSlotID);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 
 #ifndef NO_CALLBACKS
     /* Remove all notify callback helper objects. */
@@ -250,10 +265,9 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_GetSessionInfo)(ckSessionHandle, &ckSessionInfo);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jSessionInfo = ckSessionInfoPtrToJSessionInfo(env, &ckSessionInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSessionInfo = ckSessionInfoPtrToJSessionInfo(env, &ckSessionInfo);
+    }
     return jSessionInfo ;
 }
 #endif
@@ -274,7 +288,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpState;
     CK_ULONG ckStateLength;
-    jbyteArray jState;
+    jbyteArray jState = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -283,17 +297,20 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_GetOperationState)(ckSessionHandle, NULL_PTR, &ckStateLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     ckpState = (CK_BYTE_PTR) malloc(ckStateLength);
+    if (ckpState == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetOperationState)(ckSessionHandle, ckpState, &ckStateLength);
-
-    jState = ckByteArrayToJByteArray(env, ckpState, ckStateLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jState = ckByteArrayToJByteArray(env, ckpState, ckStateLength);
+    }
     free(ckpState);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jState ;
 }
 #endif
@@ -325,6 +342,8 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jOperationState, &ckpState, &ckStateLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckEncryptionKeyHandle = jLongToCKULong(jEncryptionKeyHandle);
     ckAuthenticationKeyHandle = jLongToCKULong(jAuthenticationKeyHandle);
 
@@ -332,7 +351,7 @@
 
     free(ckpState);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -362,12 +381,13 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckUserType = jLongToCKULong(jUserType);
     jCharArrayToCKCharArray(env, jPin, &ckpPinArray, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_Login)(ckSessionHandle, ckUserType, ckpPinArray, ckPinLength);
 
     free(ckpPinArray);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -391,7 +411,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_Logout)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -410,10 +430,14 @@
     NotifyListNode *currentNode, *newNode;
 
     if (notifyEncapsulation == NULL) {
-        return ;
+        return;
     }
 
     newNode = (NotifyListNode *) malloc(sizeof(NotifyListNode));
+    if (newNode == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     newNode->hSession = hSession;
     newNode->notifyEncapsulation = notifyEncapsulation;
     newNode->next = NULL;
@@ -578,9 +602,10 @@
     jEvent = ckULongToJLong(event);
 
     ckNotifyClass = (*env)->FindClass(env, CLASS_NOTIFY);
-    assert(ckNotifyClass != 0);
+    if (ckNotifyClass == NULL) { return rv; }
     jmethod = (*env)->GetMethodID(env, ckNotifyClass, "CK_NOTIFY", "(JJLjava/lang/Object;)V");
-    assert(jmethod != 0);
+    if (jmethod == NULL) { return rv; }
+
     (*env)->CallVoidMethod(env, notifyEncapsulation->jNotifyObject, jmethod,
                          jSessionHandle, jEvent, notifyEncapsulation->jApplicationData);
 
@@ -588,10 +613,14 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
+
         jmethod = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(jmethod != 0);
+        if (jmethod == NULL) { return rv; }
+
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, jmethod);
         rv = jLongToCKULong(errorCode);
     }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -77,15 +77,16 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -117,14 +118,23 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     /* START standard code */
 
     /* first determine the length of the signature */
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, NULL_PTR, &ckSignatureLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpData);
+        return NULL;
+    }
 
     ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
+    if (ckpSignature == NULL) {
+        free(ckpData);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     /* now get the signature */
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
@@ -134,22 +144,31 @@
     /* START workaround code for operation abort bug in pkcs#11 of Datakey and iButton */
 /*
     ckpSignature = (CK_BYTE_PTR) malloc(256 * sizeof(CK_BYTE));
+    if (ckpSignature == NULL) {
+        free(ckpData);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
 
     if (rv == CKR_BUFFER_TOO_SMALL) {
         free(ckpSignature);
         ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
+        if (ckpSignature == NULL) {
+            free(ckpData);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
     }
  */
     /* END workaround code */
-
-    jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
+    }
     free(ckpData);
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jSignature ;
 }
 #endif
@@ -189,14 +208,22 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
         rv = (*ckpFunctions->C_SignUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
             if (bufP != BUF) {
                 free(bufP);
             }
@@ -206,9 +233,7 @@
         jInLen -= chunkLen;
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
 }
 #endif
 
@@ -244,15 +269,18 @@
     rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
     if (rv == CKR_BUFFER_TOO_SMALL) {
         bufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jSignature = ckByteArrayToJByteArray(env, bufP, ckSignatureLength);
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
+
     return jSignature;
 }
 #endif
@@ -280,11 +308,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
@@ -323,26 +353,38 @@
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
     } else {
-        inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+        if (inBufP != INBUF) { free(inBufP); }
+        return 0;
+    }
     rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     /* re-alloc larger buffer if it fits into our Java buffer */
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckSignatureLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
+        if (outBufP == NULL) {
+            if (inBufP != INBUF) {
+                free(inBufP);
+            }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
         rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckSignatureLength, (jbyte *)outBufP);
     }
 
-    if (inBufP != INBUF) {
-        free(inBufP);
-    }
-    if (outBufP != OUTBUF) {
-        free(outBufP);
-    }
+    if (inBufP != INBUF) { free(inBufP); }
+    if (outBufP != OUTBUF) { free(outBufP); }
+
     return ckSignatureLength;
 }
 #endif
@@ -370,6 +412,8 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
@@ -378,7 +422,7 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -409,7 +453,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpData);
+        return;
+    }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_Verify)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, ckSignatureLength);
@@ -417,7 +467,7 @@
     free(ckpData);
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -456,26 +506,31 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
+
         rv = (*ckpFunctions->C_VerifyUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) {
-                free(bufP);
-            }
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+            if (bufP != BUF) { free(bufP); }
             return;
         }
         jInOfs += chunkLen;
         jInLen -= chunkLen;
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
 }
 #endif
 
@@ -502,13 +557,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_VerifyFinal)(ckSessionHandle, ckpSignature, ckSignatureLength);
 
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -535,15 +591,17 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -578,26 +636,38 @@
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
     } else {
-        inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+        if (inBufP != INBUF) { free(inBufP); }
+        return 0;
+    }
+
     rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
+
     /* re-alloc larger buffer if it fits into our Java buffer */
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckDataLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckDataLength);
+        if (outBufP == NULL) {
+            if (inBufP != INBUF) { free(inBufP); }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
         rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckDataLength, (jbyte *)outBufP);
     }
 
-    if (inBufP != INBUF) {
-        free(inBufP);
-    }
-    if (outBufP != OUTBUF) {
-        free(outBufP);
-    }
+    if (inBufP != INBUF) { free(inBufP); }
+    if (outBufP != OUTBUF) { free(outBufP); }
+
     return ckDataLength;
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -73,11 +73,11 @@
     jmethodID jConstructor;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Object");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jObjectClass, "<init>", "()V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jLockObject = (*env)->NewObject(env, jObjectClass, jConstructor);
-    assert(jLockObject != 0);
+    if (jLockObject == NULL) { return NULL; }
     jLockObject = (*env)->NewGlobalRef(env, jLockObject);
 
     return jLockObject ;
@@ -200,84 +200,30 @@
         return 0L ;
     } else {
         jPKCS11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
-        assert(jPKCS11ExceptionClass != 0);
-        jConstructor = (*env)->GetMethodID(env, jPKCS11ExceptionClass, "<init>", "(J)V");
-        assert(jConstructor != 0);
-        jErrorCode = ckULongToJLong(returnValue);
-        jPKCS11Exception = (jthrowable) (*env)->NewObject(env, jPKCS11ExceptionClass, jConstructor, jErrorCode);
-        (*env)->Throw(env, jPKCS11Exception);
+        if (jPKCS11ExceptionClass != NULL) {
+            jConstructor = (*env)->GetMethodID(env, jPKCS11ExceptionClass, "<init>", "(J)V");
+            if (jConstructor != NULL) {
+                jErrorCode = ckULongToJLong(returnValue);
+                jPKCS11Exception = (jthrowable) (*env)->NewObject(env, jPKCS11ExceptionClass, jConstructor, jErrorCode);
+                if (jPKCS11Exception != NULL) {
+                    (*env)->Throw(env, jPKCS11Exception);
+                }
+            }
+        }
+        (*env)->DeleteLocalRef(env, jPKCS11ExceptionClass);
         return jErrorCode ;
     }
 }
 
 /*
- * this function simply throws a FileNotFoundException
- *
- * @param env Used to call JNI funktions and to get the Exception class.
- * @param jmessage The message string of the Exception object.
- */
-void throwFileNotFoundException(JNIEnv *env, jstring jmessage)
-{
-    jclass jFileNotFoundExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jFileNotFoundException;
-
-    jFileNotFoundExceptionClass = (*env)->FindClass(env, CLASS_FILE_NOT_FOUND_EXCEPTION);
-    assert(jFileNotFoundExceptionClass != 0);
-
-    jConstructor = (*env)->GetMethodID(env, jFileNotFoundExceptionClass, "<init>", "(Ljava/lang/String;)V");
-    assert(jConstructor != 0);
-    jFileNotFoundException = (jthrowable) (*env)->NewObject(env, jFileNotFoundExceptionClass, jConstructor, jmessage);
-    (*env)->Throw(env, jFileNotFoundException);
-}
-
-/*
- * this function simply throws an IOException
+ * This function simply throws an IOException
  *
  * @param env Used to call JNI funktions and to get the Exception class.
  * @param message The message string of the Exception object.
  */
-void throwIOException(JNIEnv *env, const char * message)
-{
-    jclass jIOExceptionClass;
-
-    jIOExceptionClass = (*env)->FindClass(env, CLASS_IO_EXCEPTION);
-    assert(jIOExceptionClass != 0);
-
-    (*env)->ThrowNew(env, jIOExceptionClass, message);
-}
-
-/*
- * this function simply throws an IOException and takes a unicode
- * messge.
- *
- * @param env Used to call JNI funktions and to get the Exception class.
- * @param message The unicode message string of the Exception object.
- */
-void throwIOExceptionUnicodeMessage(JNIEnv *env, const short *message)
+void throwIOException(JNIEnv *env, const char *message)
 {
-    jclass jIOExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jIOException;
-    jstring jmessage;
-    jsize length;
-    short *currentCharacter;
-
-    jIOExceptionClass = (*env)->FindClass(env, CLASS_IO_EXCEPTION);
-    assert(jIOExceptionClass != 0);
-
-    length = 0;
-    if (message != NULL) {
-        currentCharacter = (short *) message;
-        while (*(currentCharacter++) != 0) length++;
-    }
-
-    jmessage = (*env)->NewString(env, (const jchar *)message, length);
-
-    jConstructor = (*env)->GetMethodID(env, jIOExceptionClass, "<init>", "(Ljava/lang/String;)V");
-    assert(jConstructor != 0);
-    jIOException = (jthrowable) (*env)->NewObject(env, jIOExceptionClass, jConstructor, jmessage);
-    (*env)->Throw(env, jIOException);
+    JNU_ThrowByName(env, CLASS_IO_EXCEPTION, message);
 }
 
 /*
@@ -288,26 +234,9 @@
  * @param env Used to call JNI funktions and to get the Exception class.
  * @param jmessage The message string of the Exception object.
  */
-void throwPKCS11RuntimeException(JNIEnv *env, jstring jmessage)
+void throwPKCS11RuntimeException(JNIEnv *env, const char *message)
 {
-    jclass jPKCS11RuntimeExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jPKCS11RuntimeException;
-
-    jPKCS11RuntimeExceptionClass = (*env)->FindClass(env, CLASS_PKCS11RUNTIMEEXCEPTION);
-    assert(jPKCS11RuntimeExceptionClass != 0);
-
-    if (jmessage == NULL) {
-        jConstructor = (*env)->GetMethodID(env, jPKCS11RuntimeExceptionClass, "<init>", "()V");
-        assert(jConstructor != 0);
-        jPKCS11RuntimeException = (jthrowable) (*env)->NewObject(env, jPKCS11RuntimeExceptionClass, jConstructor);
-        (*env)->Throw(env, jPKCS11RuntimeException);
-    } else {
-        jConstructor = (*env)->GetMethodID(env, jPKCS11RuntimeExceptionClass, "<init>", "(Ljava/lang/String;)V");
-        assert(jConstructor != 0);
-        jPKCS11RuntimeException = (jthrowable) (*env)->NewObject(env, jPKCS11RuntimeExceptionClass, jConstructor, jmessage);
-        (*env)->Throw(env, jPKCS11RuntimeException);
-    }
+    JNU_ThrowByName(env, CLASS_PKCS11RUNTIMEEXCEPTION, message);
 }
 
 /*
@@ -318,9 +247,24 @@
  */
 void throwDisconnectedRuntimeException(JNIEnv *env)
 {
-    jstring jExceptionMessage = (*env)->NewStringUTF(env, "This object is not connected to a module.");
+    throwPKCS11RuntimeException(env, "This object is not connected to a module.");
+}
 
-    throwPKCS11RuntimeException(env, jExceptionMessage);
+/* This function frees the specified CK_ATTRIBUTE array.
+ *
+ * @param attrPtr pointer to the to-be-freed CK_ATTRIBUTE array.
+ * @param len the length of the array
+ */
+void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len)
+{
+    int i;
+
+    for (i=0; i<len; i++) {
+        if (attrPtr[i].pValue != NULL_PTR) {
+            free(attrPtr[i].pValue);
+        }
+    }
+    free(attrPtr);
 }
 
 /*
@@ -375,8 +319,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jboolean*) malloc((*ckpLength) * sizeof(jboolean));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetBooleanArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
+
     *ckpArray = (CK_BBOOL*) malloc ((*ckpLength) * sizeof(CK_BBOOL));
+    if (*ckpArray == NULL) {
+        free(jpTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jBooleanToCKBBool(jpTemp[i]);
     }
@@ -403,13 +361,26 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jbyte*) malloc((*ckpLength) * sizeof(jbyte));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetByteArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
 
     /* if CK_BYTE is the same size as jbyte, we save an additional copy */
     if (sizeof(CK_BYTE) == sizeof(jbyte)) {
         *ckpArray = (CK_BYTE_PTR) jpTemp;
     } else {
         *ckpArray = (CK_BYTE_PTR) malloc ((*ckpLength) * sizeof(CK_BYTE));
+        if (*ckpArray == NULL) {
+            free(jpTemp);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
         for (i=0; i<(*ckpLength); i++) {
             (*ckpArray)[i] = jByteToCKByte(jpTemp[i]);
         }
@@ -437,8 +408,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jTemp = (jlong*) malloc((*ckpLength) * sizeof(jlong));
+    if (jTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetLongArrayRegion(env, jArray, 0, *ckpLength, jTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jTemp);
+        return;
+    }
+
     *ckpArray = (CK_ULONG_PTR) malloc (*ckpLength * sizeof(CK_ULONG));
+    if (*ckpArray == NULL) {
+        free(jTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jLongToCKULong(jTemp[i]);
     }
@@ -465,8 +450,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jchar*) malloc((*ckpLength) * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetCharArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
+
     *ckpArray = (CK_CHAR_PTR) malloc (*ckpLength * sizeof(CK_CHAR));
+    if (*ckpArray == NULL) {
+        free(jpTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jCharToCKChar(jpTemp[i]);
     }
@@ -493,8 +492,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jTemp = (jchar*) malloc((*ckpLength) * sizeof(jchar));
+    if (jTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetCharArrayRegion(env, jArray, 0, *ckpLength, jTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jTemp);
+        return;
+    }
+
     *ckpArray = (CK_UTF8CHAR_PTR) malloc (*ckpLength * sizeof(CK_UTF8CHAR));
+    if (*ckpArray == NULL) {
+        free(jTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jCharToCKUTF8Char(jTemp[i]);
     }
@@ -521,8 +534,15 @@
     }
 
     pCharArray = (*env)->GetStringUTFChars(env, jArray, &isCopy);
+    if (pCharArray == NULL) { return; }
+
     *ckpLength = strlen(pCharArray);
     *ckpArray = (CK_UTF8CHAR_PTR) malloc((*ckpLength + 1) * sizeof(CK_UTF8CHAR));
+    if (*ckpArray == NULL) {
+        (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     strcpy((char*)*ckpArray, pCharArray);
     (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
 }
@@ -552,55 +572,36 @@
     jLength = (*env)->GetArrayLength(env, jArray);
     *ckpLength = jLongToCKULong(jLength);
     *ckpArray = (CK_ATTRIBUTE_PTR) malloc(*ckpLength * sizeof(CK_ATTRIBUTE));
+    if (*ckpArray == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     TRACE1(", converting %d attibutes", jLength);
     for (i=0; i<(*ckpLength); i++) {
         TRACE1(", getting %d. attibute", i);
         jAttribute = (*env)->GetObjectArrayElement(env, jArray, i);
+        if ((*env)->ExceptionCheck(env)) {
+            freeCKAttributeArray(*ckpArray, i);
+            return;
+        }
         TRACE1(", jAttribute = %d", jAttribute);
         TRACE1(", converting %d. attibute", i);
         (*ckpArray)[i] = jAttributeToCKAttribute(env, jAttribute);
+        if ((*env)->ExceptionCheck(env)) {
+            freeCKAttributeArray(*ckpArray, i);
+            return;
+        }
     }
     TRACE0("FINISHED\n");
 }
 
 /*
- * converts a jobjectArray to a CK_VOID_PTR array. The allocated memory has to be freed after
- * use!
- * NOTE: this function does not work and is not used yet
- *
- * @param env - used to call JNI funktions to get the array informtaion
- * @param jArray - the Java object array to convert
- * @param ckpArray - the reference, where the pointer to the new CK_VOID_PTR array will be stored
- * @param ckpLength - the reference, where the array length will be stored
- */
-/*
-void jObjectArrayToCKVoidPtrArray(JNIEnv *env, const jobjectArray jArray, CK_VOID_PTR_PTR *ckpArray, CK_ULONG_PTR ckpLength)
-{
-    jobject jTemp;
-    CK_ULONG i;
-
-    if(jArray == NULL) {
-        *ckpArray = NULL_PTR;
-        *ckpLength = 0L;
-        return;
-    }
-    *ckpLength = (*env)->GetArrayLength(env, jArray);
-    *ckpArray = (CK_VOID_PTR_PTR) malloc (*ckpLength * sizeof(CK_VOID_PTR));
-    for (i=0; i<(*ckpLength); i++) {
-        jTemp = (*env)->GetObjectArrayElement(env, jArray, i);
-        (*ckpArray)[i] = jObjectToCKVoidPtr(jTemp);
-    }
-    free(jTemp);
-}
-*/
-
-/*
  * converts a CK_BYTE array and its length to a jbyteArray.
  *
  * @param env - used to call JNI funktions to create the new Java array
  * @param ckpArray - the pointer to the CK_BYTE array to convert
  * @param ckpLength - the length of the array to convert
- * @return - the new Java byte array
+ * @return - the new Java byte array or NULL if error occurred
  */
 jbyteArray ckByteArrayToJByteArray(JNIEnv *env, const CK_BYTE_PTR ckpArray, CK_ULONG ckLength)
 {
@@ -613,17 +614,21 @@
         jpTemp = (jbyte*) ckpArray;
     } else {
         jpTemp = (jbyte*) malloc((ckLength) * sizeof(jbyte));
+        if (jpTemp == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         for (i=0; i<ckLength; i++) {
             jpTemp[i] = ckByteToJByte(ckpArray[i]);
         }
     }
 
     jArray = (*env)->NewByteArray(env, ckULongToJSize(ckLength));
-    (*env)->SetByteArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetByteArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
 
-    if (sizeof(CK_BYTE) != sizeof(jbyte)) {
-        free(jpTemp);
-    }
+    if (sizeof(CK_BYTE) != sizeof(jbyte)) { free(jpTemp); }
 
     return jArray ;
 }
@@ -643,11 +648,17 @@
     jlongArray jArray;
 
     jpTemp = (jlong*) malloc((ckLength) * sizeof(jlong));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckLongToJLong(ckpArray[i]);
     }
     jArray = (*env)->NewLongArray(env, ckULongToJSize(ckLength));
-    (*env)->SetLongArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetLongArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -668,11 +679,17 @@
     jcharArray jArray;
 
     jpTemp = (jchar*) malloc(ckLength * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckCharToJChar(ckpArray[i]);
     }
     jArray = (*env)->NewCharArray(env, ckULongToJSize(ckLength));
-    (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -693,11 +710,17 @@
     jcharArray jArray;
 
     jpTemp = (jchar*) malloc(ckLength * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckUTF8CharToJChar(ckpArray[i]);
     }
     jArray = (*env)->NewCharArray(env, ckULongToJSize(ckLength));
-    (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -736,12 +759,11 @@
     jboolean jValue;
 
     jValueObjectClass = (*env)->FindClass(env, "java/lang/Boolean");
-    assert(jValueObjectClass != 0);
+    if (jValueObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jValueObjectClass, "<init>", "(Z)V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jValue = ckBBoolToJBoolean(*ckpValue);
     jValueObject = (*env)->NewObject(env, jValueObjectClass, jConstructor, jValue);
-    assert(jValueObject != 0);
 
     return jValueObject ;
 }
@@ -761,12 +783,11 @@
     jlong jValue;
 
     jValueObjectClass = (*env)->FindClass(env, "java/lang/Long");
-    assert(jValueObjectClass != 0);
+    if (jValueObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jValueObjectClass, "<init>", "(J)V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jValue = ckULongToJLong(*ckpValue);
     jValueObject = (*env)->NewObject(env, jValueObjectClass, jConstructor, jValue);
-    assert(jValueObject != 0);
 
     return jValueObject ;
 }
@@ -787,11 +808,15 @@
     CK_BBOOL *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Boolean");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "booleanValue", "()Z");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallBooleanMethod(env, jObject, jValueMethod);
     ckpValue = (CK_BBOOL *) malloc(sizeof(CK_BBOOL));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jBooleanToCKBBool(jValue);
 
     return ckpValue ;
@@ -813,13 +838,16 @@
     CK_BYTE_PTR ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Byte");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "byteValue", "()B");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallByteMethod(env, jObject, jValueMethod);
     ckpValue = (CK_BYTE_PTR) malloc(sizeof(CK_BYTE));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jByteToCKByte(jValue);
-
     return ckpValue ;
 }
 
@@ -839,13 +867,16 @@
     CK_ULONG *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Integer");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "intValue", "()I");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallIntMethod(env, jObject, jValueMethod);
     ckpValue = (CK_ULONG *) malloc(sizeof(CK_ULONG));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jLongToCKLong(jValue);
-
     return ckpValue ;
 }
 
@@ -865,11 +896,15 @@
     CK_ULONG *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Long");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "longValue", "()J");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallLongMethod(env, jObject, jValueMethod);
     ckpValue = (CK_ULONG *) malloc(sizeof(CK_ULONG));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jLongToCKULong(jValue);
 
     return ckpValue ;
@@ -891,11 +926,15 @@
     CK_CHAR_PTR ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Char");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "charValue", "()C");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallCharMethod(env, jObject, jValueMethod);
     ckpValue = (CK_CHAR_PTR) malloc(sizeof(CK_CHAR));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jCharToCKChar(jValue);
 
     return ckpValue ;
@@ -913,124 +952,172 @@
  */
 void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *ckpLength)
 {
-    jclass jBooleanClass     = (*env)->FindClass(env, "java/lang/Boolean");
-    jclass jByteClass        = (*env)->FindClass(env, "java/lang/Byte");
-    jclass jCharacterClass   = (*env)->FindClass(env, "java/lang/Character");
-    jclass jClassClass = (*env)->FindClass(env, "java/lang/Class");
-    /* jclass jShortClass       = (*env)->FindClass(env, "java/lang/Short"); */
-    jclass jIntegerClass     = (*env)->FindClass(env, "java/lang/Integer");
-    jclass jLongClass        = (*env)->FindClass(env, "java/lang/Long");
-    /* jclass jFloatClass       = (*env)->FindClass(env, "java/lang/Float"); */
-    /* jclass jDoubleClass      = (*env)->FindClass(env, "java/lang/Double"); */
-    jclass jDateClass      = (*env)->FindClass(env, CLASS_DATE);
-    jclass jStringClass      = (*env)->FindClass(env, "java/lang/String");
-    jclass jStringBufferClass      = (*env)->FindClass(env, "java/lang/StringBuffer");
-    jclass jBooleanArrayClass = (*env)->FindClass(env, "[Z");
-    jclass jByteArrayClass    = (*env)->FindClass(env, "[B");
-    jclass jCharArrayClass    = (*env)->FindClass(env, "[C");
-    /* jclass jShortArrayClass   = (*env)->FindClass(env, "[S"); */
-    jclass jIntArrayClass     = (*env)->FindClass(env, "[I");
-    jclass jLongArrayClass    = (*env)->FindClass(env, "[J");
-    /* jclass jFloatArrayClass   = (*env)->FindClass(env, "[F"); */
-    /* jclass jDoubleArrayClass  = (*env)->FindClass(env, "[D"); */
-    jclass jObjectClass = (*env)->FindClass(env, "java/lang/Object");
-    /* jclass jObjectArrayClass = (*env)->FindClass(env, "[java/lang/Object"); */
-    /* ATTENTION: jObjectArrayClass is always NULL !! */
-    /* CK_ULONG ckArrayLength; */
-    /* CK_VOID_PTR *ckpElementObject; */
-    /* CK_ULONG ckElementLength; */
-    /* CK_ULONG i; */
+    jclass jLongClass, jBooleanClass, jByteArrayClass, jCharArrayClass;
+    jclass jByteClass, jDateClass, jCharacterClass, jIntegerClass;
+    jclass jBooleanArrayClass, jIntArrayClass, jLongArrayClass;
+    jclass jStringClass;
+    jclass jObjectClass, jClassClass;
     CK_VOID_PTR ckpVoid = *ckpObjectPtr;
     jmethodID jMethod;
     jobject jClassObject;
     jstring jClassNameString;
-    jstring jExceptionMessagePrefix;
-    jobject jExceptionMessageStringBuffer;
-    jstring jExceptionMessage;
+    char *classNameString, *exceptionMsgPrefix, *exceptionMsg;
 
     TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtrPtr");
     if (jObject == NULL) {
         *ckpObjectPtr = NULL;
         *ckpLength = 0;
-    } else if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
+        return;
+    }
+
+    jLongClass = (*env)->FindClass(env, "java/lang/Long");
+    if (jLongClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
         *ckpObjectPtr = jLongObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
         TRACE1("<converted long value %X>", *((CK_ULONG *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
+        return;
+    }
+
+    jBooleanClass = (*env)->FindClass(env, "java/lang/Boolean");
+    if (jBooleanClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
         *ckpObjectPtr = jBooleanObjectToCKBBoolPtr(env, jObject);
         *ckpLength = sizeof(CK_BBOOL);
         TRACE0(" <converted boolean value ");
         TRACE0((*((CK_BBOOL *) *ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
-    } else if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
+        return;
+    }
+
+    jByteArrayClass = (*env)->FindClass(env, "[B");
+    if (jByteArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
         jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
+        return;
+    }
+
+    jCharArrayClass = (*env)->FindClass(env, "[C");
+    if (jCharArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
         jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
+        return;
+    }
+
+    jByteClass = (*env)->FindClass(env, "java/lang/Byte");
+    if (jByteClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
         *ckpObjectPtr = jByteObjectToCKBytePtr(env, jObject);
         *ckpLength = sizeof(CK_BYTE);
         TRACE1("<converted byte value %X>", *((CK_BYTE *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
+        return;
+    }
+
+    jDateClass = (*env)->FindClass(env, CLASS_DATE);
+    if (jDateClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
         *ckpObjectPtr = jDateObjectPtrToCKDatePtr(env, jObject);
         *ckpLength = sizeof(CK_DATE);
-        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year,
-                                                    (*((CK_DATE *) *ckpObjectPtr)).month,
-                                                    (*((CK_DATE *) *ckpObjectPtr)).day);
-    } else if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
+        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year, (*((CK_DATE *) *ckpObjectPtr)).month, (*((CK_DATE *) *ckpObjectPtr)).day);
+        return;
+    }
+
+    jCharacterClass = (*env)->FindClass(env, "java/lang/Character");
+    if (jCharacterClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
         *ckpObjectPtr = jCharObjectToCKCharPtr(env, jObject);
         *ckpLength = sizeof(CK_UTF8CHAR);
         TRACE1("<converted char value %c>", *((CK_CHAR *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
+        return;
+    }
+
+    jIntegerClass = (*env)->FindClass(env, "java/lang/Integer");
+    if (jIntegerClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
         *ckpObjectPtr = jIntegerObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
         TRACE1("<converted integer value %X>", *((CK_ULONG *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
+        return;
+    }
+
+    jBooleanArrayClass = (*env)->FindClass(env, "[Z");
+    if (jBooleanArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
         jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
+        return;
+    }
+
+    jIntArrayClass = (*env)->FindClass(env, "[I");
+    if (jIntArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
         jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
+        return;
+    }
+
+    jLongArrayClass = (*env)->FindClass(env, "[J");
+    if (jLongArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
         jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
+        return;
+    }
+
+    jStringClass = (*env)->FindClass(env, "java/lang/String");
+    if (jStringClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
         jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
+        return;
+    }
 
-        /* a Java object array is not used by CK_ATTRIBUTE by now... */
-/*  } else if ((*env)->IsInstanceOf(env, jObject, jObjectArrayClass)) {
-        ckArrayLength = (*env)->GetArrayLength(env, (jarray) jObject);
-        ckpObjectPtr = (CK_VOID_PTR_PTR) malloc(sizeof(CK_VOID_PTR) * ckArrayLength);
-        *ckpLength = 0;
-        for (i = 0; i < ckArrayLength; i++) {
-            jObjectToPrimitiveCKObjectPtrPtr(env, (*env)->GetObjectArrayElement(env, (jarray) jObject, i),
-                     ckpElementObject, &ckElementLength);
-            (*ckpObjectPtr)[i] = *ckpElementObject;
-            *ckpLength += ckElementLength;
-        }
-*/
-    } else {
-        /* type of jObject unknown, throw PKCS11RuntimeException */
-        jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
-        assert(jMethod != 0);
-        jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
-        assert(jClassObject != 0);
-        jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
-        assert(jMethod != 0);
-        jClassNameString = (jstring)
-                (*env)->CallObjectMethod(env, jClassObject, jMethod);
-        assert(jClassNameString != 0);
-        jExceptionMessagePrefix = (*env)->NewStringUTF(env, "Java object of this class cannot be converted to native PKCS#11 type: ");
-        jMethod = (*env)->GetMethodID(env, jStringBufferClass, "<init>", "(Ljava/lang/String;)V");
-        assert(jMethod != 0);
-        jExceptionMessageStringBuffer = (*env)->NewObject(env, jStringBufferClass, jMethod, jExceptionMessagePrefix);
-        assert(jClassNameString != 0);
-        jMethod = (*env)->GetMethodID(env, jStringBufferClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
-        assert(jMethod != 0);
-        jExceptionMessage = (jstring)
-                 (*env)->CallObjectMethod(env, jExceptionMessageStringBuffer, jMethod, jClassNameString);
-        assert(jExceptionMessage != 0);
-
-        throwPKCS11RuntimeException(env, jExceptionMessage);
-
-        *ckpObjectPtr = NULL;
-        *ckpLength = 0;
+    /* type of jObject unknown, throw PKCS11RuntimeException */
+    jObjectClass = (*env)->FindClass(env, "java/lang/Object");
+    if (jObjectClass == NULL) { return; }
+    jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
+    if (jMethod == NULL) { return; }
+    jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
+    assert(jClassObject != 0);
+    jClassClass = (*env)->FindClass(env, "java/lang/Class");
+    if (jClassClass == NULL) { return; }
+    jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
+    if (jMethod == NULL) { return; }
+    jClassNameString = (jstring)
+        (*env)->CallObjectMethod(env, jClassObject, jMethod);
+    assert(jClassNameString != 0);
+    classNameString = (char*)
+        (*env)->GetStringUTFChars(env, jClassNameString, NULL);
+    if (classNameString == NULL) { return; }
+    exceptionMsgPrefix = "Java object of this class cannot be converted to native PKCS#11 type: ";
+    exceptionMsg = (char *)
+        malloc((strlen(exceptionMsgPrefix) + strlen(classNameString) + 1));
+    if (exceptionMsg == NULL) {
+        (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
     }
+    strcpy(exceptionMsg, exceptionMsgPrefix);
+    strcat(exceptionMsg, classNameString);
+    (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
+    throwPKCS11RuntimeException(env, exceptionMsg);
+    free(exceptionMsg);
+    *ckpObjectPtr = NULL;
+    *ckpLength = 0;
 
     TRACE0("FINISHED\n");
 }
+
+#ifdef P11_MEMORYDEBUG
+
+#undef malloc
+#undef free
+
+void *p11malloc(size_t c, char *file, int line) {
+    void *p = malloc(c);
+    printf("malloc\t%08x\t%d\t%s:%d\n", p, c, file, line); fflush(stdout);
+    return p;
+}
+
+void p11free(void *p, char *file, int line) {
+    printf("free\t%08x\t\t%s:%d\n", p, file, line); fflush(stdout);
+    free(p);
+}
+
+#endif
+
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -154,6 +154,7 @@
 
 #include "pkcs11.h"
 #include <jni.h>
+#include <jni_util.h>
 
 #define MAX_STACK_BUFFER_LEN (4 * 1024)
 #define MAX_HEAP_BUFFER_LEN (64 * 1024)
@@ -277,12 +278,14 @@
  */
 
 jlong ckAssertReturnValueOK(JNIEnv *env, CK_RV returnValue);
-void throwPKCS11RuntimeException(JNIEnv *env, jstring jmessage);
-void throwFileNotFoundException(JNIEnv *env, jstring jmessage);
 void throwIOException(JNIEnv *env, const char *message);
-void throwIOExceptionUnicodeMessage(JNIEnv *env, const short *message);
+void throwPKCS11RuntimeException(JNIEnv *env, const char *message);
 void throwDisconnectedRuntimeException(JNIEnv *env);
 
+/* function to free CK_ATTRIBUTE array
+ */
+void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len);
+
 /* funktions to convert Java arrays to a CK-type array and the array length */
 
 void jBooleanArrayToCKBBoolArray(JNIEnv *env, const jbooleanArray jArray, CK_BBOOL **ckpArray, CK_ULONG_PTR ckLength);
@@ -438,3 +441,15 @@
 extern jobject jInitArgsObject;
 extern CK_C_INITIALIZE_ARGS_PTR ckpGlobalInitArgs;
 #endif /* NO_CALLBACKS */
+
+#ifdef P11_MEMORYDEBUG
+#include <stdlib.h>
+
+/* Simple malloc/free dumper */
+void *p11malloc(size_t c, char *file, int line);
+void p11free(void *p, char *file, int line);
+
+#define malloc(c)       (p11malloc((c), __FILE__, __LINE__))
+#define free(c)         (p11free((c), __FILE__, __LINE__))
+
+#endif
--- a/jdk/src/solaris/classes/sun/awt/X11/XFontPeer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XFontPeer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -27,9 +27,6 @@
 import sun.awt.PlatformFont;
 import java.awt.GraphicsEnvironment;
 
-/* FIX ME */
-import sun.awt.motif.MFontConfiguration;
-
 public class XFontPeer extends PlatformFont {
 
     /*
@@ -51,10 +48,6 @@
 
     public XFontPeer(String name, int style){
         super(name, style);
-
-        if (fontConfig != null){
-            xfsname = ((MFontConfiguration) fontConfig).getMotifFontSet(familyName, style);
-        }
     }
 
     protected char getMissingGlyphCharacter() {
--- a/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java	Fri Apr 10 13:05:12 2009 -0700
@@ -15,7 +15,7 @@
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
- * along with this work; if not, write to the Free Software Foundation,
+ * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
@@ -87,6 +87,7 @@
             return true;
         }
 
+        setFontConfiguration();
         readFcInfo();
         if (fcCompFonts == null) {
             fcCompFonts = FontManager.loadFontConfig();
@@ -172,7 +173,7 @@
 
     @Override
     public FontDescriptor[] getFontDescriptors(String fontName, int style) {
-        throw new InternalError("Not implemented");
+        return new FontDescriptor[0];
     }
 
     @Override
--- a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -16,7 +16,7 @@
  *
  * 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 conne02110-1301 USA.
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
--- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Fri Apr 10 13:05:12 2009 -0700
@@ -661,6 +661,12 @@
                 }
             }
         } else if (category == OrientationRequested.class) {
+            if (flavor.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT) ||
+                flavor.equals(DocFlavor.URL.POSTSCRIPT) ||
+                flavor.equals(DocFlavor.BYTE_ARRAY.POSTSCRIPT)) {
+                return null;
+            }
+
             boolean revPort = false;
             OrientationRequested[] orientSup = null;
 
--- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Fri Apr 10 13:05:12 2009 -0700
@@ -362,10 +362,10 @@
                  mOptions += " number-up="+nUp.getValue();
              }
 
-             if (orient == OrientationRequested.LANDSCAPE &&
+             if (orient != OrientationRequested.PORTRAIT &&
                  (flavor != null) &&
                  !flavor.equals(DocFlavor.SERVICE_FORMATTED.PAGEABLE)) {
-                 mOptions += " landscape";
+                 mOptions += " orientation-requested="+orient.getValue();
              }
 
              if (sides != null) {
--- a/jdk/src/solaris/native/java/net/NetworkInterface.c	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/solaris/native/java/net/NetworkInterface.c	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java	Fri Apr 10 13:05:12 2009 -0700
@@ -61,18 +61,10 @@
              * been opened and its fonts loaded.
              * Also note this usage is only enabled if a private flag is set.
              */
-            if ("98".equals(osName) || "Me".equals(osName)) {
-                localeMap.put("dialoginput.plain.japanese", "\uff2d\uff33 \u660e\u671d");
-                localeMap.put("dialoginput.bold.japanese", "\uff2d\uff33 \u660e\u671d");
-                localeMap.put("dialoginput.italic.japanese", "\uff2d\uff33 \u660e\u671d");
-                localeMap.put("dialoginput.bolditalic.japanese", "\uff2d\uff33 \u660e\u671d");
-            } else {
-
-                localeMap.put("dialoginput.plain.japanese", "MS Mincho");
-                localeMap.put("dialoginput.bold.japanese", "MS Mincho");
-                localeMap.put("dialoginput.italic.japanese", "MS Mincho");
-                localeMap.put("dialoginput.bolditalic.japanese", "MS Mincho");
-            }
+            localeMap.put("dialoginput.plain.japanese", "MS Mincho");
+            localeMap.put("dialoginput.bold.japanese", "MS Mincho");
+            localeMap.put("dialoginput.italic.japanese", "MS Mincho");
+            localeMap.put("dialoginput.bolditalic.japanese", "MS Mincho");
         }
         reorderMap = new HashMap();
         reorderMap.put("UTF-8.hi", "devanagari");
--- a/jdk/src/windows/classes/sun/awt/windows/fontconfig.98.properties	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-#
-# 
-# Copyright 2003-2004 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-
-# Version
-
-version=1
-
-# Component Font Mappings
-
-allfonts.chinese-ms936=SimSun
-allfonts.dingbats=Wingdings
-allfonts.lucida=Lucida Sans Regular
-allfonts.symbol=Symbol
-allfonts.thai=Lucida Sans Regular
-
-serif.plain.alphabetic=Times New Roman
-serif.plain.chinese-ms950=MingLiU
-serif.plain.hebrew=David
-serif.plain.japanese=\uff2d\uff33 \u660e\u671d
-serif.plain.korean=Batang
-
-serif.bold.alphabetic=Times New Roman Bold
-serif.bold.chinese-ms950=PMingLiU
-serif.bold.hebrew=David Bold
-serif.bold.japanese=\uff2d\uff33 \u660e\u671d
-serif.bold.korean=Batang
-
-serif.italic.alphabetic=Times New Roman Italic
-serif.italic.chinese-ms950=PMingLiU
-serif.italic.hebrew=David
-serif.italic.japanese=\uff2d\uff33 \u660e\u671d
-serif.italic.korean=Batang
-
-serif.bolditalic.alphabetic=Times New Roman Bold Italic
-serif.bolditalic.chinese-ms950=PMingLiU
-serif.bolditalic.hebrew=David Bold
-serif.bolditalic.japanese=\uff2d\uff33 \u660e\u671d
-serif.bolditalic.korean=Batang
-
-sansserif.plain.alphabetic=Arial
-sansserif.plain.chinese-ms950=MingLiU
-sansserif.plain.hebrew=David
-sansserif.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.plain.korean=Gulim
-
-sansserif.bold.alphabetic=Arial Bold
-sansserif.bold.chinese-ms950=PMingLiU
-sansserif.bold.hebrew=David Bold
-sansserif.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.bold.korean=Gulim
-
-sansserif.italic.alphabetic=Arial Italic
-sansserif.italic.chinese-ms950=PMingLiU
-sansserif.italic.hebrew=David
-sansserif.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.italic.korean=Gulim
-
-sansserif.bolditalic.alphabetic=Arial Bold Italic
-sansserif.bolditalic.chinese-ms950=PMingLiU
-sansserif.bolditalic.hebrew=David Bold
-sansserif.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.bolditalic.korean=Gulim
-
-monospaced.plain.alphabetic=Courier New
-monospaced.plain.chinese-ms950=MingLiU
-monospaced.plain.hebrew=David
-monospaced.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.plain.korean=GulimChe
-
-monospaced.bold.alphabetic=Courier New Bold
-monospaced.bold.chinese-ms950=PMingLiU
-monospaced.bold.hebrew=David Bold
-monospaced.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.bold.korean=GulimChe
-
-monospaced.italic.alphabetic=Courier New Italic
-monospaced.italic.chinese-ms950=PMingLiU
-monospaced.italic.hebrew=David
-monospaced.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.italic.korean=GulimChe
-
-monospaced.bolditalic.alphabetic=Courier New Bold Italic
-monospaced.bolditalic.chinese-ms950=PMingLiU
-monospaced.bolditalic.hebrew=David Bold
-monospaced.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.bolditalic.korean=GulimChe
-
-dialog.plain.alphabetic=Arial
-dialog.plain.chinese-ms950=MingLiU
-dialog.plain.hebrew=David
-dialog.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.plain.korean=Gulim
-
-dialog.bold.alphabetic=Arial Bold
-dialog.bold.chinese-ms950=PMingLiU
-dialog.bold.hebrew=David Bold
-dialog.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.bold.korean=Gulim
-
-dialog.italic.alphabetic=Arial Italic
-dialog.italic.chinese-ms950=PMingLiU
-dialog.italic.hebrew=David
-dialog.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.italic.korean=Gulim
-
-dialog.bolditalic.alphabetic=Arial Bold Italic
-dialog.bolditalic.chinese-ms950=PMingLiU
-dialog.bolditalic.hebrew=David Bold
-dialog.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.bolditalic.korean=Gulim
-
-dialoginput.plain.alphabetic=Courier New
-dialoginput.plain.chinese-ms950=MingLiU
-dialoginput.plain.hebrew=David
-dialoginput.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.plain.korean=Gulim
-
-dialoginput.bold.alphabetic=Courier New Bold
-dialoginput.bold.chinese-ms950=PMingLiU
-dialoginput.bold.hebrew=David Bold
-dialoginput.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.bold.korean=Gulim
-
-dialoginput.italic.alphabetic=Courier New Italic
-dialoginput.italic.chinese-ms950=PMingLiU
-dialoginput.italic.hebrew=David
-dialoginput.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.italic.korean=Gulim
-
-dialoginput.bolditalic.alphabetic=Courier New Bold Italic
-dialoginput.bolditalic.chinese-ms950=PMingLiU
-dialoginput.bolditalic.hebrew=David Bold
-dialoginput.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.bolditalic.korean=Gulim
-
-# Search Sequences
-
-sequence.allfonts=alphabetic/default,dingbats,symbol
-
-sequence.serif.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.sansserif.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.monospaced.GBK=chinese-ms936,alphabetic/1252,dingbats,symbol
-sequence.dialog.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.dialoginput.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-
-sequence.serif.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.sansserif.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.monospaced.x-windows-950=chinese-ms950,alphabetic/1252,dingbats,symbol
-sequence.dialog.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.dialoginput.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-
-sequence.allfonts.windows-1255=hebrew,alphabetic/1252,dingbats,symbol
-
-sequence.serif.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.sansserif.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.monospaced.windows-31j=japanese,alphabetic/1252,dingbats,symbol
-sequence.dialog.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.dialoginput.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-
-sequence.serif.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.sansserif.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.monospaced.x-windows-949=korean,alphabetic/1252,dingbats,symbol
-sequence.dialog.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.dialoginput.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-
-sequence.allfonts.x-windows-874=alphabetic/1252,thai,dingbats,symbol
-
-sequence.fallback=lucida
-
-# Exclusion Ranges
-
-exclusion.alphabetic=0700-1e9f,1f00-20ab,20ad-f8ff
-exclusion.hebrew=0041-005a,0060-007a,007f-00ff,20ac-20ac
-
-# Monospaced to Proportional width variant mapping
-# (Experimental private syntax)
-proportional.\uff2d\uff33_\u30b4\u30b7\u30c3\u30af=\uff2d\uff33 \uff30\u30b4\u30b7\u30c3\u30af
-proportional.\uff2d\uff33_\u660e\u671d=\uff2d\uff33 \uff30\u660e\u671d
-proportional.MingLiU=PMingLiU
-
-# Font File Names
-
-filename.Arial=ARIAL.TTF
-filename.Arial_Bold=ARIALBD.TTF
-filename.Arial_Italic=ARIALI.TTF
-filename.Arial_Bold_Italic=ARIALBI.TTF
-
-filename.Courier_New=COUR.TTF
-filename.Courier_New_Bold=COURBD.TTF
-filename.Courier_New_Italic=COURI.TTF
-filename.Courier_New_Bold_Italic=COURBI.TTF
-
-filename.Times_New_Roman=TIMES.TTF
-filename.Times_New_Roman_Bold=TIMESBD.TTF
-filename.Times_New_Roman_Italic=TIMESI.TTF
-filename.Times_New_Roman_Bold_Italic=TIMESBI.TTF
-
-filename.SimSun=SIMSUN.TTF
-
-filename.MingLiU=MINGLIU.TTC
-filename.PMingLiU=MINGLIU.TTC
-
-filename.David=DAVID.TTF
-filename.David_Bold=DAVIDBD.TTF
-
-filename.\uff2d\uff33_\u660e\u671d=MSMINCHO.TTC
-filename.\uff2d\uff33_\uff30\u660e\u671d=MSMINCHO.TTC
-filename.\uff2d\uff33_\u30b4\u30b7\u30c3\u30af=MSGOTHIC.TTC
-filename.\uff2d\uff33_\uff30\u30b4\u30b7\u30c3\u30af=MSGOTHIC.TTC
-
-filename.Gulim=gulim.TTC
-filename.Batang=batang.TTC
-filename.GulimChe=gulim.TTC
-
-filename.Lucida_Sans_Regular=LucidaSansRegular.ttf
-filename.Symbol=SYMBOL.TTF
-filename.Wingdings=WINGDING.TTF
-
--- a/jdk/src/windows/classes/sun/awt/windows/fontconfig.Me.properties	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-#
-# 
-# Copyright 2003-2004 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-
-# Version
-
-version=1
-
-# Component Font Mappings
-
-allfonts.chinese-ms936=SimSun
-allfonts.dingbats=Wingdings
-allfonts.lucida=Lucida Sans Regular
-allfonts.symbol=Symbol
-allfonts.thai=Lucida Sans Regular
-
-serif.plain.alphabetic=Times New Roman
-serif.plain.chinese-ms950=MingLiU
-serif.plain.hebrew=David
-serif.plain.japanese=\uff2d\uff33 \u660e\u671d
-serif.plain.korean=Batang
-
-serif.bold.alphabetic=Times New Roman Bold
-serif.bold.chinese-ms950=PMingLiU
-serif.bold.hebrew=David Bold
-serif.bold.japanese=\uff2d\uff33 \u660e\u671d
-serif.bold.korean=Batang
-
-serif.italic.alphabetic=Times New Roman Italic
-serif.italic.chinese-ms950=PMingLiU
-serif.italic.hebrew=David
-serif.italic.japanese=\uff2d\uff33 \u660e\u671d
-serif.italic.korean=Batang
-
-serif.bolditalic.alphabetic=Times New Roman Bold Italic
-serif.bolditalic.chinese-ms950=PMingLiU
-serif.bolditalic.hebrew=David Bold
-serif.bolditalic.japanese=\uff2d\uff33 \u660e\u671d
-serif.bolditalic.korean=Batang
-
-sansserif.plain.alphabetic=Arial
-sansserif.plain.chinese-ms950=MingLiU
-sansserif.plain.hebrew=David
-sansserif.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.plain.korean=Gulim
-
-sansserif.bold.alphabetic=Arial Bold
-sansserif.bold.chinese-ms950=PMingLiU
-sansserif.bold.hebrew=David Bold
-sansserif.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.bold.korean=Gulim
-
-sansserif.italic.alphabetic=Arial Italic
-sansserif.italic.chinese-ms950=PMingLiU
-sansserif.italic.hebrew=David
-sansserif.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.italic.korean=Gulim
-
-sansserif.bolditalic.alphabetic=Arial Bold Italic
-sansserif.bolditalic.chinese-ms950=PMingLiU
-sansserif.bolditalic.hebrew=David Bold
-sansserif.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-sansserif.bolditalic.korean=Gulim
-
-monospaced.plain.alphabetic=Courier New
-monospaced.plain.chinese-ms950=MingLiU
-monospaced.plain.hebrew=David
-monospaced.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.plain.korean=GulimChe
-
-monospaced.bold.alphabetic=Courier New Bold
-monospaced.bold.chinese-ms950=PMingLiU
-monospaced.bold.hebrew=David Bold
-monospaced.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.bold.korean=GulimChe
-
-monospaced.italic.alphabetic=Courier New Italic
-monospaced.italic.chinese-ms950=PMingLiU
-monospaced.italic.hebrew=David
-monospaced.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.italic.korean=GulimChe
-
-monospaced.bolditalic.alphabetic=Courier New Bold Italic
-monospaced.bolditalic.chinese-ms950=PMingLiU
-monospaced.bolditalic.hebrew=David Bold
-monospaced.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-monospaced.bolditalic.korean=GulimChe
-
-dialog.plain.alphabetic=Arial
-dialog.plain.chinese-ms950=MingLiU
-dialog.plain.hebrew=David
-dialog.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.plain.korean=Gulim
-
-dialog.bold.alphabetic=Arial Bold
-dialog.bold.chinese-ms950=PMingLiU
-dialog.bold.hebrew=David Bold
-dialog.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.bold.korean=Gulim
-
-dialog.italic.alphabetic=Arial Italic
-dialog.italic.chinese-ms950=PMingLiU
-dialog.italic.hebrew=David
-dialog.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.italic.korean=Gulim
-
-dialog.bolditalic.alphabetic=Arial Bold Italic
-dialog.bolditalic.chinese-ms950=PMingLiU
-dialog.bolditalic.hebrew=David Bold
-dialog.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialog.bolditalic.korean=Gulim
-
-dialoginput.plain.alphabetic=Courier New
-dialoginput.plain.chinese-ms950=MingLiU
-dialoginput.plain.hebrew=David
-dialoginput.plain.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.plain.korean=Gulim
-
-dialoginput.bold.alphabetic=Courier New Bold
-dialoginput.bold.chinese-ms950=PMingLiU
-dialoginput.bold.hebrew=David Bold
-dialoginput.bold.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.bold.korean=Gulim
-
-dialoginput.italic.alphabetic=Courier New Italic
-dialoginput.italic.chinese-ms950=PMingLiU
-dialoginput.italic.hebrew=David
-dialoginput.italic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.italic.korean=Gulim
-
-dialoginput.bolditalic.alphabetic=Courier New Bold Italic
-dialoginput.bolditalic.chinese-ms950=PMingLiU
-dialoginput.bolditalic.hebrew=David Bold
-dialoginput.bolditalic.japanese=\uff2d\uff33 \u30b4\u30b7\u30c3\u30af
-dialoginput.bolditalic.korean=Gulim
-
-# Search Sequences
-
-sequence.allfonts=alphabetic/default,dingbats,symbol
-
-sequence.serif.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.sansserif.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.monospaced.GBK=chinese-ms936,alphabetic/1252,dingbats,symbol
-sequence.dialog.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-sequence.dialoginput.GBK=alphabetic/1252,chinese-ms936,dingbats,symbol
-
-sequence.serif.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.sansserif.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.monospaced.x-windows-950=chinese-ms950,alphabetic/1252,dingbats,symbol
-sequence.dialog.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-sequence.dialoginput.x-windows-950=alphabetic/1252,chinese-ms950,dingbats,symbol
-
-sequence.allfonts.windows-1255=hebrew,alphabetic/1252,dingbats,symbol
-
-sequence.serif.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.sansserif.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.monospaced.windows-31j=japanese,alphabetic/1252,dingbats,symbol
-sequence.dialog.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-sequence.dialoginput.windows-31j=alphabetic/1252,japanese,dingbats,symbol
-
-sequence.serif.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.sansserif.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.monospaced.x-windows-949=korean,alphabetic/1252,dingbats,symbol
-sequence.dialog.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-sequence.dialoginput.x-windows-949=alphabetic/1252,korean,dingbats,symbol
-
-sequence.allfonts.x-windows-874=alphabetic/1252,thai,dingbats,symbol
-
-sequence.fallback=lucida
-
-# Exclusion Ranges
-
-exclusion.alphabetic=0700-1e9f,1f00-20ab,20ad-f8ff
-exclusion.hebrew=0041-005a,0060-007a,007f-00ff,20ac-20ac
-
-# Monospaced to Proportional width variant mapping
-# (Experimental private syntax)
-proportional.\uff2d\uff33_\u30b4\u30b7\u30c3\u30af=\uff2d\uff33 \uff30\u30b4\u30b7\u30c3\u30af
-proportional.\uff2d\uff33_\u660e\u671d=\uff2d\uff33 \uff30\u660e\u671d
-proportional.MingLiU=PMingLiU
-
-# Font File Names
-
-filename.Arial=ARIAL.TTF
-filename.Arial_Bold=ARIALBD.TTF
-filename.Arial_Italic=ARIALI.TTF
-filename.Arial_Bold_Italic=ARIALBI.TTF
-
-filename.Courier_New=COUR.TTF
-filename.Courier_New_Bold=COURBD.TTF
-filename.Courier_New_Italic=COURI.TTF
-filename.Courier_New_Bold_Italic=COURBI.TTF
-
-filename.Times_New_Roman=TIMES.TTF
-filename.Times_New_Roman_Bold=TIMESBD.TTF
-filename.Times_New_Roman_Italic=TIMESI.TTF
-filename.Times_New_Roman_Bold_Italic=TIMESBI.TTF
-
-filename.SimSun=SIMSUN.TTF
-
-filename.MingLiU=MINGLIU.TTC
-filename.PMingLiU=MINGLIU.TTC
-
-filename.David=DAVID.TTF
-filename.David_Bold=DAVIDBD.TTF
-
-filename.\uff2d\uff33_\u660e\u671d=MSMINCHO.TTC
-filename.\uff2d\uff33_\uff30\u660e\u671d=MSMINCHO.TTC
-filename.\uff2d\uff33_\u30b4\u30b7\u30c3\u30af=MSGOTHIC.TTC
-filename.\uff2d\uff33_\uff30\u30b4\u30b7\u30c3\u30af=MSGOTHIC.TTC
-
-filename.Gulim=gulim.TTC
-filename.Batang=batang.TTC
-filename.GulimChe=gulim.TTC
-
-filename.Lucida_Sans_Regular=LucidaSansRegular.ttf
-filename.Symbol=SYMBOL.TTF
-filename.Wingdings=WINGDING.TTF
-
--- a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -16,7 +16,7 @@
  *
  * 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 conne02110-1301 USA.
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
--- a/jdk/src/windows/native/sun/windows/awt.rc	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/windows/native/sun/windows/awt.rc	Fri Apr 10 13:05:12 2009 -0700
@@ -23,7 +23,7 @@
 // have any questions.
 //
 
-#include "afxres.h"
+#include "windows.h"
 
 // Need 2 defines so macro argument to XSTR will get expanded before quoting.
 #define XSTR(x) STR(x)
--- a/jdk/src/windows/resource/version.rc	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/src/windows/resource/version.rc	Fri Apr 10 13:05:12 2009 -0700
@@ -23,7 +23,7 @@
 // have any questions.
 //
 
-#include "afxres.h"
+#include "windows.h"
 
 // Need 2 defines so macro argument to XSTR will get expanded before quoting.
 #define XSTR(x) STR(x)
--- a/jdk/test/Makefile	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/Makefile	Fri Apr 10 13:05:12 2009 -0700
@@ -1,12 +1,44 @@
 #
-# Makefile to run jtreg
+# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Sun designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# Makefile to run various jdk tests
 #
 
 # Get OS/ARCH specifics
 OSNAME = $(shell uname -s)
+
+# Commands to run on paths to make mixed paths for java on windows
+GETMIXEDPATH=echo
+
+# Location of developer shared files
+SLASH_JAVA = /java
+
+# Platform specific settings
 ifeq ($(OSNAME), SunOS)
   PLATFORM = solaris
-  JCT_PLATFORM = solaris
   ARCH = $(shell uname -p)
   ifeq ($(ARCH), i386)
     ARCH=i586
@@ -14,97 +46,403 @@
 endif
 ifeq ($(OSNAME), Linux)
   PLATFORM = linux
-  JCT_PLATFORM = linux
   ARCH = $(shell uname -m)
   ifeq ($(ARCH), i386)
     ARCH=i586
   endif
 endif
-ifeq ($(OSNAME), Windows_NT)
+
+# Cannot trust uname output
+ifneq ($(PROCESSOR_IDENTIFIER), )
   PLATFORM = windows
-  JCT_PLATFORM = win32
-  ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)),ia64)
-    ARCH=ia64
+  SLASH_JAVA = J:
+  # A variety of ways to say X64 arch :^(
+  PROC_ARCH:=$(word 1, $(PROCESSOR_IDENTIFIER))
+  PROC_ARCH:=$(subst x86,X86,$(PROC_ARCH))
+  PROC_ARCH:=$(subst x64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst AMD64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst amd64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst EM64T,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst em64t,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst intel64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst Intel64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst INTEL64,X64,$(PROC_ARCH))
+  PROC_ARCH:=$(subst ia64,IA64,$(PROC_ARCH))
+  ifeq ($(PROC_ARCH),IA64)
+    ARCH = ia64
   else
-    ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)),AMD64)
-      ARCH=x64
+    ifeq ($(PROC_ARCH),X64)
+      ARCH = x64
     else
-      ifeq ($(word 1, $(PROCESSOR_IDENTIFIER)),EM64T)
-        ARCH=x64
-      else
-        ARCH=i586
-      endif
+      ARCH = i586
     endif
   endif
+  EXESUFFIX = .exe
+  # These need to be different depending on MKS or CYGWIN
+  ifeq ($(findstring cygdrive,$(shell (cd C:/ && pwd))), )
+    GETMIXEDPATH=dosname -s
+  else
+    GETMIXEDPATH=cygpath -m -s
+  endif
 endif
 
+# Utilities used
+CD    = cd
+CP    = cp
+ECHO  = echo
+MKDIR = mkdir
+ZIP   = zip
+
 # Root of this test area (important to use full paths in some places)
 TEST_ROOT := $(shell pwd)
 
-# Default bundle of all test results (passed or not)
-JPRT_ARCHIVE_BUNDLE=$(TEST_ROOT)/JPRT_ARCHIVE_BUNDLE.zip
+# Root of all test results
+ifdef ALT_OUTPUTDIR
+  ABS_OUTPUTDIR = $(ALT_OUTPUTDIR)
+else
+  ABS_OUTPUTDIR = $(TEST_ROOT)/../build/$(PLATFORM)-$(ARCH)
+endif
+ABS_BUILD_ROOT = $(ABS_OUTPUTDIR)
+ABS_TEST_OUTPUT_DIR := $(ABS_BUILD_ROOT)/testoutput
 
-# Default home for JTREG
-ifeq ($(PLATFORM), windows)
-  JT_HOME = J:/svc/jct-tools3.2.2_02
-  JTREG_KEY_OPTION=-k:!ignore
-else
-  JT_HOME = /java/svc/jct-tools3.2.2_02
-  JTREG_KEY_OPTION=-k:\!ignore
+# Expect JPRT to set PRODUCT_HOME (the product or jdk in this case to test)
+ifndef PRODUCT_HOME
+  # Try to use j2sdk-image if it exists
+  ABS_JDK_IMAGE = $(ABS_BUILD_ROOT)/j2sdk-image
+  PRODUCT_HOME :=                       \
+    $(shell                             \
+      if [ -d $(ABS_JDK_IMAGE) ] ; then \
+         $(ECHO) "$(ABS_JDK_IMAGE)";    \
+       else                             \
+         $(ECHO) "$(ABS_BUILD_ROOT)" ;  \
+       fi)
+  PRODUCT_HOME := $(PRODUCT_HOME)
+endif
+
+# Expect JPRT to set JPRT_PRODUCT_ARGS (e.g. -server etc.)
+#   Should be passed into 'java' only.
+ifdef JPRT_PRODUCT_ARGS
+  JAVA_ARGS = $(JPRT_PRODUCT_ARGS)
 endif
 
-# Default JTREG to run
-JTREG = $(JT_HOME)/$(JCT_PLATFORM)/bin/jtreg
-
-# Default JDK to test
-JAVA_HOME = $(TEST_ROOT)/../build/$(PLATFORM)-$(ARCH)
-
-# The test directories to run
-DEFAULT_TESTDIRS = demo/jvmti/gctest demo/jvmti/hprof
-TESTDIRS = $(DEFAULT_TESTDIRS)
+# Expect JPRT to set JPRT_PRODUCT_VM_ARGS (e.g. -Xcomp etc.)
+#   Should be passed into anything running the vm (java, javac, javadoc, ...).
+ifdef JPRT_PRODUCT_VM_ARGS
+  JAVA_VM_ARGS = $(JPRT_PRODUCT_VM_ARGS)
+endif
 
-# Root of all test results
-JTREG_OUTPUT_DIR = $(TEST_ROOT)/o_$(PLATFORM)-$(ARCH)
-
-# Export this setting and pass it in.
-#JAVA_TOOL_OPTIONS = -Djava.awt.headless=true
-#export JAVA_TOOL_OPTIONS
-
-# Default make rule
-all: clean check tests $(JPRT_ARCHIVE_BUNDLE)
-	@echo "Testing completed successfully"
+# Expect JPRT to set JPRT_ARCHIVE_BUNDLE (path to zip bundle for results)
+ARCHIVE_BUNDLE = $(ABS_TEST_OUTPUT_DIR)/ARCHIVE_BUNDLE.zip
+ifdef JPRT_ARCHIVE_BUNDLE
+  ARCHIVE_BUNDLE = $(JPRT_ARCHIVE_BUNDLE)
+endif
 
-# Chaeck to make sure these directories exist
-check: $(JT_HOME) $(JAVA_HOME) $(JTREG)
+# How to create the test bundle (pass or fail, we want to create this)
+#   Follow command with ";$(BUNDLE_UP_AND_EXIT)", so it always gets executed.
+ZIP_UP_RESULTS = ( $(MKDIR) -p `dirname $(ARCHIVE_BUNDLE)`     \
+	           && $(CD) $(ABS_TEST_OUTPUT_DIR)             \
+	           && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . )
+BUNDLE_UP_AND_EXIT = ( exitCode=$$? && $(ZIP_UP_RESULTS) && exit $${exitCode} )
+
+################################################################
 
-# Run the tests
-tests: FRC
-	@echo "Using export JAVA_TOOL_OPTIONS=$(JAVA_TOOL_OPTIONS)"
-	@rm -f -r $(JTREG_OUTPUT_DIR)
-	@mkdir -p $(JTREG_OUTPUT_DIR)
-	$(JTREG) -a -v:fail,error \
-          $(JTREG_KEY_OPTION) \
-          -r:$(JTREG_OUTPUT_DIR)/JTreport \
-          -w:$(JTREG_OUTPUT_DIR)/JTwork \
-          -jdk:$(JAVA_HOME) \
-          $(JAVA_TOOL_OPTIONS:%=-vmoption:%) \
-          $(JAVA_ARGS:%=-vmoption:%) \
-          $(TESTDIRS)
+# Default make rule (runs jtreg_tests)
+all: jtreg_tests
+	@$(ECHO) "Testing completed successfully"
 
-# Bundle up the results
-$(JPRT_ARCHIVE_BUNDLE): FRC
-	@rm -f $@
-	@mkdir -p $(@D)
-	( cd $(JTREG_OUTPUT_DIR) && zip -q -r $@ . )
+# Prep for output
+prep: clean
+	@$(MKDIR) -p $(ABS_TEST_OUTPUT_DIR)
+	@$(MKDIR) -p `dirname $(ARCHIVE_BUNDLE)`
 
 # Cleanup
 clean:
-	rm -f -r $(JTREG_OUTPUT_DIR)
-	rm -f $(JPRT_ARCHIVE_BUNDLE)
+	$(RM) -r $(ABS_TEST_OUTPUT_DIR)
+	$(RM) $(ARCHIVE_BUNDLE)
+
+################################################################
+
+# jtreg tests
+
+# Expect JT_HOME to be set for jtreg tests. (home for jtreg)
+JT_HOME = $(SLASH_JAVA)/re/jtreg/4.0/promoted/latest/binaries/jtreg
+ifdef JPRT_JTREG_HOME
+  JT_HOME = $(JPRT_JTREG_HOME)
+endif
+
+# Expect JPRT to set TESTDIRS to the jtreg test dirs
+ifndef TESTDIRS
+  TESTDIRS = demo/jvmti/gctest demo/jvmti/hprof
+endif
+
+# Default JTREG to run (win32 script works for everybody)
+JTREG = $(JT_HOME)/win32/bin/jtreg
+
+jtreg_tests: prep $(JT_HOME) $(PRODUCT_HOME) $(JTREG)
+	$(RM) $(JTREG).orig
+	cp $(JTREG) $(JTREG).orig
+	$(RM) $(JTREG)
+	sed -e 's@-J\*@-J-*@' $(JTREG).orig > $(JTREG)
+	chmod a+x $(JTREG)
+	( JT_HOME=$(shell $(GETMIXEDPATH) "$(JT_HOME)");                     \
+          export JT_HOME;                                                    \
+          $(shell $(GETMIXEDPATH) "$(JTREG)")                                \
+            -a -v:fail,error                                                 \
+	    -ignore:quiet                                                    \
+            $(EXTRA_JTREG_OPTIONS)                                           \
+            -r:$(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/JTreport    \
+            -w:$(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/JTwork      \
+            -jdk:$(shell $(GETMIXEDPATH) "$(PRODUCT_HOME)")                  \
+            $(JAVA_ARGS:%=-javaoptions:%)                                     \
+            $(JAVA_VM_ARGS:%=-vmoption:%)                                    \
+            $(TESTDIRS)                                                      \
+	) ; $(BUNDLE_UP_AND_EXIT)
+
+PHONY_LIST += jtreg_tests
+
+################################################################
+
+# packtest
+
+# Expect JPRT to set JPRT_PACKTEST_HOME.
+PACKTEST_HOME = /net/jprt-web.sfbay.sun.com/jprt/allproducts/packtest
+ifdef JPRT_PACKTEST_HOME
+  PACKTEST_HOME = $(JPRT_PACKTEST_HOME)
+endif
+
+packtest: prep $(PACKTEST_HOME)/ptest $(PRODUCT_HOME)
+	( $(CD) $(PACKTEST_HOME) &&            \
+	    $(PACKTEST_HOME)/ptest             \
+		 -t "$(PRODUCT_HOME)"          \
+	         $(PACKTEST_STRESS_OPTION)     \
+		 $(EXTRA_PACKTEST_OPTIONS)     \
+		 -W $(ABS_TEST_OUTPUT_DIR)     \
+                 $(JAVA_ARGS:%=-J %)           \
+                 $(JAVA_VM_ARGS:%=-J %)        \
+	 ) ; $(BUNDLE_UP_AND_EXIT)
+
+packtest_stress: PACKTEST_STRESS_OPTION=-s
+packtest_stress: packtest
+
+PHONY_LIST += packtest packtest_stress
+
+################################################################
+
+# vmsqe tests
+
+# Expect JPRT to set JPRT_VMSQE_HOME.
+VMSQE_HOME = /java/sqe/comp/vm/testbase/sqe/vm/current/build/latest/vm
+ifdef JPRT_VMSQE_HOME
+  VMSQE_HOME = $(JPRT_VMSQE_HOME)
+endif
+
+# Expect JPRT to set JPRT_RUNVMSQE_HOME.
+RUNVMSQE_HOME = /net/jprt-web.sfbay.sun.com/jprt/allproducts/runvmsqe
+ifdef JPRT_RUNVMSQE_HOME
+  RUNVMSQE_HOME = $(JPRT_RUNVMSQE_HOME)
+endif
+
+# Expect JPRT to set JPRT_TONGA3_HOME.
+TONGA3_HOME = /java/sqe//tools/gtee/harness/tonga
+ifdef JPRT_TONGA3_HOME
+  TONGA3_HOME = $(JPRT_TONGA3_HOME)
+endif
+
+RUNVMSQE_BIN = $(RUNVMSQE_HOME)/bin/runvmsqe
+
+vmsqe_tests: prep $(VMSQE_HOME)/vm $(TONGA3_HOME) $(RUNVMSQE_BIN) $(PRODUCT_HOME)
+	$(RM) -r $(ABS_TEST_OUTPUT_DIR)/vmsqe
+	( $(CD) $(ABS_TEST_OUTPUT_DIR) &&          \
+	    $(RUNVMSQE_BIN)                        \
+		 -jdk "$(PRODUCT_HOME)"            \
+		 -o "$(ABS_TEST_OUTPUT_DIR)/vmsqe" \
+		 -testbase "$(VMSQE_HOME)/vm"      \
+		 -tonga "$(TONGA3_HOME)"           \
+		 -tongajdk "$(ALT_BOOTDIR)"        \
+                 $(JAVA_ARGS)                      \
+                 $(JAVA_VM_ARGS)                   \
+	         $(RUNVMSQE_TEST_OPTION)           \
+		 $(EXTRA_RUNVMSQE_OPTIONS)         \
+	 ) ; $(BUNDLE_UP_AND_EXIT)
+
+vmsqe_jdwp: RUNVMSQE_TEST_OPTION=-jdwp
+vmsqe_jdwp: vmsqe_tests
+
+vmsqe_jdi: RUNVMSQE_TEST_OPTION=-jdi
+vmsqe_jdi: vmsqe_tests
+
+vmsqe_jdb: RUNVMSQE_TEST_OPTION=-jdb
+vmsqe_jdb: vmsqe_tests
+
+vmsqe_quick-jdi: RUNVMSQE_TEST_OPTION=-quick-jdi
+vmsqe_quick-jdi: vmsqe_tests
+
+vmsqe_sajdi: RUNVMSQE_TEST_OPTION=-sajdi
+vmsqe_sajdi: vmsqe_tests
+
+vmsqe_jvmti: RUNVMSQE_TEST_OPTION=-jvmti
+vmsqe_jvmti: vmsqe_tests
+
+vmsqe_hprof: RUNVMSQE_TEST_OPTION=-hprof
+vmsqe_hprof: vmsqe_tests
+
+vmsqe_monitoring: RUNVMSQE_TEST_OPTION=-monitoring
+vmsqe_monitoring: vmsqe_tests
+
+PHONY_LIST += vmsqe_jdwp vmsqe_jdi vmsqe_jdb vmsqe_quick-jdi vmsqe_sajdi \
+              vmsqe_jvmti vmsqe_hprof vmsqe_monitoring vmsqe_tests
+
+################################################################
+
+# jck tests
 
-# Used to force a target rules to run
-FRC:
+JCK_WORK_DIR     = $(ABS_TEST_OUTPUT_DIR)/JCKwork
+JCK_REPORT_DIR   = $(ABS_TEST_OUTPUT_DIR)/JCKreport
+JCK_PROPERTIES   = $(ABS_TEST_OUTPUT_DIR)/jck.properties
+JCK_CONFIG       = $(ABS_TEST_OUTPUT_DIR)/jck.config
+
+JCK_JAVA_EXE     = $(PRODUCT_HOME)/bin/java$(EXESUFFIX)
+
+JCK_JAVATEST_JAR = $(JCK_HOME)/lib/javatest.jar
+JCK_JAVATEST     = $(ALT_BOOTDIR)/bin/java -jar $(JCK_JAVATEST_JAR)
+
+$(JCK_CONFIG): $(TEST_ROOT)/JCK-$(JCK_BUNDLE_NAME)-$(JCK_RELEASE)-base.jti
+	$(RM) $@
+	$(MKDIR) -p $(@D)
+	$(CP) $< $@
+
+$(JCK_PROPERTIES): $(PRODUCT_HOME) $(JCK_JAVA_EXE)
+	$(RM) $@
+	$(MKDIR) -p $(@D)
+	$(ECHO) "jck.env.compiler.compRefExecute.cmdAsFile=$(JCK_JAVA_EXE)" >> $@
+	$(ECHO) "jck.env.compiler.compRefExecute.systemRoot=$(SYSTEMROOT)" >> $@
+	$(ECHO) "jck.env.compiler.testCompile.testCompileAPImultiJVM.cmdAsFile=$(JCK_JAVA_EXE)" >> $@
+	$(ECHO) "jck.tests.tests=$(JCK_BUNDLE_TESTDIRS)" >> $@
+
+jck_tests: prep $(JCK_HOME) $(JCK_PROPERTIES) $(JCK_CONFIG) $(JCK_JAVATEST_JAR)
+	$(MKDIR) -p $(JCK_WORK_DIR)
+	( $(JCK_JAVATEST)                            \
+		-verbose:commands,non-pass           \
+		-testSuite    $(JCK_HOME)            \
+		-workDir      $(JCK_WORK_DIR)        \
+		-config       $(JCK_CONFIG)          \
+		-set -file    $(JCK_PROPERTIES)      \
+		-runtests                            \
+		-writeReport  $(JCK_REPORT_DIR)      \
+        ) ; $(BUNDLE_UP_AND_EXIT)
+
+PHONY_LIST += jck_tests
+
+################################################################
+
+# jck6 tests
+
+JCK6_RELEASE = 6b
+JCK6_DEFAULT_HOME = $(SLASH_JAVA)/re/jck/$(JCK6_RELEASE)/archive/fcs/binaries
+
+# Expect JPRT to set JPRT_JCK6COMPILER_HOME.
+JCK6COMPILER_HOME = $(JCK6_DEFAULT_HOME)/JCK-compiler-$(JCK6_RELEASE)
+ifdef JPRT_JCK6COMPILER_HOME
+  JCK6COMPILER_HOME = $(JPRT_JCK6COMPILER_HOME)
+endif
+
+# Expect JPRT to set JPRT_JCK6RUNTIME_HOME.
+JCK6RUNTIME_HOME = $(JCK6_DEFAULT_HOME)/JCK-runtime-$(JCK6_RELEASE)
+ifdef JPRT_JCK6RUNTIME_HOME
+  JCK6RUNTIME_HOME = $(JPRT_JCK6RUNTIME_HOME)
+endif
+
+# Expect JPRT to set JPRT_JCK6DEVTOOLS_HOME.
+JCK6DEVTOOLS_HOME = $(JCK6_DEFAULT_HOME)/JCK-devtools-$(JCK6_RELEASE)
+ifdef JPRT_JCK6DEVTOOLS_HOME
+  JCK6DEVTOOLS_HOME = $(JPRT_JCK6DEVTOOLS_HOME)
+endif
+
+jck6_tests: JCK_HOME=$(JCK6_HOME)
+jck6_tests: JCK_RELEASE=$(JCK6_RELEASE)
+jck6_tests: jck_tests
+
+jck6compiler: JCK6_HOME=$(JCK6COMPILER_HOME)
+jck6compiler: JCK_BUNDLE_NAME=compiler
+jck6compiler: jck6_tests
+
+jck6compiler_lang: JCK_BUNDLE_TESTDIRS=lang
+jck6compiler_lang: jck6compiler
+
+jck6runtime: JCK6_HOME=$(JCK6RUNTIME_HOME)
+jck6runtime: JCK_BUNDLE_NAME=runtime
+jck6runtime: jck6_tests
+
+jck6runtime_lang: JCK_BUNDLE_TESTDIRS=lang
+jck6runtime_lang: jck6runtime
+
+jck6devtools: JCK6_HOME=$(JCK6DEVTOOLS_HOME)
+jck6devtools: JCK_BUNDLE_NAME=devtools
+jck6devtools: jck6_tests
+
+jck6devtools_lang: JCK_BUNDLE_TESTDIRS=lang
+jck6devtools_lang: jck6devtools
+
+PHONY_LIST += jck6compiler jck6runtime jck6devtools jck6_tests \
+	      jck6compiler_lang jck6runtime_lang jck6devtools_lang
+
+################################################################
+
+# jck7 tests
+
+JCK7_RELEASE = 7
+JCK7_DEFAULT_HOME = $(SLASH_JAVA)/re/jck/$(JCK7_RELEASE)/archive/fcs/binaries
+
+# Expect JPRT to set JPRT_JCK7COMPILER_HOME.
+JCK7COMPILER_HOME = $(JCK7_DEFAULT_HOME)/JCK-compiler-$(JCK7_RELEASE)
+ifdef JPRT_JCK7COMPILER_HOME
+  JCK7COMPILER_HOME = $(JPRT_JCK7COMPILER_HOME)
+endif
+
+# Expect JPRT to set JPRT_JCK7RUNTIME_HOME.
+JCK7RUNTIME_HOME = $(JCK7_DEFAULT_HOME)/JCK-runtime-$(JCK7_RELEASE)
+ifdef JPRT_JCK7RUNTIME_HOME
+  JCK7RUNTIME_HOME = $(JPRT_JCK7RUNTIME_HOME)
+endif
+
+# Expect JPRT to set JPRT_JCK7DEVTOOLS_HOME.
+JCK7DEVTOOLS_HOME = $(JCK7_DEFAULT_HOME)/JCK-devtools-$(JCK7_RELEASE)
+ifdef JPRT_JCK7DEVTOOLS_HOME
+  JCK7DEVTOOLS_HOME = $(JPRT_JCK7DEVTOOLS_HOME)
+endif
+
+jck7_tests: JCK_HOME=$(JCK7_HOME)
+jck7_tests: JCK_RELEASE=$(JCK7_RELEASE)
+jck7_tests: jck_tests
+
+jck7compiler: JCK7_HOME=$(JCK7COMPILER_HOME)
+jck7compiler: JCK_BUNDLE_NAME=compiler
+jck7compiler: jck7_tests
+
+jck7compiler_lang: JCK_BUNDLE_TESTDIRS=lang
+jck7compiler_lang: jck7compiler
+
+jck7runtime: JCK7_HOME=$(JCK7RUNTIME_HOME)
+jck7runtime: JCK_BUNDLE_NAME=runtime
+jck7runtime: jck7_tests
+
+jck7runtime_lang: JCK_BUNDLE_TESTDIRS=lang
+jck7runtime_lang: jck7runtime
+
+jck7devtools: JCK7_HOME=$(JCK7DEVTOOLS_HOME)
+jck7devtools: JCK_BUNDLE_NAME=devtools
+jck7devtools: jck7_tests
+
+jck7devtools_lang: JCK_BUNDLE_TESTDIRS=lang
+jck7devtools_lang: jck7devtools
+
+PHONY_LIST += jck7compiler jck7runtime jck7devtools jck7_tests \
+	      jck7compiler_lang jck7runtime_lang jck7devtools_lang
+
+################################################################
 
 # Phony targets (e.g. these are not filenames)
-.PHONY: all tests clean check
+.PHONY: all clean prep $(PHONY_LIST)
 
+################################################################
+
--- a/jdk/test/com/sun/jmx/snmp/SnmpOidHashCode.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/com/sun/jmx/snmp/SnmpOidHashCode.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,8 @@
  * @build   SnmpOidHashCode
  * @run     main SnmpOidHashCode
  */
-import com.sun.jmx.snmp.SnmpOid;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
 
 public class SnmpOidHashCode {
     public static final String[] oids = {
@@ -57,16 +58,81 @@
         ".39."+0xFFFFFFFFL
     };
 
+    // We use an SnmpOidBuilder in order to adapt this test case to a
+    // configuration where the SNMP packages are not present in rt.jar.
+    //
+    public static final class SnmpOidBuilder {
+        public static final String SNMP_OID_CLASS_NAME =
+            "com.sun.jmx.snmp.SnmpOid";
+        private static final Class<?> SNMP_OID_CLASS;
+        private static final Constructor<?> SNMP_OID_CTOR;
+        static {
+            Class<?> snmpOidClass;
+            try {
+                snmpOidClass =
+                    Class.forName(SNMP_OID_CLASS_NAME, true, null);
+            } catch (ClassNotFoundException x) {
+                snmpOidClass = null;
+                System.err.println("WARNING: can't load "+SNMP_OID_CLASS_NAME);
+            } catch (NoClassDefFoundError x) {
+                snmpOidClass = null;
+                System.err.println("WARNING: can't load "+SNMP_OID_CLASS_NAME);
+            }
+            SNMP_OID_CLASS = snmpOidClass;
+            if (SNMP_OID_CLASS != null) {
+                try {
+                  SNMP_OID_CTOR = snmpOidClass.getConstructor(String.class);
+                } catch (Exception x) {
+                    throw new ExceptionInInitializerError(x);
+                }
+            } else {
+                SNMP_OID_CTOR = null;
+            }
+        }
+
+        public static boolean isSnmpPresent() {
+            System.out.println(SnmpOidHashCode.class.getName()+
+                    ": Testing for SNMP Packages...");
+            return SNMP_OID_CLASS != null;
+        }
+
+        public static Object newSnmpOid(String oid)
+            throws InstantiationException,
+                   IllegalAccessException,
+                   InvocationTargetException {
+            return SNMP_OID_CTOR.newInstance(oid);
+        }
+
+    }
+
+    private static Object newSnmpOid(String oid) throws Exception {
+        try {
+            return SnmpOidBuilder.newSnmpOid(oid);
+        } catch (InvocationTargetException x) {
+            final Throwable cause = x.getCause();
+            if (cause instanceof Exception) throw (Exception)cause;
+            if (cause instanceof Error) throw (Error)cause;
+            throw x;
+        }
+    }
+
     public static void main(String args[]) {
+        if (!SnmpOidBuilder.isSnmpPresent()) {
+            System.err.println("WARNING: "+
+                    SnmpOidBuilder.SNMP_OID_CLASS_NAME+" not present.");
+            System.err.println(SnmpOidHashCode.class.getName()+
+                    ": test skipped.");
+            return;
+        }
         try {
             int errCount=0;
             int collisions=0;
             for (int i=0;i<oids.length;i++) {
                 System.out.println("Testing " + oids[i]);
-                final SnmpOid o1 = new SnmpOid(oids[i]);
+                final Object o1 = newSnmpOid(oids[i]);
                 final int startCount=errCount;
                 for (int j=0;j<oids.length;j++) {
-                    final SnmpOid o2 = new SnmpOid(oids[j]);
+                    final Object o2 = newSnmpOid(oids[j]);
                     if (o1.equals(o2)) {
                         if (!(oids[i].equals(oids[j]))) {
                             System.err.println("OIDs differ but " +
--- a/jdk/test/com/sun/jmx/snmp/TimeTicksWrapping.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/com/sun/jmx/snmp/TimeTicksWrapping.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,33 +29,158 @@
  * @build   TimeTicksWrapping
  * @run     main TimeTicksWrapping
  */
-import com.sun.jmx.snmp.SnmpTimeticks;
-import com.sun.jmx.snmp.SnmpUnsignedInt;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 
 public class TimeTicksWrapping {
+    // We use an SnmpTimeticksBuilder in order to adapt this test case to a
+    // configuration where the SNMP packages are not present in rt.jar.
+    //
+    public static final class SnmpTimeticksBuilder {
+        public static final long   MAX_VALUE = 0x0ffffffffL;
+        public static final String SNMP_TIME_TICKS_CLASS_NAME =
+            "com.sun.jmx.snmp.SnmpTimeticks";
+        private static final Class<?> SNMP_TIME_TICKS_CLASS;
+        private static final Constructor<?> SNMP_long_CTOR;
+        private static final Constructor<?> SNMP_LONG_CTOR;
+        private static final Method SNMP_LONG_VALUE;
+        static {
+            Class<?> snmpTimeTicksClass;
+            try {
+                snmpTimeTicksClass =
+                    Class.forName(SNMP_TIME_TICKS_CLASS_NAME, true, null);
+            } catch (ClassNotFoundException x) {
+                snmpTimeTicksClass = null;
+                System.err.println("WARNING: can't load "+
+                        SNMP_TIME_TICKS_CLASS_NAME);
+            } catch (NoClassDefFoundError x) {
+                snmpTimeTicksClass = null;
+                System.err.println("WARNING: can't load "+
+                        SNMP_TIME_TICKS_CLASS_NAME);
+            }
+            SNMP_TIME_TICKS_CLASS = snmpTimeTicksClass;
+            if (SNMP_TIME_TICKS_CLASS != null) {
+                try {
+                  SNMP_long_CTOR =
+                          SNMP_TIME_TICKS_CLASS.getConstructor(long.class);
+                } catch (Exception x) {
+                    throw new ExceptionInInitializerError(x);
+                }
+            } else {
+                SNMP_long_CTOR = null;
+            }
+            if (SNMP_TIME_TICKS_CLASS != null) {
+                try {
+                  SNMP_LONG_CTOR =
+                          SNMP_TIME_TICKS_CLASS.getConstructor(Long.class);
+                } catch (Exception x) {
+                    throw new ExceptionInInitializerError(x);
+                }
+            } else {
+                SNMP_LONG_CTOR = null;
+            }
+            if (SNMP_TIME_TICKS_CLASS != null) {
+                try {
+                  SNMP_LONG_VALUE =
+                          SNMP_TIME_TICKS_CLASS.getMethod("longValue");
+                } catch (Exception x) {
+                    throw new ExceptionInInitializerError(x);
+                }
+            } else {
+                SNMP_LONG_VALUE = null;
+            }
+
+        }
+
+        private final Object timeticks;
+
+        public SnmpTimeticksBuilder(long ticks) throws Exception {
+            timeticks = newSnmpTimeticks(ticks);
+        }
+        public SnmpTimeticksBuilder(Long ticks) throws Exception {
+            timeticks = newSnmpTimeticks(ticks);
+        }
+        public long longValue() throws Exception {
+            return longValue(timeticks);
+        }
+
+        public static boolean isSnmpPresent() {
+            System.out.println(TimeTicksWrapping.class.getName()+
+                    ": Testing for SNMP Packages...");
+            return SNMP_TIME_TICKS_CLASS != null;
+        }
+
+        private static Object newSnmpTimeticks(long time)
+                throws Exception {
+            try {
+                return SNMP_long_CTOR.newInstance(time);
+            } catch (InvocationTargetException x) {
+                final Throwable cause = x.getCause();
+                if (cause instanceof Exception) throw (Exception) cause;
+                if (cause instanceof Error) throw (Error) cause;
+                throw x;
+            }
+        }
+
+        private static Object newSnmpTimeticks(Long time)
+            throws Exception {
+            try {
+                return SNMP_LONG_CTOR.newInstance(time);
+            } catch (InvocationTargetException x) {
+                final Throwable cause = x.getCause();
+                if (cause instanceof Exception) throw (Exception) cause;
+                if (cause instanceof Error) throw (Error) cause;
+                throw x;
+            }
+        }
+
+        private static long longValue(Object o)
+                throws Exception {
+            try {
+                return ((Long)SNMP_LONG_VALUE.invoke(o)).longValue();
+            } catch (InvocationTargetException x) {
+                final Throwable cause = x.getCause();
+                if (cause instanceof Exception) throw (Exception) cause;
+                if (cause instanceof Error) throw (Error) cause;
+                throw x;
+            }
+        }
+
+    }
+
     public static final long[] oks = {
         0L, 1L, (long)Integer.MAX_VALUE, (long)Integer.MAX_VALUE*2,
         (long)Integer.MAX_VALUE*2+1L, (long)Integer.MAX_VALUE*2+2L,
         (long)Integer.MAX_VALUE*3,
-        SnmpUnsignedInt.MAX_VALUE, SnmpUnsignedInt.MAX_VALUE+1L,
-        SnmpUnsignedInt.MAX_VALUE*3-1L, Long.MAX_VALUE
+        SnmpTimeticksBuilder.MAX_VALUE, SnmpTimeticksBuilder.MAX_VALUE+1L,
+        SnmpTimeticksBuilder.MAX_VALUE*3-1L, Long.MAX_VALUE
     };
 
     public static final long[] kos = {
         -1L, (long)Integer.MIN_VALUE, (long)Integer.MIN_VALUE*2,
         (long)Integer.MIN_VALUE*2-1L, (long)Integer.MIN_VALUE*3,
-        -SnmpUnsignedInt.MAX_VALUE, -(SnmpUnsignedInt.MAX_VALUE+1L),
-        -(SnmpUnsignedInt.MAX_VALUE*3-1L), Long.MIN_VALUE
+        -SnmpTimeticksBuilder.MAX_VALUE, -(SnmpTimeticksBuilder.MAX_VALUE+1L),
+        -(SnmpTimeticksBuilder.MAX_VALUE*3-1L), Long.MIN_VALUE
     };
 
+
     public static void main(String args[]) {
+        if (!SnmpTimeticksBuilder.isSnmpPresent()) {
+            System.err.println("WARNING: "+
+                    SnmpTimeticksBuilder.SNMP_TIME_TICKS_CLASS_NAME+
+                    " not present.");
+            System.err.println(TimeTicksWrapping.class.getName()+
+                    ": test skipped.");
+            return;
+        }
         try {
-            SnmpTimeticks t;
+            SnmpTimeticksBuilder t = null;
 
             for (int i=0;i<oks.length;i++) {
                 final long t1,t2,t3;
-                t1 = (new SnmpTimeticks(oks[i])).longValue();
-                t2 = (new SnmpTimeticks(new Long(oks[i]))).longValue();
+                t1 = (new SnmpTimeticksBuilder(oks[i])).longValue();
+                t2 = (new SnmpTimeticksBuilder(new Long(oks[i]))).longValue();
                 t3 = oks[i]%0x0100000000L;
                 if (t1 != t3)
                     throw new Exception("Value should have wrapped: " +
@@ -64,16 +189,16 @@
                     throw new Exception("Value should have wrapped: " +
                                         "Long("+oks[i]+") expected: " + t3);
 
-                if (t1 > SnmpUnsignedInt.MAX_VALUE)
+                if (t1 > SnmpTimeticksBuilder.MAX_VALUE)
                     throw new Exception("Value should have wrapped " +
                                         "for " + oks[i] + ": " +
                                         t1 + " exceeds max: " +
-                                        SnmpUnsignedInt.MAX_VALUE);
-                if (t2 > SnmpUnsignedInt.MAX_VALUE)
+                                        SnmpTimeticksBuilder.MAX_VALUE);
+                if (t2 > SnmpTimeticksBuilder.MAX_VALUE)
                     throw new Exception("Value should have wrapped " +
                                         "for " + oks[i] + ": " +
                                         t2 + " exceeds max: " +
-                                        SnmpUnsignedInt.MAX_VALUE);
+                                        SnmpTimeticksBuilder.MAX_VALUE);
 
                 if (t1 < 0)
                     throw new Exception("Value should have wrapped: " +
@@ -90,14 +215,14 @@
 
             for (int i=0;i<kos.length;i++) {
                 try {
-                    t = new SnmpTimeticks(kos[i]);
+                    t = new SnmpTimeticksBuilder(kos[i]);
                     throw new Exception("Value should have been rejected: " +
                                         kos[i]);
                 } catch (IllegalArgumentException x) {
                     // OK!
                 }
                 try {
-                    t = new SnmpTimeticks(new Long(kos[i]));
+                    t = new SnmpTimeticksBuilder(new Long(kos[i]));
                     throw new Exception("Value should have been rejected: " +
                                         "Long("+kos[i]+")");
                 } catch (IllegalArgumentException x) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/FontClass/FontAccess.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6785424
+ * @summary Test no SecurityException searching for a font.
+ * @run main FontAccess
+ *
+ * This can only test the specific bug if run on something like
+ * Windows Citrix Server where SystemDirectory and WindowsDirectory
+ * are different locations.
+ */
+
+import java.awt.*;
+import java.awt.image.*;
+
+public class FontAccess {
+
+     public static void main(String[] args) {
+        System.setSecurityManager(new SecurityManager());
+        Font f = new Font("Verdana", Font.PLAIN, 12);
+        BufferedImage bi = new BufferedImage(1,1,1);
+        Graphics2D g = bi.createGraphics();
+        g.setFont(f);
+        System.out.println(g.getFontMetrics());
+     }
+}
--- a/jdk/test/java/awt/Frame/FrameSize/TestFrameSize.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/awt/Frame/FrameSize/TestFrameSize.java	Fri Apr 10 13:05:12 2009 -0700
@@ -15,6 +15,10 @@
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
  */
 
 /*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/GraphicsEnvironment/PreferLocaleFonts.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6752638
+ * @summary Test no NPE calling preferLocaleFonts() on custom GE.
+ * @run main PreferLocaleFonts
+ */
+
+import java.util.*;
+import java.awt.*;
+import java.awt.image.*;
+
+public class PreferLocaleFonts extends GraphicsEnvironment {
+
+    public static void main(String args[]) {
+(new PreferLocaleFonts()).preferLocaleFonts();
+    }
+    public PreferLocaleFonts() {
+        super();
+    }
+    public Graphics2D createGraphics(BufferedImage image) {
+        return null;
+    }
+    public String[] getAvailableFontFamilyNames(Locale locale) {
+        return null;
+    }
+    public String[] getAvailableFontFamilyNames() {
+        return null;
+    }
+    public Font[] getAllFonts() {
+        return null;
+    }
+    public GraphicsDevice getDefaultScreenDevice() throws HeadlessException {
+        return null;
+    }
+    public GraphicsDevice[] getScreenDevices() throws HeadlessException {
+        return null;
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/LineBreakMeasurer/FRCTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2008-9 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6448405 6519513 6745225
+ * @summary static HashMap cache in LineBreakMeasurer can grow wihout bounds
+ * @run main/othervm/timeout=600 -client -Xms16m -Xmx16m FRCTest
+ */
+import java.awt.*;
+import java.awt.image.*;
+import java.awt.font.*;
+import java.awt.geom.*;
+import java.text.*;
+import java.util.Hashtable;
+
+public class FRCTest {
+
+    static AttributedString vanGogh = new AttributedString(
+        "Many people believe that Vincent van Gogh painted his best works " +
+        "during the two-year period he spent in Provence. Here is where he " +
+        "painted The Starry Night--which some consider to be his greatest " +
+        "work of all. However, as his artistic brilliance reached new " +
+        "heights in Provence, his physical and mental health plummeted. ",
+        new Hashtable());
+
+    public static void main(String[] args) {
+
+        // First test the behaviour of Graphics2D.getFontRenderContext();
+        BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2d = bi.createGraphics();
+        AffineTransform g2dTx = new AffineTransform(2,0,2,0,1,1);
+        g2d.setTransform(g2dTx);
+        AffineTransform frcTx = g2d.getFontRenderContext().getTransform();
+        AffineTransform frcExpected = new AffineTransform(2,0,2,0,0,0);
+        if (!frcTx.equals(frcExpected)) {
+            throw new RuntimeException("FRC Tx may have translate?");
+        }
+
+        // Now test that using different translates with LBM is OK
+        // This test doesn't prove a lot since showing a leak really
+        // requires a basher test that can run for a long time.
+        for (int x=0;x<100;x++) {
+            for (int y=0;y<100;y++) {
+                AttributedCharacterIterator aci = vanGogh.getIterator();
+                AffineTransform tx = AffineTransform.getTranslateInstance(x, y);
+                FontRenderContext frc = new FontRenderContext(tx, false, false);
+                LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
+                lbm.setPosition(aci.getBeginIndex());
+                while (lbm.getPosition() < aci.getEndIndex()) {
+                    lbm.nextLayout(100f);
+                }
+            }
+        }
+
+        for (int x=0;x<25;x++) {
+            for (int y=0;y<25;y++) {
+                AttributedCharacterIterator aci = vanGogh.getIterator();
+                double rot = Math.random()*.4*Math.PI - .2*Math.PI;
+                AffineTransform tx = AffineTransform.getRotateInstance(rot);
+                FontRenderContext frc = new FontRenderContext(tx, false, false);
+                LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
+                lbm.setPosition(aci.getBeginIndex());
+                while (lbm.getPosition() < aci.getEndIndex()) {
+                    lbm.nextLayout(100f);
+                }
+            }
+        }
+    }
+}
--- a/jdk/test/java/io/File/GetXSpace.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/io/File/GetXSpace.java	Fri Apr 10 13:05:12 2009 -0700
@@ -24,6 +24,7 @@
 /**
  * @test
  * @bug 4057701 6286712 6364377
+ * @ignore until 6492634 and 6501010 is fixed
  * @run build GetXSpace
  * @run shell GetXSpace.sh
  * @summary Basic functionality of File.get-X-Space methods.
--- a/jdk/test/java/lang/Thread/StartOOMTest.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/lang/Thread/StartOOMTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -24,6 +24,7 @@
 /*
  * @test
  * @bug 6379235
+ * @ignore until 6721694 is fixed
  * @run main/othervm -server -Xmx32m -Xms32m -Xss256m StartOOMTest
  * @summary ThreadGroup accounting mistake possible with failure of Thread.start()
  */
--- a/jdk/test/java/lang/reflect/Method/InheritedMethods.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/lang/reflect/Method/InheritedMethods.java	Fri Apr 10 13:05:12 2009 -0700
@@ -23,6 +23,7 @@
 
 /* @test
    @bug 4471738
+   @ignore until 6825739 fixed
    @summary Failure to properly traverse class hierarchy in Class.getMethod()
 */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/security/Permission/ToString.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6549506
+ * @summary Specification of Permission.toString() method contradicts with
+ *      JDK implementation
+ */
+
+import java.security.*;
+
+public class ToString {
+
+    public static void main(String[]args) throws Exception {
+        DummyWritePermission dummyPerm = new DummyWritePermission();
+        NullActionPermission nullActionPerm = new NullActionPermission();
+        System.out.println(dummyPerm.toString());
+        System.out.println(dummyPerm.getDescription());
+        System.out.println(nullActionPerm.toString());
+        System.out.println(nullActionPerm.getDescription());
+        if (!dummyPerm.toString().equals(dummyPerm.getDescription())) {
+            throw new Exception("The expected permission.toString() is " +
+                dummyPerm.getDescription() + ", but " +
+                dummyPerm.toString() + " returned!");
+        }
+
+        if (!nullActionPerm.toString().equals(nullActionPerm.getDescription())) {
+            throw new Exception("The expected permission.toString() is " +
+                nullActionPerm.getDescription() + ", but " +
+                nullActionPerm.toString() + " returned!");
+        }
+    }
+
+    private static abstract class SimplePermission extends Permission {
+        public SimplePermission(String name) {
+            super(name);
+        }
+
+        public boolean implies(Permission permission) {
+            return false;
+        }
+
+        public boolean equals(Object obj) {
+            return false;
+        }
+
+        public int hashCode() {
+            return 13;
+        }
+    }
+
+    private static class DummyWritePermission extends SimplePermission {
+        public DummyWritePermission() {
+            super("permit to");
+        }
+
+        public String getActions() {
+            return "write";
+        }
+
+        public String getDescription() {
+            return "(\"ToString$DummyWritePermission\" \"permit to\" \"write\")";
+        }
+    }
+
+    private static class NullActionPermission extends SimplePermission {
+        public NullActionPermission() {
+            super("permit to");
+        }
+
+        public String getActions() {
+            return null;
+        }
+
+        public String getDescription() {
+            return "(\"ToString$NullActionPermission\" \"permit to\")";
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6383095
+ * @summary CRL revoked certificate failures masked by OCSP failures
+ *
+ * Note that the certificate validity is from Mar 16 14:55:35 2009 GMT to
+ * Dec 1 14:55:35 2028 GMT, please update it with newer certificate if
+ * expires.
+ *
+ * @author Xuelei Fan
+ */
+
+/*
+ * Certificates used in the test.
+ *
+ * end entity certificate:
+ * Data:
+ *     Version: 3 (0x2)
+ *     Serial Number: 25 (0x19)
+ *     Signature Algorithm: md5WithRSAEncryption
+ *     Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org
+ *     Validity
+ *         Not Before: Mar 16 14:55:35 2009 GMT
+ *         Not After : Dec  1 14:55:35 2028 GMT
+ *     Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org, OU=SSL-Client,
+ *              CN=localhost
+ *     Subject Public Key Info:
+ *         Public Key Algorithm: rsaEncryption
+ *         RSA Public Key: (1024 bit)
+ *             Modulus (1024 bit):
+ *                 00:bb:f0:40:36:ac:26:54:4e:f4:a3:5a:00:2f:69:
+ *                 21:6f:b9:7a:3a:93:ec:a2:f6:e1:8e:c7:63:d8:2f:
+ *                 12:30:99:2e:b0:f2:8f:f8:27:2d:24:78:28:84:f7:
+ *                 01:bf:8d:44:79:dd:3b:d2:55:f3:ce:3c:b2:5b:21:
+ *                 7d:ef:fd:33:4a:b1:a3:ff:c6:c8:9b:b9:0f:7c:41:
+ *                 35:97:f9:db:3a:05:60:05:15:af:59:17:92:a3:10:
+ *                 ad:16:1c:e4:07:53:af:a8:76:a2:56:2a:92:d3:f9:
+ *                 28:e0:78:cf:5e:1f:48:ab:5c:19:dd:e1:67:43:ba:
+ *                 75:8d:f5:82:ac:43:92:44:1b
+ *             Exponent: 65537 (0x10001)
+ *     X509v3 extensions:
+ *         X509v3 Basic Constraints:
+ *             CA:FALSE
+ *         X509v3 Key Usage:
+ *             Digital Signature, Non Repudiation, Key Encipherment
+ *         X509v3 Subject Key Identifier:
+ *             CD:BB:C8:85:AA:91:BD:FD:1D:BE:CD:67:7C:FF:B3:E9:4C:A8:22:E6
+ *         X509v3 Authority Key Identifier:
+ *             keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
+ * Signature Algorithm: md5WithRSAEncryption
+ *
+ *
+ * trusted certificate authority:
+ * Data:
+ *     Version: 3 (0x2)
+ *     Serial Number: 0 (0x0)
+ *     Signature Algorithm: md5WithRSAEncryption
+ *     Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org
+ *     Validity
+ *         Not Before: Dec  8 02:43:36 2008 GMT
+ *         Not After : Aug 25 02:43:36 2028 GMT
+ *     Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org
+ *     Subject Public Key Info:
+ *         Public Key Algorithm: rsaEncryption
+ *         RSA Public Key: (1024 bit)
+ *             Modulus (1024 bit):
+ *                 00:cb:c4:38:20:07:be:88:a7:93:b0:a1:43:51:2d:
+ *                 d7:8e:85:af:54:dd:ad:a2:7b:23:5b:cf:99:13:53:
+ *                 99:45:7d:ee:6d:ba:2d:bf:e3:ad:6e:3d:9f:1a:f9:
+ *                 03:97:e0:17:55:ae:11:26:57:de:01:29:8e:05:3f:
+ *                 21:f7:e7:36:e8:2e:37:d7:48:ac:53:d6:60:0e:c7:
+ *                 50:6d:f6:c5:85:f7:8b:a6:c5:91:35:72:3c:94:ee:
+ *                 f1:17:f0:71:e3:ec:1b:ce:ca:4e:40:42:b0:6d:ee:
+ *                 6a:0e:d6:e5:ad:3c:0f:c9:ba:82:4f:78:f8:89:97:
+ *                 89:2a:95:12:4c:d8:09:2a:e9
+ *             Exponent: 65537 (0x10001)
+ *     X509v3 extensions:
+ *         X509v3 Subject Key Identifier:
+ *             FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
+ *         X509v3 Authority Key Identifier:
+ *             keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
+ *             DirName:/C=US/ST=Some-State/L=Some-City/O=Some-Org
+ *         X509v3 Basic Constraints:
+ *             CA:TRUE
+ * Signature Algorithm: md5WithRSAEncryption
+ *
+ * CRL:
+ * Certificate Revocation List (CRL):
+ *    Version 2 (0x1)
+ *    Signature Algorithm: md5WithRSAEncryption
+ *    Issuer: /C=US/ST=Some-State/L=Some-City/O=Some-Org
+ *    Last Update: Mar 16 16:27:14 2009 GMT
+ *    Next Update: May 15 16:27:14 2028 GMT
+ *    CRL extensions:
+ *       X509v3 CRL Number:
+ *              2
+ * Revoked Certificates:
+ *    Serial Number: 19
+ *        Revocation Date: Mar 16 16:22:08 2009 GMT
+ *        CRL entry extensions:
+ *            X509v3 CRL Reason Code:
+ *                Superseded
+ *    Signature Algorithm: md5WithRSAEncryption
+ */
+
+import java.io.*;
+import java.net.SocketException;
+import java.util.*;
+import java.security.Security;
+import java.security.cert.*;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.cert.CertPathValidatorException.BasicReason;
+
+public class FailoverToCRL {
+
+    static String trusedCertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIICrDCCAhWgAwIBAgIBADANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" +
+        "MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" +
+        "EwhTb21lLU9yZzAeFw0wODEyMDgwMjQzMzZaFw0yODA4MjUwMjQzMzZaMEkxCzAJ\n" +
+        "BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" +
+        "dHkxETAPBgNVBAoTCFNvbWUtT3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" +
+        "gQDLxDggB76Ip5OwoUNRLdeOha9U3a2ieyNbz5kTU5lFfe5tui2/461uPZ8a+QOX\n" +
+        "4BdVrhEmV94BKY4FPyH35zboLjfXSKxT1mAOx1Bt9sWF94umxZE1cjyU7vEX8HHj\n" +
+        "7BvOyk5AQrBt7moO1uWtPA/JuoJPePiJl4kqlRJM2Akq6QIDAQABo4GjMIGgMB0G\n" +
+        "A1UdDgQWBBT6uVG/TOfZhpgz+efLHvEzSfeoFDBxBgNVHSMEajBogBT6uVG/TOfZ\n" +
+        "hpgz+efLHvEzSfeoFKFNpEswSTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUt\n" +
+        "U3RhdGUxEjAQBgNVBAcTCVNvbWUtQ2l0eTERMA8GA1UEChMIU29tZS1PcmeCAQAw\n" +
+        "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBcIm534U123Hz+rtyYO5uA\n" +
+        "ofd81G6FnTfEAV8Kw9fGyyEbQZclBv34A9JsFKeMvU4OFIaixD7nLZ/NZ+IWbhmZ\n" +
+        "LovmJXyCkOufea73pNiZ+f/4/ScZaIlM/PRycQSqbFNd4j9Wott+08qxHPLpsf3P\n" +
+        "6Mvf0r1PNTY2hwTJLJmKtg==\n" +
+        "-----END CERTIFICATE-----";
+
+    static String targetCertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIICizCCAfSgAwIBAgIBGTANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" +
+        "MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" +
+        "EwhTb21lLU9yZzAeFw0wOTAzMTYxNDU1MzVaFw0yODEyMDExNDU1MzVaMHIxCzAJ\n" +
+        "BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" +
+        "dHkxETAPBgNVBAoTCFNvbWUtT3JnMRMwEQYDVQQLEwpTU0wtQ2xpZW50MRIwEAYD\n" +
+        "VQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALvwQDas\n" +
+        "JlRO9KNaAC9pIW+5ejqT7KL24Y7HY9gvEjCZLrDyj/gnLSR4KIT3Ab+NRHndO9JV\n" +
+        "8848slshfe/9M0qxo//GyJu5D3xBNZf52zoFYAUVr1kXkqMQrRYc5AdTr6h2olYq\n" +
+        "ktP5KOB4z14fSKtcGd3hZ0O6dY31gqxDkkQbAgMBAAGjWjBYMAkGA1UdEwQCMAAw\n" +
+        "CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTNu8iFqpG9/R2+zWd8/7PpTKgi5jAfBgNV\n" +
+        "HSMEGDAWgBT6uVG/TOfZhpgz+efLHvEzSfeoFDANBgkqhkiG9w0BAQQFAAOBgQBv\n" +
+        "p7JjCDOrMBNun46xs4Gz7Y4ygM5VHaFP0oO7369twvRSu0pCuIdZd5OIMPFeRqQw\n" +
+        "PA68ZdhYVR0pG5W7isV+jB+Dfge/IOgOA85sZ/6FlP3PBRW+YMQKKdRr5So3ook9\n" +
+        "PimQ7rbxRAofPECv20IUKFBbOUkU+gFcn+WbTKYxBw==\n" +
+        "-----END CERTIFICATE-----";
+
+    static String crlStr =
+        "-----BEGIN X509 CRL-----\n" +
+        "MIIBRTCBrwIBATANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzETMBEGA1UE\n" +
+        "CBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQKEwhTb21l\n" +
+        "LU9yZxcNMDkwMzE2MTYyNzE0WhcNMjgwNTE1MTYyNzE0WjAiMCACARkXDTA5MDMx\n" +
+        "NjE2MjIwOFowDDAKBgNVHRUEAwoBBKAOMAwwCgYDVR0UBAMCAQIwDQYJKoZIhvcN\n" +
+        "AQEEBQADgYEAMixJI9vBwYpOGosn46+T/MTEtlm2S5pIVT/xPDrHkCPfw8l4Zrgp\n" +
+        "dGPuUkglWdrGdxY9MNRUj2YFNfdZi6zZ7JF6XbkDHYOAKYgPDJRjS/0VcBntn5RJ\n" +
+        "sQfZsBqc9fFSP8gknRRn3LT41kr9xNRxTT1t3YYjv7J3zkMYyInqeUA=\n" +
+        "-----END X509 CRL-----";
+
+
+    private static CertPath generateCertificatePath()
+            throws CertificateException {
+        // generate certificate from cert strings
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+
+        ByteArrayInputStream is =
+                new ByteArrayInputStream(targetCertStr.getBytes());
+        Certificate targetCert = cf.generateCertificate(is);
+
+        // generate certification path
+        List<Certificate> list = Arrays.asList(new Certificate[] {targetCert});
+
+        return cf.generateCertPath(list);
+    }
+
+    private static Set<TrustAnchor> generateTrustAnchors()
+            throws CertificateException {
+        // generate certificate from cert string
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+
+        ByteArrayInputStream is =
+                    new ByteArrayInputStream(trusedCertStr.getBytes());
+        Certificate trusedCert = cf.generateCertificate(is);
+
+        // generate a trust anchor
+        TrustAnchor anchor = new TrustAnchor((X509Certificate)trusedCert, null);
+
+        return Collections.singleton(anchor);
+    }
+
+    private static CertStore generateCertificateStore() throws Exception {
+        // generate CRL from CRL string
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+
+        ByteArrayInputStream is =
+                    new ByteArrayInputStream(crlStr.getBytes());
+
+        // generate a cert store
+        Collection<? extends CRL> crls = cf.generateCRLs(is);
+        return CertStore.getInstance("Collection",
+                            new CollectionCertStoreParameters(crls));
+    }
+
+    public static void main(String args[]) throws Exception {
+        CertPath path = generateCertificatePath();
+        Set<TrustAnchor> anchors = generateTrustAnchors();
+        CertStore crls = generateCertificateStore();
+
+        PKIXParameters params = new PKIXParameters(anchors);
+
+        // add the CRL store
+        params.addCertStore(crls);
+
+        // Activate certificate revocation checking
+        params.setRevocationEnabled(true);
+
+        // Activate OCSP
+        Security.setProperty("ocsp.enable", "true");
+        System.setProperty("com.sun.security.enableCRLDP", "true");
+
+        // Ensure that the ocsp.responderURL property is not set.
+        if (Security.getProperty("ocsp.responderURL") != null) {
+            throw new
+                Exception("The ocsp.responderURL property must not be set");
+        }
+
+        CertPathValidator validator = CertPathValidator.getInstance("PKIX");
+
+        try {
+            validator.validate(path, params);
+        } catch (CertPathValidatorException cpve) {
+            if (cpve.getReason() != BasicReason.REVOKED) {
+                throw new Exception(
+                    "unexpect exception, should be a REVOKED CPVE", cpve);
+            }
+        }
+    }
+}
--- a/jdk/test/java/util/concurrent/TimeUnit/Basic.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/util/concurrent/TimeUnit/Basic.java	Fri Apr 10 13:05:12 2009 -0700
@@ -60,10 +60,11 @@
         equal(1000L, MICROSECONDS.toNanos(1));
 
         long t0 = System.nanoTime();
-        MILLISECONDS.sleep(3);
+        MILLISECONDS.sleep(3); /* See windows bug 6313903, might not sleep */
         long elapsedMillis = (System.nanoTime() - t0)/(1000L * 1000L);
         System.out.printf("elapsed=%d%n", elapsedMillis);
-        check(elapsedMillis >= 3);
+        check(elapsedMillis >= 0);
+        /* Might not sleep on windows: check(elapsedMillis >= 3); */
         check(elapsedMillis < 1000);
 
         //----------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/ClassLoaderLeakTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,190 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug     6799583
+ *
+ * @summary Test verifes that LogManager shutdown hook does not cause
+ *          an application classloader leaks.
+ *
+ * @run     main/othervm ClassLoaderLeakTest
+ */
+
+import java.io.File;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.concurrent.CountDownLatch;
+import java.util.logging.Logger;
+import java.util.logging.Logger;
+
+public class ClassLoaderLeakTest {
+
+    private static CountDownLatch doneSignal;
+    private static CountDownLatch launchSignal;
+    private static ThreadGroup appsThreadGroup;
+    private static Throwable launchFailure = null;
+
+    public static void main(String[] args) {
+        appsThreadGroup = new ThreadGroup("MyAppsThreadGroup");
+        doneSignal = new CountDownLatch(1);
+        launchSignal = new CountDownLatch(1);
+
+        Runnable launcher = new Runnable() {
+            public void run() {
+                try {
+                    ClassLoader cl =
+                        Thread.currentThread().getContextClassLoader();
+                    Class appMain = cl.loadClass("AppTest");
+                    Method launch =
+                        appMain.getDeclaredMethod("launch", doneSignal.getClass());
+
+                    Constructor c = appMain.getConstructor();
+
+                    Object o = c.newInstance();
+
+                    launch.invoke(o, doneSignal);
+
+                } catch (Throwable e) {
+                    launchFailure = e;
+                } finally {
+                    launchSignal.countDown();
+                }
+            }
+        };
+
+        /* prepare test  class loader */
+        URL pwd = null;
+        try {
+
+            pwd = new File(System.getProperty("test.classes",".")).toURL();
+        } catch (MalformedURLException e) {
+            throw new RuntimeException("Test failed.", e);
+        }
+        URL[] urls = new URL[] { pwd };
+
+         MyClassLoader appClassLoader = new MyClassLoader(urls, "test0");
+         WeakReference<MyClassLoader> ref =
+                 new WeakReference<MyClassLoader>(appClassLoader);
+
+
+         Thread appThread = new Thread(appsThreadGroup, launcher, "AppThread-0");
+         appThread.setContextClassLoader(appClassLoader);
+
+         appThread.start();
+         appClassLoader = null;
+         launcher = null;
+         appThread = null;
+
+         /* wait for laucnh completion */
+         try {
+             launchSignal.await();
+         } catch (InterruptedException e) {
+         }
+
+         /* check if launch failed */
+         if (launchFailure != null) {
+             throw new RuntimeException("Test failed.", launchFailure);
+         }
+
+         /* wait for test app excution completion */
+         try {
+             doneSignal.await();
+         } catch (InterruptedException e) {
+         }
+
+         /* give a chence to GC */
+         waitAndGC(5);
+
+         if (ref.get() != null) {
+             throw new RuntimeException("Test failed: classloader is still alive");
+         }
+
+         System.out.println("Test passed.");
+    }
+
+    private static class MyClassLoader extends URLClassLoader {
+
+        private static boolean verbose =
+            Boolean.getBoolean("verboseClassLoading");
+        private String uniqClassName;
+
+        public MyClassLoader(URL[] urls, String uniq) {
+            super(urls);
+
+            uniqClassName = uniq;
+        }
+
+        public Class loadClass(String name) throws ClassNotFoundException {
+            if (verbose) {
+                System.out.printf("%s: load class %s\n", uniqClassName, name);
+            }
+            if (uniqClassName.equals(name)) {
+                return Object.class;
+            }
+            return super.loadClass(name);
+        }
+
+        public String toString() {
+            return "MyClassLoader(" + uniqClassName + ")";
+        }
+    }
+
+    private static void waitAndGC(int sec) {
+        int cnt = sec;
+        System.out.print("Wait ");
+        while (cnt-- > 0) {
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+            }
+            // do GC every 3 seconds
+            if (cnt % 3 == 2) {
+                System.gc();
+                System.out.print("+");
+            } else {
+                System.out.print(".");
+            }
+            //checkErrors();
+        }
+        System.out.println("");
+    }
+}
+
+
+class AppTest {
+    public AppTest() {
+
+    }
+
+    public void launch(CountDownLatch done) {
+        Logger log = Logger.getLogger("app_test_logger");
+        log.fine("Test app is launched");
+
+        done.countDown();
+    }
+}
--- a/jdk/test/java/util/logging/LoggingDeadlock2.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/util/logging/LoggingDeadlock2.java	Fri Apr 10 13:05:12 2009 -0700
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug     6467152
- *
+ * @ignore until 6716076 is fixed
  * @summary deadlock occurs in LogManager initialization and JVM termination
  * @author  Serguei Spitsyn / Hittachi
  *
--- a/jdk/test/java/util/regex/RegExTest.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/util/regex/RegExTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -3389,6 +3389,11 @@
               "gname",
               "yyy");
 
+        check(Pattern.compile("x+(?<8gname>y+)z+"),
+              "xxxyyyzzz",
+              "8gname",
+              "yyy");
+
         //backref
         Pattern pattern = Pattern.compile("(a*)bc\\1");
         check(pattern, "zzzaabcazzz", true);  // found "abca"
--- a/jdk/test/java/util/zip/ZipFile/LargeZipFile.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/java/util/zip/ZipFile/LargeZipFile.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,26 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
 import java.io.*;
 import java.nio.*;
 import java.util.*;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/metadata/BooleanAttributes.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,202 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 5082756
+ * @summary ensure that boolean attributes follow ( "TRUE" | "FALSE" )
+ *          including correct (i.e. upper) case
+ *
+ * @run main BooleanAttributes
+ */
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.StringReader;
+import java.util.Arrays;
+import java.util.List;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageInputStream;
+import javax.imageio.stream.ImageOutputStream;
+import javax.imageio.stream.MemoryCacheImageInputStream;
+import javax.imageio.stream.MemoryCacheImageOutputStream;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class BooleanAttributes {
+
+    private static TransformerFactory transformerFactory =
+        TransformerFactory.newInstance();
+
+    private static XPath xpathEngine = XPathFactory.newInstance().newXPath();
+
+    public static void main(String[] args) throws Exception {
+        test("image/png", false, "<javax_imageio_1.0 />",
+             "Chroma/BlackIsZero/@value",
+             "Compression/Lossless/@value");
+
+        test("image/png", false,
+             "<javax_imageio_png_1.0>" +
+             "<iTXt><iTXtEntry keyword='Comment' compressionFlag='TRUE' " +
+             "compressionMethod='0' languageTag='en' " +
+             "translatedKeyword='comment' text='foo'/></iTXt>" +
+             "</javax_imageio_png_1.0>",
+             "iTXt/iTXtEntry/@compressionFlag");
+
+        test("image/png", false,
+             "<javax_imageio_png_1.0>" +
+             "<iTXt><iTXtEntry keyword='Comment' compressionFlag='FALSE' " +
+             "compressionMethod='0' languageTag='en' " +
+             "translatedKeyword='comment' text='foo'/></iTXt>" +
+             "</javax_imageio_png_1.0>",
+             "iTXt/iTXtEntry/@compressionFlag");
+
+        test("image/gif", false, "<javax_imageio_1.0 />",
+             "Chroma/BlackIsZero/@value",
+             "Compression/Lossless/@value");
+
+        test("image/gif", false,
+             "<javax_imageio_gif_image_1.0>" +
+             "<ImageDescriptor imageLeftPosition='0' imageTopPosition='0' " +
+             "imageWidth='16' imageHeight='16' interlaceFlag='TRUE' />" +
+             "<LocalColorTable sizeOfLocalColorTable='2' " +
+             "backgroundColorIndex='1' sortFlag='TRUE'>" +
+             "<ColorTableEntry index='0' red='0' green='0' blue='0' />" +
+             "<ColorTableEntry index='1' red='255' green='255' blue='255' />" +
+             "</LocalColorTable>" +
+             "<GraphicControlExtension disposalMethod='doNotDispose' " +
+             "userInputFlag='FALSE' transparentColorFlag='TRUE' " +
+             "delayTime='100' transparentColorIndex='1' />" +
+             "</javax_imageio_gif_image_1.0>",
+             "ImageDescriptor/@interlaceFlag",
+             "LocalColorTable/@sortFlag",
+             "GraphicControlExtension/@userInputFlag",
+             "GraphicControlExtension/@transparentColorFlag");
+
+        test("image/gif", true,
+             "<javax_imageio_gif_stream_1.0>" +
+             "<GlobalColorTable sizeOfGlobalColorTable='2' " +
+             "backgroundColorIndex='1' sortFlag='TRUE'>" +
+             "<ColorTableEntry index='0' red='0' green='0' blue='0' />" +
+             "<ColorTableEntry index='1' red='255' green='255' blue='255' />" +
+             "</GlobalColorTable>" +
+             "</javax_imageio_gif_stream_1.0>",
+             "GlobalColorTable/@sortFlag");
+
+        test("image/jpeg", false, "<javax_imageio_1.0 />",
+             "Compression/Lossless/@value");
+    }
+
+    private static void transform(Source src, Result dst)
+        throws Exception
+    {
+        transformerFactory.newTransformer().transform(src, dst);
+    }
+
+    private static void verify(Node meta, String[] xpaths, boolean required)
+        throws Exception
+    {
+        for (String xpath: xpaths) {
+            NodeList list = (NodeList)
+                xpathEngine.evaluate(xpath, meta, XPathConstants.NODESET);
+            if (list.getLength() == 0 && required)
+                throw new AssertionError("Missing value: " + xpath);
+            for (int i = 0; i < list.getLength(); ++i) {
+                String value = list.item(i).getNodeValue();
+                if (!(value.equals("TRUE") || value.equals("FALSE")))
+                    throw new AssertionError(xpath + " has value " + value);
+            }
+        }
+    }
+
+    public static void test(String mimeType, boolean useStreamMeta,
+                            String metaXml, String... boolXpaths)
+        throws Exception
+    {
+        BufferedImage img =
+            new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
+        ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
+        iw.setOutput(ios);
+        ImageWriteParam param = null;
+        IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
+        IIOMetadata imageMeta =
+            iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
+        IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
+        Source src = new StreamSource(new StringReader(metaXml));
+        DOMResult dst = new DOMResult();
+        transform(src, dst);
+        Document doc = (Document)dst.getNode();
+        Element node = doc.getDocumentElement();
+        String metaFormat = node.getNodeName();
+
+        // Verify that the default metadata gets formatted correctly.
+        verify(meta.getAsTree(metaFormat), boolXpaths, false);
+
+        meta.mergeTree(metaFormat, node);
+
+        // Verify that the merged metadata gets formatte correctly.
+        verify(meta.getAsTree(metaFormat), boolXpaths, true);
+
+        iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
+        iw.dispose();
+        ios.close();
+        ImageReader ir = ImageIO.getImageReader(iw);
+        byte[] bytes = os.toByteArray();
+        if (bytes.length == 0)
+            throw new AssertionError("Zero length image file");
+        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
+        ImageInputStream iis = new MemoryCacheImageInputStream(is);
+        ir.setInput(iis);
+        if (useStreamMeta) meta = ir.getStreamMetadata();
+        else meta = ir.getImageMetadata(0);
+
+        // Verify again after writing and re-reading the image
+        verify(meta.getAsTree(metaFormat), boolXpaths, true);
+    }
+
+    public static void xtest(Object... eatAnyArguments) {
+        System.err.println("Disabled test! Change xtest back into test!");
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/plugins/gif/EncodeSubImageTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug     6795544
+ *
+ * @summary Test verifes that Image I/O gif writer correctly handles
+ *          buffered images based on translated reasters (typically
+ *          produced by getSubImage() method).
+ *
+ * @run     main EncodeSubImageTest gif
+ */
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.image.BufferedImage;
+import java.awt.image.Raster;
+import java.io.File;
+import java.io.IOException;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.ImageOutputStream;
+
+public class EncodeSubImageTest {
+    private static String format = "gif";
+    private static ImageWriter writer;
+    private static String file_suffix;
+    private static final int subSampleX = 2;
+    private static final int subSampleY = 2;
+
+    public static void main(String[] args) throws IOException {
+        if (args.length > 0) {
+            format = args[0];
+        }
+
+        writer = ImageIO.getImageWritersByFormatName(format).next();
+
+        file_suffix =writer.getOriginatingProvider().getFileSuffixes()[0];
+
+        BufferedImage src = createTestImage();
+        EncodeSubImageTest m1 = new EncodeSubImageTest(src);
+        m1.doTest("test_src");
+
+        BufferedImage sub = src.getSubimage(subImageOffset, subImageOffset,
+                src.getWidth() - 2 * subImageOffset,
+                src.getHeight() - 2 * subImageOffset);
+        EncodeSubImageTest m2 = new EncodeSubImageTest(sub);
+        m2.doTest("test_sub");
+    }
+
+    BufferedImage img;
+
+    public EncodeSubImageTest(BufferedImage img) {
+        this.img = img;
+    }
+
+    public void doTest(String prefix) throws IOException {
+        System.out.println(prefix);
+        File f = new File(prefix + file_suffix);
+        write(f, false);
+        verify(f, false);
+
+        System.out.println(prefix + "_subsampled");
+        f = new File(prefix + "_subsampled");
+        write(f, true);
+        verify(f, true);
+
+        System.out.println(prefix + ": Test PASSED.");
+    }
+
+    private static final int subImageOffset = 10;
+
+    private void verify(File f, boolean isSubsampled) {
+        BufferedImage dst = null;
+        try {
+            dst = ImageIO.read(f);
+        } catch (IOException e) {
+            throw new RuntimeException("Test FAILED: can't readin test image " +
+                f.getAbsolutePath(), e);
+        }
+        if (dst == null) {
+            throw new RuntimeException("Test FAILED: no dst image available.");
+        }
+
+        checkPixel(dst, 0, 0, isSubsampled);
+
+        checkPixel(dst, img.getWidth() / 2, img.getHeight() / 2, isSubsampled);
+    }
+
+    private void checkPixel(BufferedImage dst, int x, int y,
+                            boolean isSubsampled)
+    {
+        int dx = isSubsampled ? x / subSampleX : x;
+        int dy = isSubsampled ? y / subSampleY : y;
+        int src_rgb = img.getRGB(x, y);
+        System.out.printf("src_rgb: %x\n", src_rgb);
+
+        int dst_rgb = dst.getRGB(dx, dy);
+        System.out.printf("dst_rgb: %x\n", dst_rgb);
+
+        if (src_rgb != dst_rgb) {
+            throw new RuntimeException("Test FAILED: invalid color in dst");
+        }
+    }
+
+    private static BufferedImage createTestImage() {
+        int w = 100;
+        int h = 100;
+
+        BufferedImage src = new BufferedImage(w, h,
+                BufferedImage.TYPE_BYTE_INDEXED);
+        Graphics g = src.createGraphics();
+        g.setColor(Color.red);
+        g.fillRect(0, 0, w, h);
+        g.setColor(Color.green);
+        g.fillRect(subImageOffset, subImageOffset,
+                w - 2 * subImageOffset, h - 2* subImageOffset);
+        g.setColor(Color.blue);
+        g.fillRect(2 * subImageOffset, 2 * subImageOffset,
+                w - 4 * subImageOffset, h - 4 * subImageOffset);
+        g.dispose();
+
+        return src;
+    }
+
+    private void write(File f, boolean subsample) throws IOException {
+        ImageOutputStream ios = ImageIO.createImageOutputStream(f);
+
+        writer.setOutput(ios);
+        ImageWriteParam p = writer.getDefaultWriteParam();
+        if (subsample) {
+            p.setSourceSubsampling(subSampleX, subSampleY, 0, 0);
+        }
+        writer.write(null, new IIOImage(img, null, null), p);
+        ios.close();
+        writer.reset();
+    }
+}
--- a/jdk/test/javax/imageio/plugins/png/ITXtTest.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/javax/imageio/plugins/png/ITXtTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -123,7 +123,7 @@
         }
         t.keyword = e.getAttribute("keyword");
         t.isCompressed =
-            (Integer.valueOf(e.getAttribute("compressionFlag")).intValue() == 1);
+            Boolean.valueOf(e.getAttribute("compressionFlag")).booleanValue();
         t.compression =
             Integer.valueOf(e.getAttribute("compressionMethod")).intValue();
         t.language = e.getAttribute("languageTag");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/plugins/png/ItxtUtf8Test.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,241 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6541476 6782079
+ * @summary Write and read a PNG file including an non-latin1 iTXt chunk
+ *          Test also verifies that trunkated png images does not cause
+ *          an OoutOfMemory error.
+ *
+ * @run main ItxtUtf8Test
+ *
+ * @run main/othervm/timeout=10 -Xmx2m ItxtUtf8Test truncate
+ */
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.List;
+import javax.imageio.IIOException;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.ImageWriter;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageInputStream;
+import javax.imageio.stream.ImageOutputStream;
+import javax.imageio.stream.MemoryCacheImageInputStream;
+import javax.imageio.stream.MemoryCacheImageOutputStream;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.bootstrap.DOMImplementationRegistry;
+
+public class ItxtUtf8Test {
+
+    public static final String
+    TEXT = "\u24c9\u24d4\u24e7\u24e3" +
+      "\ud835\udc13\ud835\udc1e\ud835\udc31\ud835\udc2d" +
+      "\u24c9\u24d4\u24e7\u24e3", // a repetition for compression
+    VERBATIM = "\u24e5\u24d4\u24e1\u24d1\u24d0\u24e3\u24d8\u24dc",
+    COMPRESSED = "\u24d2\u24de\u24dc\u24df\u24e1\u24d4\u24e2\u24e2\u24d4\u24d3";
+
+    public static final byte[]
+    VBYTES = {
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x56, // chunk length
+        (byte)0x69, (byte)0x54, (byte)0x58, (byte)0x74, // chunk type "iTXt"
+        (byte)0x76, (byte)0x65, (byte)0x72, (byte)0x62,
+        (byte)0x61, (byte)0x74, (byte)0x69, (byte)0x6d, // keyword "verbatim"
+        (byte)0x00, // separator terminating keyword
+        (byte)0x00, // compression flag
+        (byte)0x00, // compression method, must be zero
+        (byte)0x78, (byte)0x2d, (byte)0x63, (byte)0x69,
+        (byte)0x72, (byte)0x63, (byte)0x6c, (byte)0x65,
+        (byte)0x64, // language tag "x-circled"
+        (byte)0x00, // separator terminating language tag
+        (byte)0xe2, (byte)0x93, (byte)0xa5, // '\u24e5'
+        (byte)0xe2, (byte)0x93, (byte)0x94, // '\u24d4'
+        (byte)0xe2, (byte)0x93, (byte)0xa1, // '\u24e1'
+        (byte)0xe2, (byte)0x93, (byte)0x91, // '\u24d1'
+        (byte)0xe2, (byte)0x93, (byte)0x90, // '\u24d0'
+        (byte)0xe2, (byte)0x93, (byte)0xa3, // '\u24e3'
+        (byte)0xe2, (byte)0x93, (byte)0x98, // '\u24d8'
+        (byte)0xe2, (byte)0x93, (byte)0x9c, // '\u24dc'
+        (byte)0x00, // separator terminating the translated keyword
+        (byte)0xe2, (byte)0x93, (byte)0x89, // '\u24c9'
+        (byte)0xe2, (byte)0x93, (byte)0x94, // '\u24d4'
+        (byte)0xe2, (byte)0x93, (byte)0xa7, // '\u24e7'
+        (byte)0xe2, (byte)0x93, (byte)0xa3, // '\u24e3'
+        (byte)0xf0, (byte)0x9d, (byte)0x90, (byte)0x93, // '\ud835\udc13'
+        (byte)0xf0, (byte)0x9d, (byte)0x90, (byte)0x9e, // '\ud835\udc1e'
+        (byte)0xf0, (byte)0x9d, (byte)0x90, (byte)0xb1, // '\ud835\udc31'
+        (byte)0xf0, (byte)0x9d, (byte)0x90, (byte)0xad, // '\ud835\udc2d'
+        (byte)0xe2, (byte)0x93, (byte)0x89, // '\u24c9'
+        (byte)0xe2, (byte)0x93, (byte)0x94, // '\u24d4'
+        (byte)0xe2, (byte)0x93, (byte)0xa7, // '\u24e7'
+        (byte)0xe2, (byte)0x93, (byte)0xa3, // '\u24e3'
+        (byte)0xb5, (byte)0xcc, (byte)0x97, (byte)0x56 // CRC
+    },
+    CBYTES = {
+        // we don't want to check the chunk length,
+        // as this might depend on implementation.
+        (byte)0x69, (byte)0x54, (byte)0x58, (byte)0x74, // chunk type "iTXt"
+        (byte)0x63, (byte)0x6f, (byte)0x6d, (byte)0x70,
+        (byte)0x72, (byte)0x65, (byte)0x73, (byte)0x73,
+        (byte)0x65, (byte)0x64, // keyword "compressed"
+        (byte)0x00, // separator terminating keyword
+        (byte)0x01, // compression flag
+        (byte)0x00, // compression method, 0=deflate
+        (byte)0x78, (byte)0x2d, (byte)0x63, (byte)0x69,
+        (byte)0x72, (byte)0x63, (byte)0x6c, (byte)0x65,
+        (byte)0x64, // language tag "x-circled"
+        (byte)0x00, // separator terminating language tag
+        // we don't want to check the actual compressed data,
+        // as this might depend on implementation.
+    };
+/*
+*/
+
+    public static void main(String[] args) throws Exception {
+        List argList = Arrays.asList(args);
+        if (argList.contains("truncate")) {
+            try {
+                runTest(false, true);
+                throw new AssertionError("Expect an error for truncated file");
+            }
+            catch (IIOException e) {
+                // expected an error for a truncated image file.
+            }
+        }
+        else {
+            runTest(argList.contains("dump"), false);
+        }
+    }
+
+    public static void runTest(boolean dump, boolean truncate)
+        throws Exception
+    {
+        String format = "javax_imageio_png_1.0";
+        BufferedImage img =
+            new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
+        ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
+        iw.setOutput(ios);
+        IIOMetadata meta =
+            iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
+        DOMImplementationRegistry registry;
+        registry = DOMImplementationRegistry.newInstance();
+        DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
+        Document doc = impl.createDocument(null, format, null);
+        Element root, itxt, entry;
+        root = doc.getDocumentElement();
+        root.appendChild(itxt = doc.createElement("iTXt"));
+        itxt.appendChild(entry = doc.createElement("iTXtEntry"));
+        entry.setAttribute("keyword", "verbatim");
+        entry.setAttribute("compressionFlag", "false");
+        entry.setAttribute("compressionMethod", "0");
+        entry.setAttribute("languageTag", "x-circled");
+        entry.setAttribute("translatedKeyword", VERBATIM);
+        entry.setAttribute("text", TEXT);
+        itxt.appendChild(entry = doc.createElement("iTXtEntry"));
+        entry.setAttribute("keyword", "compressed");
+        entry.setAttribute("compressionFlag", "true");
+        entry.setAttribute("compressionMethod", "0");
+        entry.setAttribute("languageTag", "x-circled");
+        entry.setAttribute("translatedKeyword", COMPRESSED);
+        entry.setAttribute("text", TEXT);
+        meta.mergeTree(format, root);
+        iw.write(new IIOImage(img, null, meta));
+        iw.dispose();
+
+        byte[] bytes = os.toByteArray();
+        if (dump)
+            System.out.write(bytes);
+        if (findBytes(VBYTES, bytes) < 0)
+            throw new AssertionError("verbatim block not found");
+        if (findBytes(CBYTES, bytes) < 0)
+            throw new AssertionError("compressed block not found");
+        int length = bytes.length;
+        if (truncate)
+            length = findBytes(VBYTES, bytes) + 32;
+
+        ImageReader ir = ImageIO.getImageReader(iw);
+        ByteArrayInputStream is = new ByteArrayInputStream(bytes, 0, length);
+        ImageInputStream iis = new MemoryCacheImageInputStream(is);
+        ir.setInput(iis);
+        meta = ir.getImageMetadata(0);
+        Node node = meta.getAsTree(format);
+        for (node = node.getFirstChild();
+             !"iTXt".equals(node.getNodeName());
+             node = node.getNextSibling());
+        boolean verbatimSeen = false, compressedSeen = false;
+        for (node = node.getFirstChild();
+             node != null;
+             node = node.getNextSibling()) {
+            entry = (Element)node;
+            String keyword = entry.getAttribute("keyword");
+            String translatedKeyword = entry.getAttribute("translatedKeyword");
+            String text = entry.getAttribute("text");
+            if ("verbatim".equals(keyword)) {
+                if (verbatimSeen) throw new AssertionError("Duplicate");
+                verbatimSeen = true;
+                if (!VERBATIM.equals(translatedKeyword))
+                    throw new AssertionError("Wrong translated keyword");
+                if (!TEXT.equals(text))
+                    throw new AssertionError("Wrong text");
+            }
+            else if ("compressed".equals(keyword)) {
+                if (compressedSeen) throw new AssertionError("Duplicate");
+                compressedSeen = true;
+                if (!COMPRESSED.equals(translatedKeyword))
+                    throw new AssertionError("Wrong translated keyword");
+                if (!TEXT.equals(text))
+                    throw new AssertionError("Wrong text");
+            }
+            else {
+                throw new AssertionError("Unexpected keyword");
+            }
+        }
+        if (!(verbatimSeen && compressedSeen))
+            throw new AssertionError("Missing chunk");
+    }
+
+    private static final int findBytes(byte[] needle, byte[] haystack) {
+        HAYSTACK: for (int h = 0; h <= haystack.length - needle.length; ++h) {
+            for (int n = 0; n < needle.length; ++n) {
+                if (needle[n] != haystack[h + n]) {
+                    continue HAYSTACK;
+                }
+            }
+            return h;
+        }
+        return -1;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/plugins/png/MergeStdCommentTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 5106550
+ * @summary Merge a comment using the standard metdata format
+ *          and only a minimal set of attributes
+ */
+
+import java.awt.image.BufferedImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.ImageWriter;
+import javax.imageio.metadata.IIOMetadata;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.bootstrap.DOMImplementationRegistry;
+
+public class MergeStdCommentTest {
+
+    public static void main(String[] args) throws Exception {
+        String format = "javax_imageio_1.0";
+        BufferedImage img =
+            new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
+        ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
+        IIOMetadata meta =
+            iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
+        DOMImplementationRegistry registry;
+        registry = DOMImplementationRegistry.newInstance();
+        DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
+        Document doc = impl.createDocument(null, format, null);
+        Element root, text, entry;
+        root = doc.getDocumentElement();
+        root.appendChild(text = doc.createElement("Text"));
+        text.appendChild(entry = doc.createElement("TextEntry"));
+        // keyword isn't #REQUIRED by the standard metadata format.
+        // However, it is required by the PNG format, so we include it here.
+        entry.setAttribute("keyword", "Comment");
+        entry.setAttribute("value", "Some demo comment");
+        meta.mergeTree(format, root);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/stream/StreamCloserLeak/run_test.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,205 @@
+#!/bin/ksh -p
+#
+# Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+# 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+#   @test
+#   @bug        6788096
+#   @summary    Test simulates the case of multiple applets executed in
+#               the same VM and verifies that ImageIO shutdown hook
+#               StreamCloser does not cause a leak of classloaders.
+#
+#   @build      test.Main
+#   @build      testapp.Main
+#   @run shell  run_test.sh
+
+# There are several resources which need to be present before many
+#  shell scripts can run.  Following are examples of how to check for
+#  many common ones.
+#
+# Note that the shell used is the Korn Shell, KSH
+#
+# Also note, it is recommended that make files NOT be used.  Rather,
+#  put the individual commands directly into this file.  That way,
+#  it is possible to use command line arguments and other shell tech-
+#  niques to find the compiler, etc on different systems.  For example,
+#  a different path could be used depending on whether this were a
+#  Solaris or Win32 machine, which is more difficult (if even possible)
+#  in a make file.
+
+
+# Beginning of subroutines:
+status=1
+
+#Call this from anywhere to fail the test with an error message
+# usage: fail "reason why the test failed"
+fail()
+ { echo "The test failed :-("
+   echo "$*" 1>&2
+   echo "exit status was $status"
+   exit $status
+ } #end of fail()
+
+#Call this from anywhere to pass the test with a message
+# usage: pass "reason why the test passed if applicable"
+pass()
+ { echo "The test passed!!!"
+   echo "$*" 1>&2
+   exit 0
+ } #end of pass()
+
+# end of subroutines
+
+
+# The beginning of the script proper
+
+# Checking for proper OS
+OS=`uname -s`
+case "$OS" in
+   SunOS )
+      VAR="One value for Sun"
+      DEFAULT_JDK=/usr/local/java/jdk1.2/solaris
+      FILESEP="/"
+      PATHSEP=":"
+      TMP="/tmp"
+      ;;
+
+   Linux )
+      VAR="A different value for Linux"
+      DEFAULT_JDK=/usr/local/java/jdk1.4/linux-i386
+      FILESEP="/"
+      PATHSEP=":"
+      TMP="/tmp"
+      ;;
+
+   Windows_95 | Windows_98 | Windows_NT | Windows_ME )
+      VAR="A different value for Win32"
+      DEFAULT_JDK=/usr/local/java/jdk1.2/win32
+      FILESEP="\\"
+      PATHSEP=";"
+      TMP=`cd "${SystemRoot}/Temp"; echo ${PWD}`
+      ;;
+
+   # catch all other OSs
+   * )
+      echo "Unrecognized system!  $OS"
+      fail "Unrecognized system!  $OS"
+      ;;
+esac
+
+# Want this test to run standalone as well as in the harness, so do the
+#  following to copy the test's directory into the harness's scratch directory
+#  and set all appropriate variables:
+
+if [ -z "${TESTJAVA}" ] ; then
+   # TESTJAVA is not set, so the test is running stand-alone.
+   # TESTJAVA holds the path to the root directory of the build of the JDK
+   # to be tested.  That is, any java files run explicitly in this shell
+   # should use TESTJAVA in the path to the java interpreter.
+   # So, we'll set this to the JDK spec'd on the command line.  If none
+   # is given on the command line, tell the user that and use a cheesy
+   # default.
+   # THIS IS THE JDK BEING TESTED.
+   if [ -n "$1" ] ;
+      then TESTJAVA=$1
+      else echo "no JDK specified on command line so using default!"
+	 TESTJAVA=$DEFAULT_JDK
+   fi
+   TESTSRC=.
+   TESTCLASSES=.
+   STANDALONE=1;
+fi
+echo "JDK under test is: $TESTJAVA"
+
+
+###############  YOUR TEST CODE HERE!!!!!!!  #############
+
+#All files required for the test should be in the same directory with
+# this file.  If converting a standalone test to run with the harness,
+# as long as all files are in the same directory and it returns 0 for
+# pass, you should be able to cut and paste it into here and it will
+# run with the test harness.
+
+# This is an example of running something -- test
+# The stuff below catches the exit status of test then passes or fails
+# this shell test as appropriate ( 0 status is considered a pass here )
+
+echo "Create TestApp.jar..."
+
+if [ -f TestApp.jar ] ; then
+    rm -f TestApp.jar
+fi
+
+${TESTJAVA}/bin/jar -cvf TestApp.jar -C ${TESTCLASSES} testapp
+
+if [ $? -ne "0" ] ; then
+    fail "Failed to create TestApp.jar"
+fi
+
+echo "Create Test.jar..."
+if [ -f Test.jar ] ; then
+    rm -f Test.jar
+fi
+
+${TESTJAVA}/bin/jar -cvf Test.jar -C ${TESTCLASSES} test
+
+if [ $? -ne 0 ] ; then
+    fail "Failed to create Test.jar"
+fi
+
+# Prepare temp dir for cahce files
+mkdir ./tmp
+if [ $? -ne 0 ] ; then
+    fail "Unable to create temp directory."
+fi
+
+# Verify that all classoladers are destroyed
+${TESTJAVA}/bin/java -cp Test.jar test.Main
+if [ $? -ne 0 ] ; then
+    fail "Test FAILED: some classloaders weren't destroyed."
+fi
+
+
+# Verify that ImageIO shutdown hook works correcly
+${TESTJAVA}/bin/java -cp Test.jar -DforgetSomeStreams=true test.Main
+if [ $? -ne 0 ] ; then
+    fail "Test FAILED: some classloaders weren't destroyed of shutdown hook failed."
+fi
+
+# sanity check: verify that all cache files were deleted
+cache_files=`ls tmp`
+
+if [ "x${cache_files}" != "x" ] ; then
+    echo "WARNING: some cache files was not deleted: ${cache_files}"
+fi
+
+echo "Test done."
+
+status=$?
+
+if [ $status -eq "0" ] ; then
+    pass ""
+else
+    fail "Test failed due to test plugin was not found."
+fi
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/stream/StreamCloserLeak/test/Main.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,284 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package test;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.HashMap;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import javax.imageio.stream.ImageInputStream;
+import sun.awt.AppContext;
+import sun.awt.SunToolkit;
+
+public class Main {
+
+    private static ThreadGroup appsThreadGroup;
+
+    private static WeakHashMap<MyClassLoader, String> refs =
+            new WeakHashMap<MyClassLoader, String>();
+
+    /** Collection to simulate forgrotten streams **/
+    private static HashMap<String, ImageInputStream> strongRefs =
+            new HashMap<String, ImageInputStream>();
+
+    private static ConcurrentLinkedQueue<Throwable> problems =
+            new ConcurrentLinkedQueue<Throwable>();
+
+    private static AppContext mainAppContext = null;
+
+    private static CountDownLatch doneSignal;
+
+    private static final int gcTimeout =
+        Integer.getInteger("gcTimeout", 10).intValue();
+
+    private static boolean forgetSomeStreams =
+            Boolean.getBoolean("forgetSomeStreams");
+
+    public static void main(String[] args) throws IOException {
+        mainAppContext = SunToolkit.createNewAppContext();
+        System.out.println("Current context class loader: " +
+                Thread.currentThread().getContextClassLoader());
+
+        appsThreadGroup = new ThreadGroup("MyAppsThreadGroup");
+
+        File jar = new File("TestApp.jar");
+        if (!jar.exists()) {
+            System.out.println(jar.getAbsolutePath() + " was not found!\n" +
+                    "Please install the jar with test application correctly!");
+            throw new RuntimeException("Test failed: no TestApp.jar");
+        }
+
+        URL[] urls = new URL[]{jar.toURL()};
+
+        int numApps = Integer.getInteger("numApps", 20).intValue();
+
+        doneSignal = new CountDownLatch(numApps);
+        int cnt = 0;
+        while (cnt++ < numApps) {
+            launch(urls, "testapp.Main", "launch");
+
+            checkErrors();
+        }
+
+        System.out.println("Wait for apps completion....");
+
+        try {
+            doneSignal.await();
+        } catch (InterruptedException e) {
+        }
+
+        System.out.println("All apps finished.");
+
+        System.gc();
+
+        System.out.flush();
+
+        System.out.println("Enumerate strong refs:");
+        for (String is : strongRefs.keySet()) {
+            System.out.println("-> " + is);
+        }
+
+        System.out.println("=======================");
+
+        // wait few seconds
+        waitAndGC(gcTimeout);
+
+        doneSignal = new CountDownLatch(1);
+
+        Runnable workaround = new Runnable() {
+
+            public void run() {
+                AppContext ctx = null;
+                try {
+                    ctx = SunToolkit.createNewAppContext();
+                } catch (Throwable e) {
+                    // ignore...
+                } finally {
+                    doneSignal.countDown();
+                }
+            }
+        };
+
+        Thread wt = new Thread(appsThreadGroup, workaround, "Workaround");
+        wt.setContextClassLoader(new MyClassLoader(urls, "workaround"));
+        wt.start();
+        wt = null;
+        workaround = null;
+
+        System.out.println("Wait for workaround completion...");
+
+        try {
+            doneSignal.await();
+        } catch (InterruptedException e) {
+        }
+
+        // give a chance to GC
+        waitAndGC(gcTimeout);
+
+        if (!refs.isEmpty()) {
+            System.out.println("Classloaders still alive:");
+
+            for (MyClassLoader l : refs.keySet()) {
+                String val = refs.get(l);
+
+                if (val == null) {
+                    throw new RuntimeException("Test FAILED: Invalid classloader name");
+                }
+                System.out.println("->" + val + (strongRefs.get(val) != null ?
+                                    " (has strong ref)" : ""));
+                if (strongRefs.get(val) == null) {
+                    throw new RuntimeException("Test FAILED: exta class loader is detected! ");
+                }
+            }
+        } else {
+            System.out.println("No alive class loaders!!");
+        }
+        System.out.println("Test PASSED.");
+    }
+
+    private static void waitAndGC(int sec) {
+        int cnt = sec;
+        System.out.print("Wait ");
+        while (cnt-- > 0) {
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException e) {
+            }
+            // do GC every 3 seconds
+            if (cnt % 3 == 2) {
+                System.gc();
+                System.out.print("+");
+            } else {
+                System.out.print(".");
+            }
+            checkErrors();
+        }
+        System.out.println("");
+    }
+
+    private static void checkErrors() {
+        while (!problems.isEmpty()) {
+            Throwable theProblem = problems.poll();
+            System.out.println("Test FAILED!");
+            do {
+                theProblem.printStackTrace(System.out);
+                theProblem = theProblem.getCause();
+            } while (theProblem != null);
+            throw new RuntimeException("Test FAILED");
+        }
+    }
+    static int counter = 0;
+
+    private static void launch(URL[] urls, final String className,
+                               final String methodName)
+    {
+        final String uniqClassName = "testapp/Uniq" + counter;
+        final boolean saveStrongRef = forgetSomeStreams ? (counter % 5 == 4) : false;
+
+        System.out.printf("%s: launch the app\n", uniqClassName);
+        Runnable launchIt = new Runnable() {
+            public void run() {
+                AppContext ctx = SunToolkit.createNewAppContext();
+
+                try {
+                    Class appMain =
+                        ctx.getContextClassLoader().loadClass(className);
+                    Method launch = appMain.getDeclaredMethod(methodName,
+                                strongRefs.getClass());
+
+                    Constructor c = appMain.getConstructor(String.class,
+                                                           problems.getClass());
+
+                    Object o = c.newInstance(uniqClassName, problems);
+
+                    if (saveStrongRef) {
+                        System.out.printf("%s: force strong ref\n",
+                                          uniqClassName);
+                        launch.invoke(o, strongRefs);
+                    } else {
+                        HashMap<String, ImageInputStream> empty = null;
+                        launch.invoke(o, empty);
+                    }
+
+                    ctx = null;
+                } catch (Throwable e) {
+                    problems.add(e);
+                } finally {
+                    doneSignal.countDown();
+                }
+            }
+        };
+
+        MyClassLoader appClassLoader = new MyClassLoader(urls, uniqClassName);
+
+        refs.put(appClassLoader, uniqClassName);
+
+        Thread appThread = new Thread(appsThreadGroup, launchIt,
+                                      "AppThread" + counter++);
+        appThread.setContextClassLoader(appClassLoader);
+
+        appThread.start();
+        launchIt = null;
+        appThread = null;
+        appClassLoader = null;
+    }
+
+    private static class MyClassLoader extends URLClassLoader {
+
+        private static boolean verbose =
+            Boolean.getBoolean("verboseClassLoading");
+        private String uniqClassName;
+
+        public MyClassLoader(URL[] urls, String uniq) {
+            super(urls);
+
+            uniqClassName = uniq;
+        }
+
+        public Class loadClass(String name) throws ClassNotFoundException {
+            if (verbose) {
+                System.out.printf("%s: load class %s\n", uniqClassName, name);
+            }
+            if (uniqClassName.equals(name)) {
+                return Object.class;
+            }
+            return super.loadClass(name);
+        }
+
+        public String toString() {
+            return "MyClassLoader(" + uniqClassName + ")";
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/imageio/stream/StreamCloserLeak/testapp/Main.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package testapp;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import javax.imageio.stream.FileCacheImageInputStream;
+import javax.imageio.stream.ImageInputStream;
+
+public class Main {
+
+    public static void main(String[] args) {
+        Main o = new Main("testapp.some.class", null);
+        o.launch(null);
+    }
+
+    private final  String uniqClassName;
+    private final ConcurrentLinkedQueue<Throwable> problems;
+
+    public Main(String uniq, ConcurrentLinkedQueue<Throwable> p) {
+        uniqClassName = uniq;
+        problems = p;
+    }
+
+    public void launch(HashMap<String, ImageInputStream> refs) {
+        System.out.printf("%s: current context class loader: %s\n",
+                          uniqClassName,
+                Thread.currentThread().getContextClassLoader());
+        try {
+            byte[] data = new byte[1024];
+            ByteArrayInputStream bais = new ByteArrayInputStream(data);
+            MyImageInputStream iis = new MyImageInputStream(bais,
+                                                            uniqClassName,
+                                                            problems);
+            if (refs != null) {
+                System.out.printf("%s: added to strong store\n",
+                                  uniqClassName);
+                refs.put(uniqClassName, iis);
+            }
+            iis.read();
+            //leave stream open : let's shutdown hook work!
+        } catch (IOException e) {
+            problems.add(e);
+        }
+    }
+
+    private static class MyImageInputStream extends FileCacheImageInputStream {
+        private final String uniqClassName;
+        private ConcurrentLinkedQueue<Throwable> problems;
+        public MyImageInputStream(InputStream is, String uniq,
+                                  ConcurrentLinkedQueue<Throwable> p) throws IOException
+   {
+            super(is, new File("tmp"));
+            uniqClassName = uniq;
+            problems = p;
+        }
+
+        @Override
+        public void close() throws IOException {
+            Test t = new Test();
+            try {
+                t.doTest(uniqClassName);
+            } catch (Throwable e) {
+                problems.add(e);
+            }
+
+            super.close();
+
+            problems = null;
+        }
+    }
+}
+
+class Test {
+    public void doTest(String uniqClassName) throws ClassNotFoundException {
+        System.out.printf("%s: Current thread: %s\n", uniqClassName,
+                          Thread.currentThread());
+
+        ClassLoader thisCL = this.getClass().getClassLoader();
+        Class uniq = thisCL.loadClass(uniqClassName);
+
+        System.out.printf("%s: test is done!\n",uniqClassName);
+    }
+}
--- a/jdk/test/javax/script/Test3.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/javax/script/Test3.java	Fri Apr 10 13:05:12 2009 -0700
@@ -4,7 +4,6 @@
  *
  * 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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/awt/image/DrawByteBinary.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug     6800846
+ *
+ * @summary Test verifes that images with short palette are rendered
+ *          withourt artifacts.
+ *
+ * @run     main DrawByteBinary
+ */
+
+
+import java.awt.*;
+import java.awt.color.*;
+import java.awt.image.*;
+import static java.awt.image.BufferedImage.*;
+
+
+public class DrawByteBinary {
+
+    public static void main(String args[]) {
+        int w = 100, h = 30;
+        int x = 10;
+        byte[] arr = {(byte)0xff, (byte)0x0, (byte)0x00};
+
+        IndexColorModel newCM = new IndexColorModel(1, 2, arr, arr, arr);
+        BufferedImage orig = new BufferedImage(w, h, TYPE_BYTE_BINARY, newCM);
+        Graphics2D g2d = orig.createGraphics();
+        g2d.setColor(Color.white);
+        g2d.fillRect(0, 0, w, h);
+        g2d.setColor(Color.black);
+        g2d.drawLine(x, 0, x, h);
+        g2d.dispose();
+
+        IndexColorModel origCM = (IndexColorModel)orig.getColorModel();
+        BufferedImage test = new BufferedImage(w, h, TYPE_BYTE_BINARY,origCM);
+        g2d = test.createGraphics();
+        g2d.drawImage(orig, 0, 0, null);
+        g2d.dispose();
+
+        int y = h / 2;
+
+        // we expect white color outside the line
+        if (test.getRGB(x - 1, y) != 0xffffffff) {
+            throw new RuntimeException("Invalid color outside the line.");
+        }
+
+        // we expect black color on the line
+        if (test.getRGB(x, y) != 0xff000000) {
+            throw new RuntimeException("Invalid color on the line.");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/java2d/cmm/ProfileOp/ReadWriteProfileTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6476665 6523403 6733501
+ * @summary Verifies reading and writing profiles and tags of the standard color
+ * spaces
+ * @run main ReadWriteProfileTest
+ */
+import java.awt.color.ColorSpace;
+import java.awt.color.ICC_Profile;
+import java.util.*;
+import java.nio.*;
+import java.util.Hashtable;
+
+public class ReadWriteProfileTest implements Runnable {
+    /* Location of the tag sig counter in 4-byte words */
+    final static int TAG_COUNT_OFFSET = 32;
+
+    /* Location of the tag sig table in 4-byte words */
+    final static int TAG_ELEM_OFFSET = 33;
+
+    static byte[][] profiles;
+    static int [][] tagSigs;
+    static Hashtable<Integer,byte[]> [] tags;
+
+    static int [] cspaces = {ColorSpace.CS_sRGB, ColorSpace.CS_PYCC,
+                             ColorSpace.CS_LINEAR_RGB, ColorSpace.CS_CIEXYZ,
+                             ColorSpace.CS_GRAY};
+
+    static String [] csNames = {"sRGB", "PYCC", "LINEAR_RGB", "CIEXYZ", "GRAY"};
+
+    static void getProfileTags(byte [] data, Hashtable tags) {
+        ByteBuffer byteBuf = ByteBuffer.wrap(data);
+        IntBuffer intBuf = byteBuf.asIntBuffer();
+        int tagCount = intBuf.get(TAG_COUNT_OFFSET);
+        intBuf.position(TAG_ELEM_OFFSET);
+        for (int i = 0; i < tagCount; i++) {
+            int tagSig = intBuf.get();
+            int tagDataOff = intBuf.get();
+            int tagSize = intBuf.get();
+
+            byte [] tagData = new byte[tagSize];
+            byteBuf.position(tagDataOff);
+            byteBuf.get(tagData);
+            tags.put(tagSig, tagData);
+        }
+    }
+
+    static {
+        profiles = new byte[cspaces.length][];
+        tags = new Hashtable[cspaces.length];
+
+        for (int i = 0; i < cspaces.length; i++) {
+            ICC_Profile pf = ICC_Profile.getInstance(cspaces[i]);
+            profiles[i] = pf.getData();
+            tags[i] = new Hashtable();
+            getProfileTags(profiles[i], tags[i]);
+        }
+    }
+
+    public void run() {
+        for (int i = 0; i < cspaces.length; i++) {
+            ICC_Profile pf = ICC_Profile.getInstance(cspaces[i]);
+            byte [] data = pf.getData();
+            pf = ICC_Profile.getInstance(data);
+            if (!Arrays.equals(data, profiles[i])) {
+                System.err.println("Incorrect result of getData() " + "with " +
+                                   csNames[i] + " profile");
+                throw new RuntimeException("Incorrect result of getData()");
+            }
+
+            for (int tagSig : tags[i].keySet()) {
+                byte [] tagData = pf.getData(tagSig);
+                byte [] empty = new byte[tagData.length];
+                pf.setData(tagSig, empty);
+                pf.setData(tagSig, tagData);
+
+                byte [] tagData1 = pf.getData(tagSig);
+
+                if (!Arrays.equals(tagData1, tags[i].get(tagSig)))
+                {
+                    System.err.println("Incorrect result of getData(int) with" +
+                                       " tag " +
+                                       Integer.toHexString(tagSig) +
+                                       " of " + csNames[i] + " profile");
+
+                    throw new RuntimeException("Incorrect result of " +
+                                               "getData(int)");
+                }
+            }
+        }
+    }
+
+    public static void main(String [] args) {
+        ReadWriteProfileTest test = new ReadWriteProfileTest();
+        test.run();
+    }
+}
--- a/jdk/test/sun/nio/cs/FindEncoderBugs.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/jdk/test/sun/nio/cs/FindEncoderBugs.java	Fri Apr 10 13:05:12 2009 -0700
@@ -526,4 +526,3 @@
         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
         if (failed > 0) throw new AssertionError("Some tests failed");}
 }
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/nio/cs/StrCodingBenchmark.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.util.*;
+import java.nio.*;
+import java.nio.charset.*;
+import java.util.concurrent.*;
+import java.util.regex.Pattern;
+
+/**
+ * Usage: java StringCodingBenchmark
+ * [-Diterations=N] [-Dsize=N] [-Dsubsize=N] [-Dmaxchar=N]
+ * [-Dfilter=REGEXP] [-DSecurityManager=true]
+ */
+public class StrCodingBenchmark {
+    abstract static class Job {
+        private final String name;
+        public Job(String name) { this.name = name; }
+        public String name() { return name; }
+        public abstract void work() throws Throwable;
+    }
+
+    private static void collectAllGarbage() {
+        final java.util.concurrent.CountDownLatch drained
+            = new java.util.concurrent.CountDownLatch(1);
+        try {
+            System.gc();        // enqueue finalizable objects
+            new Object() { protected void finalize() {
+                drained.countDown(); }};
+            System.gc();        // enqueue detector
+            drained.await();    // wait for finalizer queue to drain
+            System.gc();        // cleanup finalized objects
+        } catch (InterruptedException e) { throw new Error(e); }
+    }
+
+    /**
+     * Runs each job for long enough that all the runtime compilers
+     * have had plenty of time to warm up, i.e. get around to
+     * compiling everything worth compiling.
+     * Returns array of average times per job per run.
+     */
+    public static long[] time0(Job ... jobs) throws Throwable {
+        //final long warmupNanos = 10L * 1000L * 1000L * 1000L;
+        final long warmupNanos = 100L * 100L;
+        long[] nanoss = new long[jobs.length];
+        for (int i = 0; i < jobs.length; i++) {
+            collectAllGarbage();
+            long t0 = System.nanoTime();
+            long t;
+            int j = 0;
+            do { jobs[i].work(); j++; }
+            while ((t = System.nanoTime() - t0) < warmupNanos);
+            nanoss[i] = t/j;
+        }
+        return nanoss;
+    }
+
+    public static void time(Job ... jobs) throws Throwable {
+
+        long[] warmup = time0(jobs); // Warm up run
+        long[] nanoss = time0(jobs); // Real timing run
+        long[] milliss = new long[jobs.length];
+        double[] ratios = new double[jobs.length];
+
+        final String nameHeader   = "Method";
+        final String millisHeader = "Millis";
+        final String ratioHeader  = "Ratio";
+
+        int nameWidth   = nameHeader.length();
+        int millisWidth = millisHeader.length();
+        int ratioWidth  = ratioHeader.length();
+
+        for (int i = 0; i < jobs.length; i++) {
+            nameWidth = Math.max(nameWidth, jobs[i].name().length());
+
+            milliss[i] = nanoss[i]/(1000L * 1000L);
+            millisWidth = Math.max(millisWidth,
+                                   String.format("%d", milliss[i]).length());
+
+            ratios[i] = (double) nanoss[i] / (double) nanoss[0];
+            ratioWidth = Math.max(ratioWidth,
+                                  String.format("%.3f", ratios[i]).length());
+        }
+        String format = String.format("%%-%ds %%%dd %n",
+                                      nameWidth, millisWidth);
+        String headerFormat = String.format("%%-%ds %%%ds%n",
+                                            nameWidth, millisWidth);
+        System.out.printf(headerFormat, "Method", "Millis");
+
+        // Print out absolute and relative times, calibrated against first job
+        for (int i = 0; i < jobs.length; i++)
+            System.out.printf(format, jobs[i].name(), milliss[i], ratios[i]);
+    }
+
+    public static Job[] filter(Pattern filter, Job[] jobs) {
+        if (filter == null) return jobs;
+        Job[] newJobs = new Job[jobs.length];
+        int n = 0;
+        for (Job job : jobs)
+            if (filter.matcher(job.name()).find())
+                newJobs[n++] = job;
+        // Arrays.copyOf not available in JDK 5
+        Job[] ret = new Job[n];
+        System.arraycopy(newJobs, 0, ret, 0, n);
+        return ret;
+    }
+
+    static class PermissiveSecurityManger extends SecurityManager {
+        @Override public void checkPermission(java.security.Permission p) {
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        final int itrs = Integer.getInteger("iterations", 100000);
+        final int size       = Integer.getInteger("size", 2048);
+        final int subsize    = Integer.getInteger("subsize", 128);
+        final int maxchar    = Integer.getInteger("maxchar", 128);
+        final String regex = System.getProperty("filter");
+        final Pattern filter = (regex == null) ? null : Pattern.compile(regex);
+        final boolean useSecurityManager = Boolean.getBoolean("SecurityManager");
+        if (useSecurityManager)
+            System.setSecurityManager(new PermissiveSecurityManger());
+        final Random rnd = new Random();
+
+        for (Charset charset:  Charset.availableCharsets().values()) {
+            if (!("ISO-8859-1".equals(charset.name()) ||
+                  "US-ASCII".equals(charset.name()) ||
+                  charset.newDecoder() instanceof sun.nio.cs.SingleByte.Decoder))
+                continue;
+            final String csn = charset.name();
+            final Charset cs = charset;
+            final StringBuilder sb = new StringBuilder();
+            {
+                final CharsetEncoder enc = cs.newEncoder();
+                for (int i = 0; i < size; ) {
+                    char c = (char) rnd.nextInt(maxchar);
+                    if (enc.canEncode(c)) {
+                        sb.append(c);
+                        i++;
+                    }
+                }
+            }
+            final String string = sb.toString();
+            final byte[] bytes  = string.getBytes(cs);
+
+            System.out.printf("%n--------%s---------%n", csn);
+            for (int sz = 4; sz <= 2048; sz *= 2) {
+                System.out.printf("   [len=%d]%n", sz);
+                final byte[] bs  = Arrays.copyOf(bytes, sz);
+                final String str = new String(bs, csn);
+                Job[] jobs = {
+                    new Job("String decode: csn") {
+                    public void work() throws Throwable {
+                        for (int i = 0; i < itrs; i++)
+                            new String(bs, csn);
+                    }},
+
+                    new Job("String decode: cs") {
+                    public void work() throws Throwable {
+                        for (int i = 0; i < itrs; i++)
+                            new String(bs, cs);
+                    }},
+
+                    new Job("String encode: csn") {
+                    public void work() throws Throwable {
+                        for (int i = 0; i < itrs; i++)
+                                str.getBytes(csn);
+                    }},
+
+                    new Job("String encode: cs") {
+                    public void work() throws Throwable {
+                         for (int i = 0; i < itrs; i++)
+                          str.getBytes(cs);
+                    }},
+                };
+                time(filter(filter, jobs));
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/nio/cs/TestStringCoding.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 6636323 6636319
+   @summary Test if StringCoding and NIO result have the same de/encoding result
+ * @run main/timeout=2000 TestStringCoding
+ */
+
+import java.util.*;
+import java.nio.*;
+import java.nio.charset.*;
+
+public class TestStringCoding {
+    public static void main(String[] args) throws Throwable {
+
+        for (Boolean hasSM: new boolean[] { false, true }) {
+            if (hasSM)
+                System.setSecurityManager(new PermissiveSecurityManger());
+            for (Charset cs:  Charset.availableCharsets().values()) {
+                if ("ISO-2022-CN".equals(cs.name()) ||
+                    "x-COMPOUND_TEXT".equals(cs.name()) ||
+                    "x-JISAutoDetect".equals(cs.name()))
+                    continue;
+                System.out.printf("Testing(sm=%b) " + cs.name() + "....", hasSM);
+                // full bmp first
+                char[] bmpCA = new char[0x10000];
+                for (int i = 0; i < 0x10000; i++) {
+                     bmpCA[i] = (char)i;
+                }
+                byte[] sbBA = new byte[0x100];
+                for (int i = 0; i < 0x100; i++) {
+                    sbBA[i] = (byte)i;
+                }
+                test(cs, bmpCA, sbBA);
+                // "randomed" sizes
+                Random rnd = new Random();
+                for (int i = 0; i < 10; i++) {
+                    int clen = rnd.nextInt(0x10000);
+                    int blen = rnd.nextInt(0x100);
+                    //System.out.printf("    blen=%d, clen=%d%n", blen, clen);
+                    test(cs, Arrays.copyOf(bmpCA, clen), Arrays.copyOf(sbBA, blen));
+                    //add a pair of surrogates
+                    int pos = clen / 2;
+                    if ((pos + 1) < blen) {
+                        bmpCA[pos] = '\uD800';
+                        bmpCA[pos+1] = '\uDC00';
+                    }
+                    test(cs, Arrays.copyOf(bmpCA, clen), Arrays.copyOf(sbBA, blen));
+                }
+                System.out.println("done!");
+            }
+        }
+    }
+
+    static void test(Charset cs, char[] bmpCA, byte[] sbBA) throws Throwable {
+        String bmpStr = new String(bmpCA);
+        CharsetDecoder dec = cs.newDecoder()
+            .onMalformedInput(CodingErrorAction.REPLACE)
+            .onUnmappableCharacter(CodingErrorAction.REPLACE);
+        CharsetEncoder enc = cs.newEncoder()
+            .onMalformedInput(CodingErrorAction.REPLACE)
+            .onUnmappableCharacter(CodingErrorAction.REPLACE);
+
+        //getBytes(csn);
+        byte[] baSC = bmpStr.getBytes(cs.name());
+        ByteBuffer bf = enc.reset().encode(CharBuffer.wrap(bmpCA));
+        byte[] baNIO = new byte[bf.limit()];
+        bf.get(baNIO, 0, baNIO.length);
+        if (!Arrays.equals(baSC, baNIO))
+            throw new RuntimeException("getBytes(csn) failed  -> " + cs.name());
+
+        //getBytes(cs);
+        baSC = bmpStr.getBytes(cs);
+        if (!Arrays.equals(baSC, baNIO))
+            throw new RuntimeException("getBytes(cs) failed  -> " + cs.name());
+
+        //new String(csn);
+        String strSC = new String(sbBA, cs.name());
+        String strNIO = dec.reset().decode(ByteBuffer.wrap(sbBA)).toString();
+        if(!strNIO.equals(strSC))
+            throw new RuntimeException("new String(csn) failed  -> " + cs.name());
+
+        //new String(cs);
+        strSC = new String(sbBA, cs);
+        if (!strNIO.equals(strSC))
+            throw new RuntimeException("new String(cs) failed  -> " + cs.name());
+
+        //encode unmappable surrogates
+        if (enc instanceof sun.nio.cs.ArrayEncoder &&
+            cs.contains(Charset.forName("ASCII"))) {
+            enc.replaceWith(new byte[] { (byte)'A'});
+            sun.nio.cs.ArrayEncoder cae = (sun.nio.cs.ArrayEncoder)enc;
+
+            String str = "ab\uD800\uDC00\uD800\uDC00cd";
+            byte[] ba = new byte[str.length() - 2];
+            int n = cae.encode(str.toCharArray(), 0, str.length(), ba);
+            if (n != 6 || !"abAAcd".equals(new String(ba, cs.name())))
+                throw new RuntimeException("encode1(surrogates) failed  -> "
+                                           + cs.name());
+
+            ba = new byte[str.length()];
+            n = cae.encode(str.toCharArray(), 0, str.length(), ba);
+            if (n != 6 || !"abAAcd".equals(new String(ba, 0, n,
+                                                     cs.name())))
+                throw new RuntimeException("encode2(surrogates) failed  -> "
+                                           + cs.name());
+            str = "ab\uD800B\uDC00Bcd";
+            ba = new byte[str.length()];
+            n = cae.encode(str.toCharArray(), 0, str.length(), ba);
+            if (n != 8 || !"abABABcd".equals(new String(ba, 0, n,
+                                                       cs.name())))
+                throw new RuntimeException("encode3(surrogates) failed  -> "
+                                           + cs.name());
+
+            ba = new byte[str.length() - 1];
+            n = cae.encode(str.toCharArray(), 0, str.length(), ba);
+            if (n != 7 || !"abABABc".equals(new String(ba, 0, n,
+                                                      cs.name())))
+                throw new RuntimeException("encode4(surrogates) failed  -> "
+                                           + cs.name());
+        }
+
+    }
+
+    static class PermissiveSecurityManger extends SecurityManager {
+        @Override public void checkPermission(java.security.Permission p) {}
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/pisces/DashStrokeTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary verify that first element is a dash
+ * @bug 6793344
+ */
+
+import java.awt.*;
+import java.awt.image.*;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+public class DashStrokeTest extends Component {
+
+    static BufferedImage bi;
+    static boolean printed = false;
+
+    public Dimension getPreferredSize() {
+      return new Dimension(200,200);
+    }
+
+    public static void drawGui() {
+        bi = new BufferedImage(200, 20, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2d = bi.createGraphics();
+        BasicStroke dashStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND,
+                BasicStroke.JOIN_ROUND, 1.0f, new float[] { 0.0f, 200 },
+                1.0f);
+
+        g2d.setStroke(dashStroke);
+        g2d.setColor(Color.RED);
+        g2d.drawLine(5,10, 100,10);
+        printed =true;
+    }
+
+    public static void main(String[] args) {
+            try {
+            SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                drawGui();
+            }
+
+            });
+            } catch (Exception e) {
+            }
+
+            if (printed) {
+                checkBI(bi, Color.RED);
+            }
+    }
+
+    static void checkBI(BufferedImage bi, Color badColor) {
+      int badrgb = badColor.getRGB();
+
+      int col = bi.getRGB(6, 9);
+      if (col == badrgb) {
+          throw new RuntimeException("A pixel was turned on. ");
+      }
+   }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/pisces/JoinMiterTest.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Pass if no RuntimeException.
+ * @bug 6812600
+ */
+import java.awt.*;
+import java.awt.image.BufferedImage;
+
+public class JoinMiterTest {
+
+  public static void main(String[] args) throws Exception {
+    BufferedImage image = new BufferedImage(200, 200,
+BufferedImage.TYPE_INT_RGB);
+    Graphics2D g = image.createGraphics();
+    g.setPaint(Color.WHITE);
+    g.fill(new Rectangle(image.getWidth(), image.getHeight()));
+    g.translate(25, 100);
+    g.setPaint(Color.BLACK);
+    g.setStroke(new BasicStroke(20, BasicStroke.CAP_BUTT,
+                                BasicStroke.JOIN_MITER));
+    g.draw(new Polygon(new int[] {0, 150, 0}, new int[] {75, 0, -75}, 3));
+    if (image.getRGB(16, 10) == Color.WHITE.getRGB()) {
+      throw new RuntimeException("Miter is not rendered.");
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/SpnegoReqFlags.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6815182
+ * @summary GSSAPI/SPNEGO does not work with server using MIT Kerberos library
+ */
+
+import sun.security.jgss.GSSUtil;
+import sun.security.util.BitArray;
+import sun.security.util.DerInputStream;
+import sun.security.util.DerValue;
+
+public class SpnegoReqFlags {
+
+    public static void main(String[] args)
+            throws Exception {
+
+        // Create and start the KDC
+        new OneKDC(null).writeJAASConf();
+        new SpnegoReqFlags().go();
+    }
+
+    void go() throws Exception {
+        Context c = Context.fromJAAS("client");
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_SPNEGO_MECH_OID);
+
+        byte[] token = c.doAs(new Action() {
+            @Override
+            public byte[] run(Context me, byte[] input) throws Exception {
+                me.x().requestCredDeleg(true);
+                me.x().requestReplayDet(false);
+                me.x().requestSequenceDet(false);
+                return me.x().initSecContext(new byte[0], 0, 0);
+            }
+        }, null);
+
+        DerValue d = new DerValue(token);   // GSSToken
+        DerInputStream ins = d.data;        // OID + mech token
+        d.data.getDerValue();               // skip OID
+        d = d.data.getDerValue();           // NegTokenInit
+        d = d.data.getDerValue();           // The SEQUENCE inside
+
+        boolean found = false;
+
+        // Go through all fields inside NegTokenInit. The reqFlags field
+        // is optional. It's even not recommended in RFC 4178.
+        while (d.data.available() > 0) {
+            DerValue d2 = d.data.getDerValue();
+            if (d2.isContextSpecific((byte)1)) {
+                found = true;
+                System.out.println("regFlags field located.");
+                BitArray ba = d2.data.getUnalignedBitString();
+                if (ba.length() != 7) {
+                    throw new Exception("reqFlags should contain 7 bits");
+                }
+                if (!ba.get(0)) {
+                    throw new Exception("delegFlag should be true");
+                }
+                if (ba.get(2) || ba.get(3)) {
+                    throw new Exception("replay/sequenceFlag should be false");
+                }
+            }
+        }
+
+        if (!found) {
+            System.out.println("Warning: regFlags field not found, too new?");
+        }
+        c.dispose();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/tools/keytool/NoExtNPE.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,65 @@
+#
+# Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+# 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 6813402
+# @summary keytool cannot -printcert entries without extensions
+#
+# @run shell NoExtNPE.sh
+
+# set a few environment variables so that the shell-script can run stand-alone
+# in the source directory
+if [ "${TESTSRC}" = "" ] ; then
+   TESTSRC="."
+fi
+
+if [ "${TESTJAVA}" = "" ] ; then
+   echo "TESTJAVA not set.  Test cannot execute."
+   echo "FAILED!!!"
+   exit 1
+fi
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  SunOS )
+    FILESEP="/"
+    ;;
+  Linux )
+    FILESEP="/"
+    ;;
+  Windows* )
+    FILESEP="\\"
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
+${TESTJAVA}${FILESEP}bin${FILESEP}keytool \
+	-list -v \
+	-keystore ${TESTSRC}${FILESEP}CloneKeyAskPassword.jks \
+	-storepass test123
+
+exit $?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/tools/keytool/importreadall.sh	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,62 @@
+#
+# Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+# 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 6819272
+# @summary keytool -importcert should read the whole input
+#
+# @run shell importreadall.sh
+
+# set a few environment variables so that the shell-script can run stand-alone
+# in the source directory
+if [ "${TESTSRC}" = "" ] ; then
+   TESTSRC="."
+fi
+
+if [ "${TESTJAVA}" = "" ] ; then
+  JAVA_CMD=`which java`
+  TESTJAVA=`dirname $JAVA_CMD`/..
+fi
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Windows_* )
+    FS="\\"
+    ;;
+  * )
+    FS="/"
+    ;;
+esac
+
+KEYTOOL="${TESTJAVA}${FS}bin${FS}keytool -keystore importreadall.jks -storepass changeit -keypass changeit"
+
+# In case the test is run twice in the same directory
+
+$KEYTOOL -delete -alias a
+$KEYTOOL -delete -alias ca
+$KEYTOOL -genkeypair -alias a -dname CN=a || exit 1
+$KEYTOOL -genkeypair -alias ca -dname CN=ca || exit 2
+$KEYTOOL -certreq -alias a | $KEYTOOL -gencert -alias ca | $KEYTOOL -importcert -alias a
+
+exit $?
--- a/langtools/.hgtags	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/.hgtags	Fri Apr 10 13:05:12 2009 -0700
@@ -24,3 +24,7 @@
 2b8f6bab23926aa32b9cf7e4c540b9d1ce74b7d5 jdk7-b47
 c53007f34195f69223bdd4125ec6c0740f7d6736 jdk7-b48
 d17d927ad9bdfafae32451645d182acb7bed7be6 jdk7-b49
+46f2f6ed96f13fc49fec3d1b6aa616686128cb57 jdk7-b50
+8c55d5b0ed71ed3a749eb97e4eab79b4831649b8 jdk7-b51
+29329051d483d39f66073752ba4afbf29d893cfe jdk7-b52
+dbdeb4a7581b2a8699644b91cae6793cb01953f7 jdk7-b53
--- a/langtools/make/build.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/build.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/langtools/make/build.xml	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/build.xml	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!--
- Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
  This code is free software; you can redistribute it and/or modify it
--- a/langtools/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,241 +0,0 @@
-#!echo "This is not a shell script"
-#############################################################################
-#
-# Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Sun designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
-# CA 95054 USA or visit www.sun.com if you need additional information or
-# have any questions.
-#
-#############################################################################
-#
-# JPRT shell configuration for building.
-#
-# Input environment variables:
-#    ALT_BOOTDIR
-#    ALT_SLASH_JAVA
-#    ALT_JDK_IMPORT_PATH
-#    Windows Only:
-#      PATH
-#      PROCESSOR_IDENTIFIER
-#      ROOTDIR
-#
-# Output variable settings:
-#    make    Full path to GNU make
-#
-# Output environment variables:
-#    PATH
-#    Windows Only:
-#      ALT_DEVTOOLS_PATH (To avoid the C:/UTILS default)
-#
-# After JDK6, most settings will be found via ALT_SLASH_JAVA or
-#   by way of other system environment variables. If this was JDK5
-#   or an older JDK, you might need to export more ALT_* variables.
-#
-#############################################################################
-
-#############################################################################
-# Error
-error() # message
-{
-  echo "ERROR: $1"
-  exit 6
-}
-# Directory must exist
-dirMustExist() # dir name
-{
-  if [ ! -d "$1" ] ; then
-    error "Directory for $2 does not exist: $1"
-  fi
-}
-# File must exist
-fileMustExist() # dir name
-{
-  if [ ! -f "$1" ] ; then
-    error "File for $2 does not exist: $1"
-  fi
-}
-#############################################################################
-
-# Should be set by JPRT as the 3 basic inputs
-bootdir="${ALT_BOOTDIR}"
-slashjava="${ALT_SLASH_JAVA}"
-jdk_import="${ALT_JDK_IMPORT_PATH}"
-
-# Check input
-dirMustExist "${bootdir}"    ALT_BOOTDIR
-dirMustExist "${slashjava}"  ALT_SLASH_JAVA
-dirMustExist "${jdk_import}" ALT_JDK_IMPORT_PATH
-
-# Uses 'uname -s', but only expect SunOS or Linux, assume Windows otherwise.
-osname=`uname -s`
-if [ "${osname}" = SunOS ] ; then
-   
-    # SOLARIS: Sparc or X86
-    osarch=`uname -p`
-    if [ "${osarch}" = sparc ] ; then
-	solaris_arch=sparc
-    else
-	solaris_arch=i386
-    fi
-
-    # Add basic solaris system paths
-    path4sdk=/usr/ccs/bin:/usr/ccs/lib:/usr/bin:/bin:/usr/sfw/bin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-
-    # Find GNU make
-    make=/usr/sfw/bin/gmake
-    if [ ! -f ${make} ] ; then
-	make=/opt/sfw/bin/gmake
-	if [ ! -f ${make} ] ; then
-	    make=${slashjava}/devtools/${solaris_arch}/bin/gnumake
-        fi 
-    fi
-    fileMustExist "${make}" make
-
-    # File creation mask
-    umask 002
-
-elif [ "${osname}" = Linux ] ; then
-   
-    # LINUX: X86, AMD64
-    osarch=`uname -m`
-    if [ "${osarch}" = i686 ] ; then
-	linux_arch=i586
-    elif [ "${osarch}" = x86_64 ] ; then
-	linux_arch=amd64
-    fi
-
-    # Add basic paths
-    path4sdk=/usr/bin:/bin:/usr/sbin:/sbin
-
-    # Get the previous JDK to be used to bootstrap the build
-    path4sdk=${bootdir}/bin:${path4sdk}
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk=${antbindir}:${path4sdk}
-    
-    # Find GNU make
-    make=/usr/bin/make
-    fileMustExist "${make}" make
-
-    umask 002
-
-else
-
-    # Windows: Differs on CYGWIN vs. MKS
-    #   Also, blanks in pathnames gives GNU make headaches, so anything placed
-    #   in any ALT_* variable should be the short windows dosname.
-   
-    # WINDOWS: Install and use MKS or CYGWIN (should have already been done)
-    #   Assumption here is that you are in a shell window via MKS or cygwin.
-    #   MKS install should have defined the environment variable ROOTDIR.
-    #   We also need to figure out which one we have: X86, AMD64
-    if [ "`echo ${PROCESSOR_IDENTIFIER} | fgrep AMD64`" != "" ] ; then
-	windows_arch=amd64
-    else
-	windows_arch=i586
-    fi
-    
-    # We need to determine if we are running a CYGWIN shell or an MKS shell
-    #    (if uname isn't available, then it will be unix_toolset=unknown)
-    unix_toolset=unknown
-    if [ "`uname -a | fgrep Cygwin`" = "" -a -d "${ROOTDIR}" ] ; then
-        # We kind of assume ROOTDIR is where MKS is and it's ok
-        unix_toolset=MKS
-        mkshome=`dosname -s "${ROOTDIR}"`
-	# Utility to convert to short pathnames without spaces
-	dosname="${mkshome}/mksnt/dosname -s"
-        # Most unix utilities are in the mksnt directory of ROOTDIR
-        unixcommand_path="${mkshome}/mksnt"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-	devtools_path="${slashjava}/devtools/win32/bin"
-	path4sdk="${devtools_path};${path4sdk}"
-	# Normally this need not be set, but on Windows it's default is C:/UTILS
-        ALT_DEVTOOLS_PATH="${devtools_path}"
-	export ALT_DEVTOOLS_PATH
-        dirMustExist "${devtools_path}" ALT_DEVTOOLS_PATH
-        # Find GNU make
-        make="${devtools_path}/gnumake.exe"
-        fileMustExist "${make}" make
-    elif [ "`uname -a | fgrep Cygwin`" != "" -a -f /bin/cygpath ] ; then
-        # For CYGWIN, uname will have "Cygwin" in it, and /bin/cygpath should exist
-        unix_toolset=CYGWIN
-	# Utility to convert to short pathnames without spaces
-	dosname="/usr/bin/cygpath -a -m -s"
-        # Most unix utilities are in the /usr/bin
-        unixcommand_path="/usr/bin"
-        path4sdk="${unixcommand_path}"
-        dirMustExist "${unixcommand_path}" ALT_UNIXCOMMAND_PATH
-        # Find GNU make
-        make="${unixcommand_path}/make.exe"
-        fileMustExist "${make}" make
-    else
-      echo "WARNING: Cannot figure out if this is MKS or CYGWIN"
-    fi
-
-    # WINDOWS: Get the previous JDK to be used to bootstrap the build
-    path4sdk="${bootdir}/bin;${path4sdk}"
-
-    # Ant
-    ANT_HOME=${slashjava}/devtools/share/ant/1.7.0
-    export ANT_HOME
-    antbindir=${ANT_HOME}/bin
-    fileMustExist "${antbindir}/ant" ant
-    path4sdk="${antbindir};${path4sdk}"
-
-    # Turn all \\ into /, remove duplicates and trailing /
-    slash_path="`echo ${path4sdk} | sed -e 's@\\\\@/@g' -e 's@//@/@g' -e 's@/$@@' -e 's@/;@;@g'`"
-    
-    # For windows, it's hard to know where the system is, so we just add this
-    #    to PATH.
-    path4sdk="${slash_path};${PATH}"
-    
-    # Convert path4sdk to cygwin style
-    if [ "${unix_toolset}" = CYGWIN ] ; then
-	path4sdk="`/usr/bin/cygpath -p ${path4sdk}`"
-    fi
-
-fi
-
-# Export PATH setting
-PATH="${path4sdk}"
-export PATH
-
-# Things we need to unset
-unset LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH_32
-unset LD_LIBRARY_PATH_64
-unset JAVA_HOME
-
--- a/langtools/make/netbeans/langtools/build.xml	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/netbeans/langtools/build.xml	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!--
- Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
--- a/langtools/make/netbeans/langtools/nbproject/project.xml	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/netbeans/langtools/nbproject/project.xml	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!--
- Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
--- a/langtools/make/netbeans/langtools/nbproject/standard-context-menu-items.ent	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/netbeans/langtools/nbproject/standard-context-menu-items.ent	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!--
- Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
--- a/langtools/make/netbeans/langtools/nbproject/standard-ide-actions.ent	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/netbeans/langtools/nbproject/standard-ide-actions.ent	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!--
- Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
--- a/langtools/make/tools/SelectTool/SelectToolTask.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/make/tools/SelectTool/SelectToolTask.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/comp/AnnotationProcessingError.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/comp/AnnotationProcessingError.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/comp/Apt.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/comp/Apt.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/comp/UsageMessageNeededException.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/comp/UsageMessageNeededException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/main/JavaCompiler.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/main/JavaCompiler.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/mirror/apt/RoundCompleteEventImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/mirror/apt/RoundCompleteEventImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationProxyMaker.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationProxyMaker.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/apt/mirror/type/TypeVariableImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/apt/mirror/type/TypeVariableImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2004-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/Annotation.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Annotation.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/AttributeException.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/AttributeException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/Code_attribute.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Code_attribute.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/ConstantPool.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/ConstantPool.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/ConstantPoolException.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/ConstantPoolException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/Descriptor.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Descriptor.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/DescriptorException.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/DescriptorException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/classfile/StackMapTable_attribute.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/classfile/StackMapTable_attribute.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,11 +25,11 @@
 
 package com.sun.tools.doclets.formats.html;
 
-import com.sun.tools.doclets.internal.toolkit.util.*;
+import java.io.*;
+import java.util.*;
 
 import com.sun.javadoc.*;
-import java.io.*;
-import java.util.*;
+import com.sun.tools.doclets.internal.toolkit.util.*;
 
 /**
  * Generate Index for all the Member Names with Indexing in
@@ -100,18 +100,22 @@
         h2();
         strong(unicode.toString());
         h2End();
-        dl();
-        for (int i = 0; i < memberlist.size(); i++) {
-            Doc element = memberlist.get(i);
-            if (element instanceof MemberDoc) {
-                printDescription((MemberDoc)element);
-            } else if (element instanceof ClassDoc) {
-                printDescription((ClassDoc)element);
-            } else if (element instanceof PackageDoc) {
-                printDescription((PackageDoc)element);
+        int memberListSize = memberlist.size();
+        // Display the list only if there are elements to be displayed.
+        if (memberListSize > 0) {
+            dl();
+            for (int i = 0; i < memberListSize; i++) {
+                Doc element = memberlist.get(i);
+                if (element instanceof MemberDoc) {
+                    printDescription((MemberDoc)element);
+                } else if (element instanceof ClassDoc) {
+                    printDescription((ClassDoc)element);
+                } else if (element instanceof PackageDoc) {
+                    printDescription((PackageDoc)element);
+                }
             }
+            dlEnd();
         }
-        dlEnd();
         hr();
     }
 
@@ -126,8 +130,10 @@
         printPackageLink(pkg, Util.getPackageName(pkg), true);
         print(" - ");
         print(configuration.getText("doclet.package") + " " + pkg.name());
+        dtEnd();
         dd();
         printSummaryComment(pkg);
+        ddEnd();
     }
 
     /**
@@ -140,8 +146,10 @@
         printLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_INDEX, cd, true));
         print(" - ");
         printClassInfo(cd);
+        dtEnd();
         dd();
         printComment(cd);
+        ddEnd();
     }
 
     /**
@@ -178,8 +186,10 @@
         println(" - ");
         printMemberDesc(member);
         println();
+        dtEnd();
         dd();
         printComment(member);
+        ddEnd();
         println();
     }
 
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,19 +25,20 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.lang.reflect.Modifier;
+import java.util.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
 
-import com.sun.javadoc.*;
-import java.util.*;
-import java.lang.reflect.Modifier;
-
 /**
  * The base class for member writers.
  *
  * @author Robert Field
  * @author Atul M Dambalkar
  * @author Jamie Ho (Re-write)
+ * @author Bhavesh Patel (Modified)
  */
 public abstract class AbstractMemberWriter {
 
@@ -59,7 +60,11 @@
 
     /*** abstracts ***/
 
-    public abstract void printSummaryLabel(ClassDoc cd);
+    public abstract void printSummaryLabel();
+
+    public abstract void printTableSummary();
+
+    public abstract void printSummaryTableHeader(ProgramElementDoc member);
 
     public abstract void printInheritedSummaryLabel(ClassDoc cd);
 
@@ -232,10 +237,26 @@
         }
     }
 
+    /**
+     * Print the deprecated output for the given member.
+     *
+     * @param member the member being documented.
+     */
+    protected void printDeprecated(ProgramElementDoc member) {
+        String output = (new DeprecatedTaglet()).getTagletOutput(member,
+            writer.getTagletWriterInstance(false)).toString().trim();
+        if (!output.isEmpty()) {
+            writer.printMemberDetailsListStartTag();
+            writer.print(output);
+        }
+    }
+
     protected void printComment(ProgramElementDoc member) {
         if (member.inlineTags().length > 0) {
+            writer.printMemberDetailsListStartTag();
             writer.dd();
             writer.printInlineComment(member);
+            writer.ddEnd();
         }
     }
 
@@ -267,6 +288,14 @@
     }
 
     /**
+     * Write the member footer.
+     */
+    protected void printMemberFooter() {
+        writer.printMemberDetailsListEndTag();
+        assert !writer.getMemberDetailsListPrinted();
+    }
+
+    /**
      * Forward to containing writer
      */
     public void printSummaryHeader(ClassDoc cd) {
@@ -317,12 +346,13 @@
      * format for listing the API. Call methods from the sub-class to complete
      * the generation.
      */
-    protected void printDeprecatedAPI(List<Doc> deprmembers, String headingKey) {
+    protected void printDeprecatedAPI(List<Doc> deprmembers, String headingKey, String tableSummary, String[] tableHeader) {
         if (deprmembers.size() > 0) {
-            writer.tableIndexSummary();
-            writer.tableHeaderStart("#CCCCFF");
-            writer.strongText(headingKey);
-            writer.tableHeaderEnd();
+            writer.tableIndexSummary(tableSummary);
+            writer.tableCaptionStart();
+            writer.printText(headingKey);
+            writer.tableCaptionEnd();
+            writer.summaryTableHeader(tableHeader, "col");
             for (int i = 0; i < deprmembers.size(); i++) {
                 ProgramElementDoc member =(ProgramElementDoc)deprmembers.get(i);
                 writer.trBgcolorStyle("white", "TableRowColor");
@@ -345,19 +375,26 @@
     /**
      * Print use info.
      */
-    protected void printUseInfo(List<? extends ProgramElementDoc> mems, String heading) {
+    protected void printUseInfo(List<? extends ProgramElementDoc> mems, String heading, String tableSummary) {
         if (mems == null) {
             return;
         }
         List<? extends ProgramElementDoc> members = mems;
+        boolean printedUseTableHeader = false;
         if (members.size() > 0) {
-            writer.tableIndexSummary();
-            writer.tableUseInfoHeaderStart("#CCCCFF");
+            writer.tableIndexSummary(tableSummary);
+            writer.tableSubCaptionStart();
             writer.print(heading);
-            writer.tableHeaderEnd();
+            writer.tableCaptionEnd();
             for (Iterator<? extends ProgramElementDoc> it = members.iterator(); it.hasNext(); ) {
                 ProgramElementDoc pgmdoc = it.next();
                 ClassDoc cd = pgmdoc.containingClass();
+                if (!printedUseTableHeader) {
+                    // Passing ProgramElementDoc helps decides printing
+                    // interface or class header in case of nested classes.
+                    this.printSummaryTableHeader(pgmdoc);
+                    printedUseTableHeader = true;
+                }
 
                 writer.printSummaryLinkType(this, pgmdoc);
                 if (cd != null && !(pgmdoc instanceof ConstructorDoc)
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractPackageIndexWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractPackageIndexWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -35,6 +35,7 @@
  * generate overview-frame.html as well as overview-summary.html.
  *
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public abstract class AbstractPackageIndexWriter extends HtmlDocletWriter {
 
@@ -61,7 +62,7 @@
 
     protected abstract void printOverviewHeader();
 
-    protected abstract void printIndexHeader(String text);
+    protected abstract void printIndexHeader(String text, String tableSummary);
 
     protected abstract void printIndexRow(PackageDoc pkg);
 
@@ -101,7 +102,10 @@
      * Generate the frame or non-frame package index.
      */
     protected void generateIndex() {
-        printIndexContents(packages, "doclet.Package_Summary");
+        printIndexContents(packages, "doclet.Package_Summary",
+                configuration.getText("doclet.Member_Table_Summary",
+                configuration.getText("doclet.Package_Summary"),
+                configuration.getText("doclet.packages")));
     }
 
     /**
@@ -111,10 +115,10 @@
      * @param packages Array of packages to be documented.
      * @param text     String which will be used as the heading.
      */
-    protected void printIndexContents(PackageDoc[] packages, String text) {
+    protected void printIndexContents(PackageDoc[] packages, String text, String tableSummary) {
         if (packages.length > 0) {
             Arrays.sort(packages);
-            printIndexHeader(text);
+            printIndexHeader(text, tableSummary);
             printAllClassesPackagesLink();
             for(int i = 0; i < packages.length; i++) {
                 if (packages[i] != null) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeOptionalMemberWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeOptionalMemberWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,15 +25,16 @@
 
 package com.sun.tools.doclets.formats.html;
 
-import com.sun.tools.doclets.internal.toolkit.*;
+import java.io.*;
+
 import com.sun.javadoc.*;
-
-import java.io.*;
+import com.sun.tools.doclets.internal.toolkit.*;
 
 /**
  * Writes annotation type optional member documentation in HTML format.
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  */
 public class AnnotationTypeOptionalMemberWriterImpl extends
         AnnotationTypeRequiredMemberWriterImpl
@@ -63,14 +64,20 @@
      * {@inheritDoc}
      */
     public void writeDefaultValueInfo(MemberDoc member) {
-        writer.dl();
-        writer.dt();
-        writer.strong(ConfigurationImpl.getInstance().
-            getText("doclet.Default"));
-        writer.dd();
-        writer.print(((AnnotationTypeElementDoc) member).defaultValue());
-        writer.ddEnd();
-        writer.dlEnd();
+        if (((AnnotationTypeElementDoc) member).defaultValue() != null) {
+            writer.printMemberDetailsListStartTag();
+            writer.dd();
+            writer.dl();
+            writer.dt();
+            writer.strong(ConfigurationImpl.getInstance().
+                getText("doclet.Default"));
+            writer.dtEnd();
+            writer.dd();
+            writer.print(((AnnotationTypeElementDoc) member).defaultValue());
+            writer.ddEnd();
+            writer.dlEnd();
+            writer.ddEnd();
+        }
     }
 
     /**
@@ -83,8 +90,27 @@
     /**
      * {@inheritDoc}
      */
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Annotation_Type_Optional_Member_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Annotation_Type_Optional_Member_Summary");
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Annotation_Type_Optional_Member_Summary"),
+                configuration().getText("doclet.annotation_type_optional_members")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header = new String[] {
+            writer.getModifierTypeHeader(),
+            configuration().getText("doclet.0_and_1",
+                    configuration().getText("doclet.Annotation_Type_Optional_Member"),
+                    configuration().getText("doclet.Description"))
+        };
+        writer.summaryTableHeader(header, "col");
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeRequiredMemberWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeRequiredMemberWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,16 +25,16 @@
 
 package com.sun.tools.doclets.formats.html;
 
-import com.sun.tools.doclets.internal.toolkit.*;
-import com.sun.tools.doclets.internal.toolkit.taglets.*;
+import java.io.*;
+
 import com.sun.javadoc.*;
-
-import java.io.*;
+import com.sun.tools.doclets.internal.toolkit.*;
 
 /**
  * Writes annotation type required member documentation in HTML format.
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  */
 public class AnnotationTypeRequiredMemberWriterImpl extends AbstractMemberWriter
     implements AnnotationTypeRequiredMemberWriter, MemberSummaryWriter {
@@ -134,17 +134,14 @@
             strong(member.name());
         }
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
      * {@inheritDoc}
      */
     public void writeComments(MemberDoc member) {
-        if (member.inlineTags().length > 0) {
-            writer.dd();
-            writer.printInlineComment(member);
-        }
+        printComment(member);
     }
 
     /**
@@ -160,7 +157,7 @@
      * Write the annotation type member footer.
      */
     public void writeMemberFooter() {
-        writer.dlEnd();
+        printMemberFooter();
     }
 
     /**
@@ -182,8 +179,27 @@
     /**
      * {@inheritDoc}
      */
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Annotation_Type_Required_Member_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Annotation_Type_Required_Member_Summary");
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Annotation_Type_Required_Member_Summary"),
+                configuration().getText("doclet.annotation_type_required_members")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header = new String[] {
+            writer.getModifierTypeHeader(),
+            configuration().getText("doclet.0_and_1",
+                    configuration().getText("doclet.Annotation_Type_Required_Member"),
+                    configuration().getText("doclet.Description"))
+        };
+        writer.summaryTableHeader(header, "col");
     }
 
     /**
@@ -267,9 +283,7 @@
      * {@inheritDoc}
      */
     public void writeDeprecated(MemberDoc member) {
-        print(((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(member,
-            writer.getTagletWriterInstance(false))).toString());
+        printDeprecated(member);
     }
 
     private Type getType(MemberDoc member) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,10 +25,10 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
 import com.sun.tools.doclets.internal.toolkit.builders.*;
-import com.sun.javadoc.*;
 
 /**
  * Generate the Class Information Page.
@@ -165,8 +165,6 @@
      * {@inheritDoc}
      */
     public void writeAnnotationTypeSignature(String modifiers) {
-        dl();
-        dt();
         preNoNewLine();
         writeAnnotationInfo(annotationType);
         print(modifiers);
@@ -178,7 +176,6 @@
         } else {
             strong(name);
         }
-        dlEnd();
         preEnd();
         p();
     }
@@ -334,6 +331,7 @@
             } else {
                 strongText("doclet.Enclosing_Class");
             }
+            dtEnd();
             dd();
             printLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS, outerClass,
                 false));
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassUseWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassUseWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -34,6 +34,7 @@
  * Generate class usage information.
  *
  * @author Robert G. Field
+ * @author Bhavesh Patel (Modified)
  */
 public class ClassUseWriter extends SubWriterHolderWriter {
 
@@ -65,6 +66,13 @@
     final ConstructorWriterImpl constrSubWriter;
     final FieldWriterImpl fieldSubWriter;
     final NestedClassWriterImpl classSubWriter;
+    // Summary for various use tables.
+    final String classUseTableSummary;
+    final String subclassUseTableSummary;
+    final String subinterfaceUseTableSummary;
+    final String fieldUseTableSummary;
+    final String methodUseTableSummary;
+    final String constructorUseTableSummary;
 
 
     /**
@@ -116,6 +124,18 @@
         constrSubWriter = new ConstructorWriterImpl(this);
         fieldSubWriter = new FieldWriterImpl(this);
         classSubWriter = new NestedClassWriterImpl(this);
+        classUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.classes"));
+        subclassUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.subclasses"));
+        subinterfaceUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.subinterfaces"));
+        fieldUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.fields"));
+        methodUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.methods"));
+        constructorUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.constructors"));
     }
 
     /**
@@ -213,12 +233,13 @@
     }
 
     protected void generatePackageList() throws IOException {
-        tableIndexSummary();
-        tableHeaderStart("#CCCCFF");
+        tableIndexSummary(useTableSummary);
+        tableCaptionStart();
         printText("doclet.ClassUse_Packages.that.use.0",
             getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc,
                 false)));
-        tableHeaderEnd();
+        tableCaptionEnd();
+        summaryTableHeader(packageTableHeader, "col");
 
         for (Iterator<PackageDoc> it = pkgSet.iterator(); it.hasNext();) {
             PackageDoc pkg = it.next();
@@ -234,12 +255,13 @@
                pkgToPackageAnnotations == null ||
                pkgToPackageAnnotations.size() == 0)
             return;
-        tableIndexSummary();
-        tableHeaderStart("#CCCCFF");
+        tableIndexSummary(useTableSummary);
+        tableCaptionStart();
         printText("doclet.ClassUse_PackageAnnotation",
             getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc,
                 false)));
-        tableHeaderEnd();
+        tableCaptionEnd();
+        summaryTableHeader(packageTableHeader, "col");
         for (Iterator<PackageDoc> it = pkgToPackageAnnotations.iterator(); it.hasNext();) {
             PackageDoc pkg = it.next();
             trBgcolorStyle("white", "TableRowColor");
@@ -300,83 +322,68 @@
             LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc, false));
         String pkgLink = getPackageLink(pkg, Util.getPackageName(pkg), false);
         classSubWriter.printUseInfo(pkgToClassAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_Annotation", classLink,
-            pkgLink));
-
+                configuration.getText("doclet.ClassUse_Annotation", classLink,
+                pkgLink), classUseTableSummary);
         classSubWriter.printUseInfo(pkgToClassTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_TypeParameter", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_TypeParameter", classLink,
+                pkgLink), classUseTableSummary);
         classSubWriter.printUseInfo(pkgToSubclass.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_Subclass", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_Subclass", classLink,
+                pkgLink), subclassUseTableSummary);
         classSubWriter.printUseInfo(pkgToSubinterface.get(pkg.name()),
-                                    configuration.getText("doclet.ClassUse_Subinterface",
-                                            classLink,
-                                            pkgLink));
+                configuration.getText("doclet.ClassUse_Subinterface", classLink,
+                pkgLink), subinterfaceUseTableSummary);
         classSubWriter.printUseInfo(pkgToImplementingClass.get(pkg.name()),
-                                    configuration.getText("doclet.ClassUse_ImplementingClass",
-                                            classLink,
-                                            pkgLink));
+                configuration.getText("doclet.ClassUse_ImplementingClass", classLink,
+                pkgLink), classUseTableSummary);
         fieldSubWriter.printUseInfo(pkgToField.get(pkg.name()),
-                                    configuration.getText("doclet.ClassUse_Field",
-                                            classLink,
-                                            pkgLink));
+                configuration.getText("doclet.ClassUse_Field", classLink,
+                pkgLink), fieldUseTableSummary);
         fieldSubWriter.printUseInfo(pkgToFieldAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_FieldAnnotations",
-            classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_FieldAnnotations", classLink,
+                pkgLink), fieldUseTableSummary);
         fieldSubWriter.printUseInfo(pkgToFieldTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_FieldTypeParameter",
-            classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_FieldTypeParameter", classLink,
+                pkgLink), fieldUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_MethodAnnotations", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_MethodAnnotations", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodParameterAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_MethodParameterAnnotations", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_MethodParameterAnnotations", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_MethodTypeParameter", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_MethodTypeParameter", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodReturn.get(pkg.name()),
-                                     configuration.getText("doclet.ClassUse_MethodReturn",
-                                             classLink,
-                                             pkgLink));
+                configuration.getText("doclet.ClassUse_MethodReturn", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodReturnTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_MethodReturnTypeParameter", classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_MethodReturnTypeParameter", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodArgs.get(pkg.name()),
-                                     configuration.getText("doclet.ClassUse_MethodArgs",
-                                             classLink,
-                                             pkgLink));
+                configuration.getText("doclet.ClassUse_MethodArgs", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodArgTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_MethodArgsTypeParameters",
-            classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_MethodArgsTypeParameters", classLink,
+                pkgLink), methodUseTableSummary);
         methodSubWriter.printUseInfo(pkgToMethodThrows.get(pkg.name()),
-                                     configuration.getText("doclet.ClassUse_MethodThrows",
-                                             classLink,
-                                             pkgLink));
+                configuration.getText("doclet.ClassUse_MethodThrows", classLink,
+                pkgLink), methodUseTableSummary);
         constrSubWriter.printUseInfo(pkgToConstructorAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_ConstructorAnnotations",
-                classLink,
-                pkgLink));
+                configuration.getText("doclet.ClassUse_ConstructorAnnotations", classLink,
+                pkgLink), constructorUseTableSummary);
         constrSubWriter.printUseInfo(pkgToConstructorParameterAnnotations.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_ConstructorParameterAnnotations",
-                classLink,
-                pkgLink));
+                configuration.getText("doclet.ClassUse_ConstructorParameterAnnotations", classLink,
+                pkgLink), constructorUseTableSummary);
         constrSubWriter.printUseInfo(pkgToConstructorArgs.get(pkg.name()),
-                                     configuration.getText("doclet.ClassUse_ConstructorArgs",
-                                             classLink,
-                                             pkgLink));
+                configuration.getText("doclet.ClassUse_ConstructorArgs", classLink,
+                pkgLink), constructorUseTableSummary);
         constrSubWriter.printUseInfo(pkgToConstructorArgTypeParameter.get(pkg.name()),
-            configuration.getText("doclet.ClassUse_ConstructorArgsTypeParameters",
-            classLink,
-            pkgLink));
+                configuration.getText("doclet.ClassUse_ConstructorArgsTypeParameters", classLink,
+                pkgLink), constructorUseTableSummary);
         constrSubWriter.printUseInfo(pkgToConstructorThrows.get(pkg.name()),
-                                     configuration.getText("doclet.ClassUse_ConstructorThrows",
-                                             classLink,
-                                             pkgLink));
+                configuration.getText("doclet.ClassUse_ConstructorThrows", classLink,
+                pkgLink), constructorUseTableSummary);
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,12 +25,12 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.util.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
 import com.sun.tools.doclets.internal.toolkit.builders.*;
-import com.sun.javadoc.*;
-
-import java.util.*;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
 
 /**
@@ -171,8 +171,6 @@
      */
     public void writeClassSignature(String modifiers) {
         boolean isInterface = classDoc.isInterface();
-        dl();
-        dt();
         preNoNewLine();
         writeAnnotationInfo(classDoc);
         print(modifiers);
@@ -191,7 +189,7 @@
             Type superclass = Util.getFirstVisibleSuperClass(classDoc,
                 configuration());
             if (superclass != null) {
-                dt();
+                println();
                 print("extends ");
                 printLink(new LinkInfoImpl(
                     LinkInfoImpl.CONTEXT_CLASS_SIGNATURE_PARENT_NAME,
@@ -208,7 +206,7 @@
                     continue;
                 }
                 if (counter == 0) {
-                    dt();
+                    println();
                     print(isInterface? "extends " : "implements ");
                 } else {
                     print(", ");
@@ -219,7 +217,6 @@
                 counter++;
             }
         }
-        dlEnd();
         preEnd();
         p();
     }
@@ -342,6 +339,7 @@
             TagletOutput output = (new ParamTaglet()).getTagletOutput(classDoc,
                 getTagletWriterInstance(false));
             print(output.toString());
+            dtEnd();
             dlEnd();
         }
     }
@@ -360,8 +358,10 @@
                 dl();
                 dt();
                 strongText("doclet.Subclasses");
+                dtEnd();
                 writeClassLinks(LinkInfoImpl.CONTEXT_SUBCLASSES,
                     subclasses);
+                dlEnd();
             }
         }
     }
@@ -376,8 +376,10 @@
                 dl();
                 dt();
                 strongText("doclet.Subinterfaces");
+                dtEnd();
                 writeClassLinks(LinkInfoImpl.CONTEXT_SUBINTERFACES,
                     subInterfaces);
+                dlEnd();
             }
         }
     }
@@ -398,8 +400,10 @@
             dl();
             dt();
             strongText("doclet.Implementing_Classes");
+            dtEnd();
             writeClassLinks(LinkInfoImpl.CONTEXT_IMPLEMENTED_CLASSES,
                 implcl);
+            dlEnd();
         }
     }
 
@@ -414,8 +418,10 @@
             dl();
             dt();
             strongText("doclet.All_Implemented_Interfaces");
+            dtEnd();
             writeClassLinks(LinkInfoImpl.CONTEXT_IMPLEMENTED_INTERFACES,
                 interfaceArray);
+            dlEnd();
         }
     }
 
@@ -430,8 +436,10 @@
             dl();
             dt();
             strongText("doclet.All_Superinterfaces");
+            dtEnd();
             writeClassLinks(LinkInfoImpl.CONTEXT_SUPER_INTERFACES,
                 interfaceArray);
+            dlEnd();
         }
     }
 
@@ -455,7 +463,6 @@
             }
         }
         ddEnd();
-        dlEnd();
     }
 
     protected void navLinkTree() {
@@ -574,6 +581,7 @@
             } else {
                 strongText("doclet.Enclosing_Class");
             }
+            dtEnd();
             dd();
             printLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS, outerClass,
                 false));
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstantsSummaryWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstantsSummaryWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -35,6 +35,7 @@
  * Write the Constants Summary Page in HTML format.
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  * @since 1.4
  */
 public class ConstantsSummaryWriterImpl extends HtmlDocletWriter
@@ -50,6 +51,10 @@
      */
     private ClassDoc currentClassDoc;
 
+    private final String constantsTableSummary;
+
+    private final String[] constantsTableHeader;
+
     /**
      * Construct a ConstantsSummaryWriter.
      * @param configuration the configuration used in this run
@@ -59,6 +64,13 @@
             throws IOException {
         super(configuration, ConfigurationImpl.CONSTANTS_FILE_NAME);
         this.configuration = configuration;
+        constantsTableSummary = configuration.getText("doclet.Constants_Table_Summary",
+                configuration.getText("doclet.Constants_Summary"));
+        constantsTableHeader = new String[] {
+            getModifierTypeHeader(),
+            configuration.getText("doclet.ConstantField"),
+            configuration.getText("doclet.Value")
+        };
     }
 
     /**
@@ -151,12 +163,11 @@
      * @param classStr the heading to print.
      */
     protected void writeClassName(String classStr) {
-        table(1, 3, 0);
-        trBgcolorStyle("#EEEEFF", "TableSubHeadingColor");
-        thAlignColspan("left", 3);
+        table(1, 3, 0, constantsTableSummary);
+        tableSubCaptionStart();
         write(classStr);
-        thEnd();
-        trEnd();
+        tableCaptionEnd();
+        summaryTableHeader(constantsTableHeader, "col");
     }
 
     private void tableFooter(boolean isHeader) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstructorWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstructorWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,18 +25,19 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.io.*;
+import java.util.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.tools.doclets.internal.toolkit.taglets.*;
-import com.sun.javadoc.*;
-import java.util.*;
-import java.io.*;
 
 /**
  * Writes constructor documentation.
  *
  * @author Robert Field
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class ConstructorWriterImpl extends AbstractExecutableMemberWriter
     implements ConstructorWriter, MemberSummaryWriter {
@@ -149,7 +150,7 @@
         writeParameters(constructor);
         writeExceptions(constructor);
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
@@ -158,12 +159,7 @@
      * @param constructor the constructor being documented.
      */
     public void writeDeprecated(ConstructorDoc constructor) {
-        String output = ((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(constructor,
-            writer.getTagletWriterInstance(false))).toString();
-        if (output != null && output.trim().length() > 0) {
-            writer.print(output);
-        }
+        printDeprecated(constructor);
     }
 
     /**
@@ -172,10 +168,7 @@
      * @param constructor the constructor being documented.
      */
     public void writeComments(ConstructorDoc constructor) {
-        if (constructor.inlineTags().length > 0) {
-            writer.dd();
-            writer.printInlineComment(constructor);
-        }
+        printComment(constructor);
     }
 
     /**
@@ -191,7 +184,7 @@
      * Write the constructor footer.
      */
     public void writeConstructorFooter() {
-        writer.dlEnd();
+        printMemberFooter();
     }
 
     /**
@@ -219,8 +212,34 @@
         this.foundNonPubConstructor = foundNonPubConstructor;
     }
 
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Constructor_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Constructor_Summary");
+    }
+
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Constructor_Summary"),
+                configuration().getText("doclet.constructors")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header;
+        if (foundNonPubConstructor) {
+            header = new String[] {
+                configuration().getText("doclet.Modifier"),
+                configuration().getText("doclet.0_and_1",
+                        configuration().getText("doclet.Constructor"),
+                        configuration().getText("doclet.Description"))
+            };
+        }
+        else {
+            header = new String[] {
+                configuration().getText("doclet.0_and_1",
+                        configuration().getText("doclet.Constructor"),
+                        configuration().getText("doclet.Description"))
+            };
+        }
+        writer.summaryTableHeader(header, "col");
     }
 
     public void printSummaryAnchor(ClassDoc cd) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/DeprecatedListWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/DeprecatedListWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -35,6 +35,7 @@
  *
  * @see java.util.List
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class DeprecatedListWriter extends SubWriterHolderWriter {
 
@@ -55,6 +56,28 @@
         "doclet.Deprecated_Annotation_Type_Members"
     };
 
+    private static final String[] SUMMARY_KEYS = new String[] {
+        "doclet.deprecated_interfaces", "doclet.deprecated_classes",
+        "doclet.deprecated_enums", "doclet.deprecated_exceptions",
+        "doclet.deprecated_errors",
+        "doclet.deprecated_annotation_types",
+        "doclet.deprecated_fields",
+        "doclet.deprecated_methods", "doclet.deprecated_constructors",
+        "doclet.deprecated_enum_constants",
+        "doclet.deprecated_annotation_type_members"
+    };
+
+    private static final String[] HEADER_KEYS = new String[] {
+        "doclet.Interface", "doclet.Class",
+        "doclet.Enum", "doclet.Exceptions",
+        "doclet.Errors",
+        "doclet.AnnotationType",
+        "doclet.Field",
+        "doclet.Method", "doclet.Constructor",
+        "doclet.Enum_Constant",
+        "doclet.Annotation_Type_Member"
+    };
+
     private AbstractMemberWriter[] writers;
 
     private ConfigurationImpl configuration;
@@ -119,11 +142,20 @@
         ulEnd();
         println();
 
+        String memberTableSummary;
+        String[] memberTableHeader = new String[1];
         for (int i = 0; i < DeprecatedAPIListBuilder.NUM_TYPES; i++) {
             if (deprapi.hasDocumentation(i)) {
                 writeAnchor(deprapi, i);
+                memberTableSummary =
+                        configuration.getText("doclet.Member_Table_Summary",
+                        configuration.getText(HEADING_KEYS[i]),
+                        configuration.getText(SUMMARY_KEYS[i]));
+                memberTableHeader[0] = configuration.getText("doclet.0_and_1",
+                        configuration.getText(HEADER_KEYS[i]),
+                        configuration.getText("doclet.Description"));
                 writers[i].printDeprecatedAPI(deprapi.getList(i),
-                    HEADING_KEYS[i]);
+                    HEADING_KEYS[i], memberTableSummary, memberTableHeader);
             }
         }
         printDeprecatedFooter();
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/EnumConstantWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/EnumConstantWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,17 +25,17 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.io.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
-import com.sun.tools.doclets.internal.toolkit.taglets.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.javadoc.*;
-
-import java.io.*;
 
 /**
  * Writes enum constant documentation in HTML format.
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  */
 public class EnumConstantWriterImpl extends AbstractMemberWriter
     implements EnumConstantWriter, MemberSummaryWriter {
@@ -146,26 +146,21 @@
             strong(enumConstant.name());
         }
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
      * {@inheritDoc}
      */
     public void writeDeprecated(FieldDoc enumConstant) {
-        print(((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(enumConstant,
-            writer.getTagletWriterInstance(false))).toString());
+        printDeprecated(enumConstant);
     }
 
     /**
      * {@inheritDoc}
      */
     public void writeComments(FieldDoc enumConstant) {
-        if (enumConstant.inlineTags().length > 0) {
-            writer.dd();
-            writer.printInlineComment(enumConstant);
-        }
+        printComment(enumConstant);
     }
 
     /**
@@ -179,7 +174,7 @@
      * {@inheritDoc}
      */
     public void writeEnumConstantFooter() {
-        writer.dlEnd();
+        printMemberFooter();
     }
 
     /**
@@ -200,8 +195,23 @@
         return VisibleMemberMap.ENUM_CONSTANTS;
     }
 
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Enum_Constant_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Enum_Constant_Summary");
+    }
+
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Enum_Constant_Summary"),
+                configuration().getText("doclet.enum_constants")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header = new String[] {
+            configuration().getText("doclet.0_and_1",
+                    configuration().getText("doclet.Enum_Constant"),
+                    configuration().getText("doclet.Description"))
+        };
+        writer.summaryTableHeader(header, "col");
     }
 
     public void printSummaryAnchor(ClassDoc cd) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/FieldWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/FieldWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,12 +25,11 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.io.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
-import com.sun.tools.doclets.internal.toolkit.taglets.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.javadoc.*;
-
-import java.io.*;
 
 /**
  * Writes field documentation in HTML format.
@@ -38,6 +37,7 @@
  * @author Robert Field
  * @author Atul M Dambalkar
  * @author Jamie Ho (rewrite)
+ * @author Bhavesh Patel (Modified)
  */
 public class FieldWriterImpl extends AbstractMemberWriter
     implements FieldWriter, MemberSummaryWriter {
@@ -156,7 +156,7 @@
             strong(field.name());
         }
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
@@ -165,9 +165,7 @@
      * @param field the field being documented.
      */
     public void writeDeprecated(FieldDoc field) {
-        print(((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(field,
-            writer.getTagletWriterInstance(false))).toString());
+        printDeprecated(field);
     }
 
     /**
@@ -178,10 +176,12 @@
     public void writeComments(FieldDoc field) {
         ClassDoc holder = field.containingClass();
         if (field.inlineTags().length > 0) {
+            writer.printMemberDetailsListStartTag();
             if (holder.equals(classdoc) ||
                 (! (holder.isPublic() || Util.isLinkable(holder, configuration())))) {
                 writer.dd();
                 writer.printInlineComment(field);
+                writer.ddEnd();
             } else {
                 String classlink = writer.codeText(
                     writer.getDocLink(LinkInfoImpl.CONTEXT_FIELD_DOC_COPY,
@@ -196,6 +196,7 @@
                 writer.ddEnd();
                 writer.dd();
                 writer.printInlineComment(field);
+                writer.ddEnd();
             }
         }
     }
@@ -213,7 +214,7 @@
      * Write the field footer.
      */
     public void writeFieldFooter() {
-        writer.dlEnd();
+        printMemberFooter();
     }
 
     /**
@@ -236,8 +237,24 @@
         return VisibleMemberMap.FIELDS;
     }
 
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Field_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Field_Summary");
+    }
+
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Field_Summary"),
+                configuration().getText("doclet.fields")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header = new String[] {
+            writer.getModifierTypeHeader(),
+            configuration().getText("doclet.0_and_1",
+                    configuration().getText("doclet.Field"),
+                    configuration().getText("doclet.Description"))
+        };
+        writer.summaryTableHeader(header, "col");
     }
 
     public void printSummaryAnchor(ClassDoc cd) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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,17 +24,16 @@
  */
 
 package com.sun.tools.doclets.formats.html;
-import com.sun.tools.doclets.formats.html.markup.*;
 
-import com.sun.tools.doclets.internal.toolkit.*;
-import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.tools.doclets.internal.toolkit.taglets.*;
-
-import com.sun.javadoc.*;
 import java.io.*;
 import java.text.SimpleDateFormat;
 import java.util.*;
 
+import com.sun.javadoc.*;
+import com.sun.tools.doclets.formats.html.markup.*;
+import com.sun.tools.doclets.internal.toolkit.*;
+import com.sun.tools.doclets.internal.toolkit.util.*;
+import com.sun.tools.doclets.internal.toolkit.taglets.*;
 
 /**
  * Class for the Html Format Code Generation specific to JavaDoc.
@@ -44,6 +43,7 @@
  * @since 1.2
  * @author Atul M Dambalkar
  * @author Robert Field
+ * @author Bhavesh Patel (Modified)
  */
 public class HtmlDocletWriter extends HtmlDocWriter {
 
@@ -205,7 +205,13 @@
     private void printMethodInfo(MethodDoc method) {
         ClassDoc[] intfacs = method.containingClass().interfaces();
         MethodDoc overriddenMethod = method.overriddenMethod();
-        if (intfacs.length > 0 || overriddenMethod != null) {
+        // Check whether there is any implementation or overridden info to be
+        // printed. If no overridden or implementation info needs to be
+        // printed, do not print this section.
+        if ((intfacs.length > 0 &&
+                new ImplementedMethods(method, this.configuration).build().length > 0) ||
+                overriddenMethod != null) {
+            printMemberDetailsListStartTag();
             dd();
             printTagsInfoHeader();
             MethodWriterImpl.printImplementsInfo(this, method);
@@ -216,7 +222,6 @@
             printTagsInfoFooter();
             ddEnd();
         }
-        dd();
     }
 
     protected void printTags(Doc doc) {
@@ -230,41 +235,37 @@
         TagletWriter.genTagOuput(configuration.tagletManager, doc,
             configuration.tagletManager.getCustomTags(doc),
                 getTagletWriterInstance(false), output);
-        if (output.toString().trim().length() > 0) {
+        String outputString = output.toString().trim();
+        // For RootDoc, ClassDoc and PackageDoc, this section is not the
+        // definition description but the start of definition list.
+        if (!outputString.isEmpty()) {
+            if (!(doc instanceof RootDoc || doc instanceof ClassDoc ||
+                    doc instanceof PackageDoc)) {
+                printMemberDetailsListStartTag();
+                dd();
+            }
             printTagsInfoHeader();
-            print(output.toString());
+            print(outputString);
             printTagsInfoFooter();
-        } else if (! (doc instanceof ConstructorDoc ||
-            doc instanceof RootDoc || doc instanceof ClassDoc)) {
-            //To be consistent with 1.4.2 output.
-            //I hate to do this but we have to pass the diff test to prove
-            //nothing has broken.
-            printTagsInfoHeader();
-            printTagsInfoFooter();
+            if (!(doc instanceof RootDoc || doc instanceof ClassDoc ||
+                    doc instanceof PackageDoc))
+                ddEnd();
         }
     }
 
     /**
-     * Check whether there are any tags to be printed.
+     * Check whether there are any tags for Serialization Overview
+     * section to be printed.
      *
-     * @param doc the Doc object to check for tags.
+     * @param field the FieldDoc object to check for tags.
      * @return true if there are tags to be printed else return false.
      */
-    protected boolean hasTagsToPrint(Doc doc) {
-        if (doc instanceof MethodDoc) {
-            ClassDoc[] intfacs = ((MethodDoc)doc).containingClass().interfaces();
-            MethodDoc overriddenMethod = ((MethodDoc)doc).overriddenMethod();
-            if ((intfacs.length > 0 &&
-                new ImplementedMethods((MethodDoc)doc, this.configuration).build().length > 0) ||
-                overriddenMethod != null) {
-                return true;
-            }
-        }
+    protected boolean hasSerializationOverviewTags(FieldDoc field) {
         TagletOutputImpl output = new TagletOutputImpl("");
-        TagletWriter.genTagOuput(configuration.tagletManager, doc,
-            configuration.tagletManager.getCustomTags(doc),
+        TagletWriter.genTagOuput(configuration.tagletManager, field,
+            configuration.tagletManager.getCustomTags(field),
                 getTagletWriterInstance(false), output);
-        return (output.toString().trim().isEmpty());
+        return (!output.toString().trim().isEmpty());
     }
 
     /**
@@ -786,6 +787,15 @@
     }
 
     /**
+     * Print the Html table tag for the index summary tables.
+     *
+     * @param summary the summary for the table tag summary attribute.
+     */
+    public void tableIndexSummary(String summary) {
+        table(1, "100%", 3, 0, summary);
+    }
+
+    /**
      * Same as {@link #tableIndexSummary()}.
      */
     public void tableIndexDetail() {
@@ -801,6 +811,40 @@
     }
 
     /**
+     * Print table caption.
+     */
+    public void tableCaptionStart() {
+        captionStyle("TableCaption");
+    }
+
+    /**
+     * Print table sub-caption.
+     */
+    public void tableSubCaptionStart() {
+        captionStyle("TableSubCaption");
+    }
+
+    /**
+     * Print table caption end tags.
+     */
+    public void tableCaptionEnd() {
+        captionEnd();
+    }
+
+    /**
+     * Print summary table header.
+     */
+    public void summaryTableHeader(String[] header, String scope) {
+        tr();
+        for ( int i=0; i < header.length; i++ ) {
+            thScopeNoWrap("TableHeader", scope);
+            print(header[i]);
+            thEnd();
+        }
+        trEnd();
+    }
+
+    /**
      * Prine table header information about color, column span and the font.
      *
      * @param color Background color.
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialFieldWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialFieldWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,11 +25,12 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.util.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.javadoc.*;
-import java.util.*;
 
 /**
  * Generate serialized form for serializable fields.
@@ -37,6 +38,7 @@
  * <code>serialField</code> is processed.
  *
  * @author Joe Fialli
+ * @author Bhavesh Patel (Modified)
  */
 public class HtmlSerialFieldWriter extends FieldWriterImpl
     implements SerializedFormWriter.SerialFieldWriter {
@@ -75,7 +77,7 @@
             writer.println();
             if (heading.equals(
                    configuration().getText("doclet.Serialized_Form_class"))) {
-                writer.dl();
+                assert !writer.getMemberDetailsListPrinted();
             }
         } else {
             writer.printTableHeadingBackground(heading);
@@ -102,7 +104,7 @@
         print(fieldDimensions + ' ');
         strong(fieldName);
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
@@ -111,9 +113,7 @@
      * @param field the field to document.
      */
     public void writeMemberDeprecatedInfo(FieldDoc field) {
-        print(((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(field,
-            writer.getTagletWriterInstance(false))).toString());
+        printDeprecated(field);
     }
 
     /**
@@ -123,14 +123,17 @@
      */
     public void writeMemberDescription(FieldDoc field) {
         if (field.inlineTags().length > 0) {
+            writer.printMemberDetailsListStartTag();
             writer.dd();
             writer.printInlineComment(field);
+            writer.ddEnd();
         }
         Tag[] tags = field.tags("serial");
         if (tags.length > 0) {
-            writer.dt();
+            writer.printMemberDetailsListStartTag();
             writer.dd();
             writer.printInlineComment(field, tags[0]);
+            writer.ddEnd();
         }
     }
 
@@ -140,9 +143,14 @@
      * @param serialFieldTag the field to document (represented by tag).
      */
     public void writeMemberDescription(SerialFieldTag serialFieldTag) {
-        writer.dd();
-        writer.print(serialFieldTag.description());
-        writer.dlEnd();
+        String serialFieldTagDesc = serialFieldTag.description().trim();
+        if (!serialFieldTagDesc.isEmpty()) {
+            writer.dl();
+            writer.dd();
+            writer.print(serialFieldTagDesc);
+            writer.ddEnd();
+            writer.dlEnd();
+        }
     }
 
     /**
@@ -151,33 +159,57 @@
      * @param field the field to document.
      */
     public void writeMemberTags(FieldDoc field) {
-        writer.dl();
         TagletOutputImpl output = new TagletOutputImpl("");
         TagletWriter.genTagOuput(configuration().tagletManager, field,
             configuration().tagletManager.getCustomTags(field),
                 writer.getTagletWriterInstance(false), output);
-        if (output.toString().length() > 0) {
-            print(output.toString());
+        String outputString = output.toString().trim();
+        if (!outputString.isEmpty()) {
+            writer.printMemberDetailsListStartTag();
+            writer.dd();
+            writer.dl();
+            print(outputString);
+            writer.dlEnd();
+            writer.ddEnd();
         }
-        writer.dlEnd();
-    }
-    public void writeMemberFooter(FieldDoc member) {
-        writer.dlEnd();
     }
 
     /**
-     * Check to see if member details should be printed. If
+     * Check to see if overview details should be printed. If
      * nocomment option set or if there is no text to be printed
-     * for deprecation info, inline comment, no serial tag or inline tags,
-     * do not print member details.
+     * for deprecation info, comment or tags, do not print overview details.
+     *
+     * @param field the field to check overview details for.
+     * @return true if overview details need to be printed
      */
-    public boolean shouldPrintMemberDetails(FieldDoc field) {
-        if (!configuration().nocomment)
-            if((field.inlineTags().length > 0) ||
-                (field.tags("serial").length > 0) || (writer.hasTagsToPrint(field)))
+    public boolean shouldPrintOverview(FieldDoc field) {
+        if (!configuration().nocomment) {
+            if(!field.commentText().isEmpty() ||
+                    writer.hasSerializationOverviewTags(field))
                 return true;
-        if (!Util.isDeprecated(field))
+        }
+        if (field.tags("deprecated").length > 0)
             return true;
         return false;
     }
+
+    public void writeMemberFooter() {
+        printMemberFooter();
+    }
+
+    /**
+     * Write the footer information. If the serilization overview section was
+     * printed, check for definition list and close list tag.
+     *
+     * @param heading the heading that was written.
+     */
+    public void writeFooter(String heading) {
+        if (printedOverallAnchor) {
+            if (heading.equals(
+                   configuration().getText("doclet.Serialized_Form_class"))) {
+                writer.printMemberDetailsListEndTag();
+                assert !writer.getMemberDetailsListPrinted();
+            }
+        }
+    }
 }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,9 +25,9 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
-import com.sun.javadoc.*;
 
 /**
  * Generate serialized form for Serializable/Externalizable methods.
@@ -66,14 +66,12 @@
         writeSignature(member);
     }
 
-    public void writeMemberFooter(MethodDoc member) {
-        writer.dlEnd();
+    public void writeMemberFooter() {
+        printMemberFooter();
     }
 
     public void writeDeprecatedMemberInfo(MethodDoc member) {
-        print(((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(member,
-            writer.getTagletWriterInstance(false))).toString());
+        printDeprecated(member);
     }
 
     public void writeMemberDescription(MethodDoc member) {
@@ -81,23 +79,27 @@
     }
 
     public void writeMemberTags(MethodDoc member) {
-        writer.dd();
-        writer.dl();
         TagletOutputImpl output = new TagletOutputImpl("");
         TagletManager tagletManager =
             ConfigurationImpl.getInstance().tagletManager;
         TagletWriter.genTagOuput(tagletManager, member,
             tagletManager.getSerializedFormTags(),
             writer.getTagletWriterInstance(false), output);
-        print(output.toString());
+        String outputString = output.toString().trim();
+        if (!outputString.isEmpty()) {
+            writer.printMemberDetailsListStartTag();
+            writer.dd();
+            writer.dl();
+            print(outputString);
+            writer.dlEnd();
+            writer.ddEnd();
+        }
         MethodDoc method = member;
         if (method.name().compareTo("writeExternal") == 0
                 && method.tags("serialData").length == 0) {
             serialWarning(member.position(), "doclet.MissingSerialDataTag",
                 method.containingClass().qualifiedName(), method.name());
         }
-        writer.ddEnd();
-        writer.dlEnd();
     }
 
     protected void printTypeLinkNoDimension(Type type) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/MethodWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/MethodWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,19 +25,20 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.io.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
 
-import java.io.*;
-import com.sun.javadoc.*;
-
 /**
  * Writes method documentation in HTML format.
  *
  * @author Robert Field
  * @author Atul M Dambalkar
  * @author Jamie Ho (rewrite)
+ * @author Bhavesh Patel (Modified)
  */
 public class MethodWriterImpl extends AbstractExecutableMemberWriter
         implements MethodWriter, MemberSummaryWriter {
@@ -172,7 +173,7 @@
         writeParameters(method);
         writeExceptions(method);
         writer.preEnd();
-        writer.dl();
+        assert !writer.getMemberDetailsListPrinted();
     }
 
     /**
@@ -181,12 +182,7 @@
      * @param method the method being documented.
      */
     public void writeDeprecated(MethodDoc method) {
-        String output = ((TagletOutputImpl)
-            (new DeprecatedTaglet()).getTagletOutput(method,
-            writer.getTagletWriterInstance(false))).toString();
-        if (output != null && output.trim().length() > 0) {
-            writer.print(output);
-        }
+        printDeprecated(method);
     }
 
     /**
@@ -197,11 +193,13 @@
     public void writeComments(Type holder, MethodDoc method) {
         ClassDoc holderClassDoc = holder.asClassDoc();
         if (method.inlineTags().length > 0) {
+            writer.printMemberDetailsListStartTag();
             if (holder.asClassDoc().equals(classdoc) ||
                 (! (holderClassDoc.isPublic() ||
                     Util.isLinkable(holderClassDoc, configuration())))) {
                 writer.dd();
                 writer.printInlineComment(method);
+                writer.ddEnd();
             } else {
                 String classlink = writer.codeText(
                     writer.getDocLink(LinkInfoImpl.CONTEXT_METHOD_DOC_COPY,
@@ -217,6 +215,7 @@
                 writer.ddEnd();
                 writer.dd();
                 writer.printInlineComment(method);
+                writer.ddEnd();
             }
         }
     }
@@ -234,8 +233,7 @@
      * Write the method footer.
      */
     public void writeMethodFooter() {
-        writer.ddEnd();
-        writer.dlEnd();
+        printMemberFooter();
     }
 
     /**
@@ -258,8 +256,24 @@
         return VisibleMemberMap.METHODS;
     }
 
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Method_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Method_Summary");
+    }
+
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Method_Summary"),
+                configuration().getText("doclet.methods")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header = new String[] {
+            writer.getModifierTypeHeader(),
+            configuration().getText("doclet.0_and_1",
+                    configuration().getText("doclet.Method"),
+                    configuration().getText("doclet.Description"))
+        };
+        writer.summaryTableHeader(header, "col");
     }
 
     public void printSummaryAnchor(ClassDoc cd) {
@@ -318,6 +332,7 @@
             String name = method.name();
             writer.dt();
             writer.strongText(label);
+            writer.dtEnd();
             writer.dd();
             String methLink = writer.codeText(
                 writer.getLink(
@@ -326,6 +341,7 @@
                         writer.getAnchor(method), name, false)
                 ));
             writer.printText("doclet.in_class", methLink, overriddenTypeLink);
+            writer.ddEnd();
         }
     }
 
@@ -364,11 +380,13 @@
                     LinkInfoImpl.CONTEXT_METHOD_SPECIFIED_BY, intfac)));
             writer.dt();
             writer.strongText("doclet.Specified_By");
+            writer.dtEnd();
             writer.dd();
             methlink = writer.codeText(writer.getDocLink(
                 LinkInfoImpl.CONTEXT_MEMBER, implementedMeth,
                 implementedMeth.name(), false));
             writer.printText("doclet.in_interface", methlink, intfaclink);
+            writer.ddEnd();
         }
 
     }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/NestedClassWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/NestedClassWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,11 +25,11 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import java.io.*;
+
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.javadoc.*;
-
-import java.io.*;
 
 /**
  * Writes nested class documentation in HTML format.
@@ -37,6 +37,7 @@
  * @author Robert Field
  * @author Atul M Dambalkar
  * @author Jamie Ho (rewrite)
+ * @author Bhavesh Patel (Modified)
  */
 public class NestedClassWriterImpl extends AbstractMemberWriter
     implements MemberSummaryWriter {
@@ -129,7 +130,6 @@
             writer.println("");
         }
         writer.anchor(nestedClass.name());
-        writer.dl();
         writer.h3();
         writer.print(nestedClass.name());
         writer.h3End();
@@ -148,8 +148,35 @@
         return VisibleMemberMap.INNERCLASSES;
     }
 
-    public void printSummaryLabel(ClassDoc cd) {
-        writer.strongText("doclet.Nested_Class_Summary");
+    public void printSummaryLabel() {
+        writer.printText("doclet.Nested_Class_Summary");
+    }
+
+    public void printTableSummary() {
+        writer.tableIndexSummary(configuration().getText("doclet.Member_Table_Summary",
+                configuration().getText("doclet.Nested_Class_Summary"),
+                configuration().getText("doclet.nested_classes")));
+    }
+
+    public void printSummaryTableHeader(ProgramElementDoc member) {
+        String[] header;
+        if (member.isInterface()) {
+            header = new String[] {
+                writer.getModifierTypeHeader(),
+                configuration().getText("doclet.0_and_1",
+                        configuration().getText("doclet.Interface"),
+                        configuration().getText("doclet.Description"))
+            };
+        }
+        else {
+            header = new String[] {
+                writer.getModifierTypeHeader(),
+                configuration().getText("doclet.0_and_1",
+                        configuration().getText("doclet.Class"),
+                        configuration().getText("doclet.Description"))
+            };
+        }
+        writer.summaryTableHeader(header, "col");
     }
 
     public void printSummaryAnchor(ClassDoc cd) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageIndexFrameWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageIndexFrameWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -114,7 +114,7 @@
      *
      * @param text Text string will not be used in this method.
      */
-    protected void printIndexHeader(String text) {
+    protected void printIndexHeader(String text, String tableSummary) {
         printTableHeader(false);
     }
 
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageIndexWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageIndexWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,6 +36,7 @@
  * with the "pacakge-summary.html" file for the clicked package.
  *
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class PackageIndexWriter extends AbstractPackageIndexWriter {
 
@@ -123,7 +124,10 @@
         List<PackageDoc> list = groupPackageMap.get(groupname);
             if (list != null && list.size() > 0) {
                 printIndexContents(list.toArray(new PackageDoc[list.size()]),
-                                    groupname);
+                        groupname,
+                        configuration.getText("doclet.Member_Table_Summary",
+                        groupname,
+                        configuration.getText("doclet.packages")));
             }
         }
     }
@@ -149,11 +153,12 @@
     /**
      * Print Html tags for the table for this package index.
      */
-    protected void printIndexHeader(String text) {
-        tableIndexSummary();
-        tableHeaderStart("#CCCCFF");
-        strong(text);
-        tableHeaderEnd();
+    protected void printIndexHeader(String text, String tableSummary) {
+        tableIndexSummary(tableSummary);
+        tableCaptionStart();
+        print(text);
+        tableCaptionEnd();
+        summaryTableHeader(packageTableHeader, "col");
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageTreeWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageTreeWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,9 +25,10 @@
 
 package com.sun.tools.doclets.formats.html;
 
-import com.sun.tools.doclets.internal.toolkit.util.*;
+import java.io.*;
+
 import com.sun.javadoc.*;
-import java.io.*;
+import com.sun.tools.doclets.internal.toolkit.util.*;
 
 /**
  * Class to generate Tree page for a package. The name of the file generated is
@@ -145,8 +146,10 @@
         dl();
         dt();
         strongText("doclet.Package_Hierarchies");
+        dtEnd();
         dd();
         navLinkMainTree(configuration.getText("doclet.All_Packages"));
+        ddEnd();
         dlEnd();
         hr();
     }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageUseWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageUseWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -34,6 +34,7 @@
  * Generate package usage information.
  *
  * @author Robert G. Field
+ * @author Bhavesh Patel (Modified)
  */
 public class PackageUseWriter extends SubWriterHolderWriter {
 
@@ -131,11 +132,12 @@
     }
 
     protected void generatePackageList() throws IOException {
-        tableIndexSummary();
-        tableHeaderStart("#CCCCFF");
+        tableIndexSummary(useTableSummary);
+        tableCaptionStart();
         printText("doclet.ClassUse_Packages.that.use.0",
             getPackageLink(pkgdoc, Util.getPackageName(pkgdoc), false));
-        tableHeaderEnd();
+        tableCaptionEnd();
+        summaryTableHeader(packageTableHeader, "col");
         Iterator<String> it = usingPackageToUsedClasses.keySet().iterator();
         while (it.hasNext()) {
             PackageDoc pkg = configuration.root.packageNamed(it.next());
@@ -147,6 +149,11 @@
     }
 
     protected void generateClassList() throws IOException {
+        String[] classTableHeader = new String[] {
+            configuration.getText("doclet.0_and_1",
+                    configuration.getText("doclet.Class"),
+                    configuration.getText("doclet.Description"))
+        };
         Iterator<String> itp = usingPackageToUsedClasses.keySet().iterator();
         while (itp.hasNext()) {
             String packageName = itp.next();
@@ -154,12 +161,14 @@
             if (usingPackage != null) {
                 anchor(usingPackage.name());
             }
-            tableIndexSummary();
-            tableHeaderStart("#CCCCFF");
+            tableIndexSummary(configuration.getText("doclet.Use_Table_Summary",
+                    configuration.getText("doclet.classes")));
+            tableCaptionStart();
             printText("doclet.ClassUse_Classes.in.0.used.by.1",
                 getPackageLink(pkgdoc, Util.getPackageName(pkgdoc), false),
                 getPackageLink(usingPackage,Util.getPackageName(usingPackage), false));
-            tableHeaderEnd();
+            tableCaptionEnd();
+            summaryTableHeader(classTableHeader, "col");
             Iterator<ClassDoc> itc =
                     usingPackageToUsedClasses.get(packageName).iterator();
             while (itc.hasNext()) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -38,6 +38,7 @@
  * class-kind will update the frame with the clicked class-kind page.
  *
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class PackageWriterImpl extends HtmlDocletWriter
     implements PackageSummaryWriter {
@@ -107,14 +108,15 @@
     /**
      * {@inheritDoc}
      */
-    public void writeClassesSummary(ClassDoc[] classes, String label) {
+    public void writeClassesSummary(ClassDoc[] classes, String label, String tableSummary, String[] tableHeader) {
         if(classes.length > 0) {
             Arrays.sort(classes);
-            tableIndexSummary();
+            tableIndexSummary(tableSummary);
             boolean printedHeading = false;
             for (int i = 0; i < classes.length; i++) {
                 if (!printedHeading) {
-                    printFirstRow(label);
+                    printTableCaption(label);
+                    printFirstRow(tableHeader);
                     printedHeading = true;
                 }
                 if (!Util.isCoreClass(classes[i]) ||
@@ -149,14 +151,23 @@
     }
 
     /**
+     * Print the table caption for the class-listing.
+     *
+     * @param label label for the Class kind listing.
+     */
+    protected void printTableCaption(String label) {
+        tableCaptionStart();
+        print(label);
+        tableCaptionEnd();
+    }
+
+    /**
      * Print the table heading for the class-listing.
      *
-     * @param label Label for the Class kind listing.
+     * @param tableHeader table header string for the Class listing.
      */
-    protected void printFirstRow(String label) {
-        tableHeaderStart("#CCCCFF");
-        strong(label);
-        tableHeaderEnd();
+    protected void printFirstRow(String[] tableHeader) {
+        summaryTableHeader(tableHeader, "col");
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/StylesheetWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/StylesheetWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -33,6 +33,7 @@
  * Writes the style sheet for the doclet output.
  *
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class StylesheetWriter extends HtmlDocletWriter {
 
@@ -115,6 +116,13 @@
         println("background-color:#FFFFFF; color:#000000}");
         print(".NavBarCell3    { font-family: Arial, Helvetica, sans-serif; ");
         println("background-color:#FFFFFF; color:#000000}");
+
+        print("/* "); printText("doclet.Style_line_12"); println(" */");
+        print(".TableCaption     { background: #CCCCFF; color:#000000; text-align: left; font-size: 150%; font-weight: bold; border-left: 2px ridge; border-right: 2px ridge; border-top: 2px ridge; padding-left: 5px; }");
+        print(" /* "); printText("doclet.Style_line_5"); println(" */");
+        print(".TableSubCaption  { background: #EEEEFF; color:#000000; text-align: left; font-weight: bold; border-left: 2px ridge; border-right: 2px ridge; border-top: 2px ridge; padding-left: 5px; }");
+        print(" /* "); printText("doclet.Style_line_6"); println(" */");
+        print(".TableHeader     { text-align: center; font-size: 80%; font-weight: bold; }");
         println("");
 
     }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -43,6 +43,7 @@
  *
  * @author Robert Field
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public abstract class SubWriterHolderWriter extends HtmlDocletWriter {
 
@@ -72,10 +73,11 @@
 
     public void printSummaryHeader(AbstractMemberWriter mw, ClassDoc cd) {
         mw.printSummaryAnchor(cd);
-        tableIndexSummary();
-        tableHeaderStart("#CCCCFF");
-        mw.printSummaryLabel(cd);
-        tableHeaderEnd();
+        mw.printTableSummary();
+        tableCaptionStart();
+        mw.printSummaryLabel();
+        tableCaptionEnd();
+        mw.printSummaryTableHeader(cd);
     }
 
     public void printTableHeadingBackground(String str) {
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletOutputImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletOutputImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,17 +25,18 @@
 
 package com.sun.tools.doclets.formats.html;
 
+import com.sun.javadoc.*;
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.builders.SerializedFormBuilder;
 import com.sun.tools.doclets.internal.toolkit.taglets.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.javadoc.*;
 
 /**
  * The taglet writer that writes HTML.
  *
  * @since 1.5
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  */
 
 public class TagletWriterImpl extends TagletWriter {
@@ -99,11 +100,12 @@
                     output.append(DocletConstants.NL + "<P>" +
                         DocletConstants.NL);
                 }
+                output.append("</DD>");
             } else {
                 if (Util.isDeprecated(member.containingClass())) {
                     output.append("<DD><STRONG>" +
                     ConfigurationImpl.getInstance().
-                            getText("doclet.Deprecated") + "</STRONG>&nbsp;");
+                            getText("doclet.Deprecated") + "</STRONG>&nbsp;</DD>");
                 }
             }
         }
@@ -123,7 +125,7 @@
     public TagletOutput getParamHeader(String header) {
         StringBuffer result = new StringBuffer();
         result.append("<DT>");
-        result.append("<STRONG>" +  header + "</STRONG>");
+        result.append("<STRONG>" +  header + "</STRONG></DT>");
         return new TagletOutputImpl(result.toString());
     }
 
@@ -132,7 +134,7 @@
      */
     public TagletOutput paramTagOutput(ParamTag paramTag, String paramName) {
         TagletOutput result = new TagletOutputImpl("<DD><CODE>" + paramName + "</CODE>"
-         + " - " + htmlWriter.commentTagsToString(paramTag, null, paramTag.inlineTags(), false));
+         + " - " + htmlWriter.commentTagsToString(paramTag, null, paramTag.inlineTags(), false) + "</DD>");
         return result;
     }
 
@@ -142,9 +144,9 @@
     public TagletOutput returnTagOutput(Tag returnTag) {
         TagletOutput result = new TagletOutputImpl(DocletConstants.NL + "<DT>" +
             "<STRONG>" + htmlWriter.configuration.getText("doclet.Returns") +
-            "</STRONG>" + "<DD>" +
+            "</STRONG>" + "</DT>" + "<DD>" +
             htmlWriter.commentTagsToString(returnTag, null, returnTag.inlineTags(),
-            false));
+            false) + "</DD>");
         return result;
     }
 
@@ -174,22 +176,21 @@
         }
         if (holder.isClass() && ((ClassDoc)holder).isSerializable()) {
             //Automatically add link to serialized form page for serializable classes.
-            if (!(SerializedFormBuilder.serialInclude(holder) &&
+            if ((SerializedFormBuilder.serialInclude(holder) &&
                       SerializedFormBuilder.serialInclude(((ClassDoc)holder).containingPackage()))) {
-                return result.equals("") ? null : new TagletOutputImpl(result);
+                result = addSeeHeader(result);
+                result += htmlWriter.getHyperLink(htmlWriter.relativePath + "serialized-form.html",
+                        ((ClassDoc)holder).qualifiedName(), htmlWriter.configuration.getText("doclet.Serialized_Form"), false);
             }
-            result = addSeeHeader(result);
-            result += htmlWriter.getHyperLink(htmlWriter.relativePath + "serialized-form.html",
-                ((ClassDoc)holder).qualifiedName(), htmlWriter.configuration.getText("doclet.Serialized_Form"), false);
         }
-        return result.equals("") ? null : new TagletOutputImpl(result);
+        return result.equals("") ? null : new TagletOutputImpl(result + "</DD>");
     }
 
     private String addSeeHeader(String result) {
         if (result != null && result.length() > 0) {
             return result + ", " + DocletConstants.NL;
         } else {
-            return "<DT><STRONG>" + htmlWriter.configuration().getText("doclet.See_Also") + "</STRONG><DD>";
+            return "<DT><STRONG>" + htmlWriter.configuration().getText("doclet.See_Also") + "</STRONG></DT><DD>";
         }
      }
 
@@ -205,7 +206,8 @@
             }
             result += htmlWriter.commentTagsToString(simpleTags[i], null, simpleTags[i].inlineTags(), false);
         }
-         return new TagletOutputImpl(result + "</DD>" + DocletConstants.NL);
+        result += "</DD>" + DocletConstants.NL;
+        return new TagletOutputImpl(result);
     }
 
     /**
@@ -222,7 +224,7 @@
      */
     public TagletOutput getThrowsHeader() {
         return new TagletOutputImpl(DocletConstants.NL + "<DT>" + "<STRONG>" +
-            htmlWriter.configuration().getText("doclet.Throws") + "</STRONG>");
+            htmlWriter.configuration().getText("doclet.Throws") + "</STRONG></DT>");
     }
 
     /**
@@ -241,6 +243,7 @@
         if (text != null && text.toString().length() > 0) {
             result += " - " + text;
         }
+        result += "</DD>";
         return new TagletOutputImpl(result);
     }
 
@@ -250,7 +253,7 @@
     public TagletOutput throwsTagOutput(Type throwsType) {
         return new TagletOutputImpl(DocletConstants.NL + "<DD>" +
             htmlWriter.codeText(htmlWriter.getLink(
-                new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER, throwsType))));
+                new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER, throwsType))) + "</DD>");
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TreeWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TreeWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -25,9 +25,11 @@
 
 package com.sun.tools.doclets.formats.html;
 
-import com.sun.tools.doclets.internal.toolkit.util.*;
+import java.io.*;
+
 import com.sun.javadoc.*;
-import java.io.*;
+import com.sun.tools.doclets.internal.toolkit.util.*;
+
 /**
  * Generate Class Hierarchy page for all the Classes in this run.  Use
  * ClassTree for building the Tree. The name of
@@ -120,6 +122,7 @@
             dl();
             dt();
             strongText("doclet.Package_Hierarchies");
+            dtEnd();
             dd();
             for (int i = 0; i < packages.length; i++) {
                 if (packages[i].name().length() == 0) {
@@ -131,6 +134,7 @@
                     print(", ");
                 }
             }
+            ddEnd();
             dlEnd();
             hr();
         }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlDocWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlDocWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -245,6 +245,31 @@
     }
 
     /**
+     * Keep track of member details list. Print the definition list start tag
+     * if it is not printed yet.
+     */
+    public void printMemberDetailsListStartTag () {
+        if (!getMemberDetailsListPrinted()) {
+            dl();
+            memberDetailsListPrinted = true;
+        }
+    }
+
+    /**
+     * Print the definition list end tag if the list start tag was printed.
+     */
+    public void printMemberDetailsListEndTag () {
+        if (getMemberDetailsListPrinted()) {
+            dlEnd();
+            memberDetailsListPrinted = false;
+        }
+    }
+
+    public boolean getMemberDetailsListPrinted() {
+        return memberDetailsListPrinted;
+    }
+
+    /**
      * Print the frameset version of the Html file header.
      * Called only when generating an HTML frameset file.
      *
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,10 @@
 
 package com.sun.tools.doclets.formats.html.markup;
 
+import java.io.*;
+
 import com.sun.tools.doclets.internal.toolkit.*;
 import com.sun.tools.doclets.internal.toolkit.util.*;
-import java.io.*;
 
 /**
  * Class for the Html format code generation.
@@ -36,6 +37,7 @@
  *
  * @since 1.2
  * @author Atul M Dambalkar
+ * @author Bhavesh Patel (Modified)
  */
 public class HtmlWriter extends PrintWriter {
 
@@ -61,6 +63,26 @@
     protected Configuration configuration;
 
     /**
+     * The flag to indicate whether a member details list is printed or not.
+     */
+    protected boolean memberDetailsListPrinted;
+
+    /**
+     * Header for tables displaying packages and description..
+     */
+    protected final String[] packageTableHeader;
+
+    /**
+     * Summary for use tables displaying class and package use.
+     */
+    protected final String useTableSummary;
+
+    /**
+     * Column header for class docs displaying Modifier and Type header.
+     */
+    protected final String modifierTypeHeader;
+
+    /**
      * Constructor.
      *
      * @param path The directory path to be created for this file
@@ -79,6 +101,16 @@
         super(Util.genWriter(configuration, path, filename, docencoding));
         this.configuration = configuration;
         htmlFilename = filename;
+        this.memberDetailsListPrinted = false;
+        packageTableHeader = new String[] {
+            configuration.getText("doclet.Package"),
+            configuration.getText("doclet.Description")
+        };
+        useTableSummary = configuration.getText("doclet.Use_Table_Summary",
+                configuration.getText("doclet.packages"));
+        modifierTypeHeader = configuration.getText("doclet.0_and_1",
+                configuration.getText("doclet.Modifier"),
+                configuration.getText("doclet.Type"));
     }
 
     /**
@@ -529,7 +561,14 @@
     }
 
     /**
-     * Print &lt;DT&gt; tag.
+     * Print &lt;/DT&gt; tag.
+     */
+    public void dtEnd() {
+        print("</DT>");
+    }
+
+    /**
+     * Print &lt;DD&gt; tag.
      */
     public void dd() {
         print("<DD>");
@@ -789,6 +828,26 @@
     }
 
     /**
+     * Print HTML &lt;TABLE BORDER="border" WIDTH="width"
+     * CELLPADDING="cellpadding" CELLSPACING="cellspacing" SUMMARY="summary"&gt; tag.
+     *
+     * @param border       Border size.
+     * @param width        Width of the table.
+     * @param cellpadding  Cellpadding for the table cells.
+     * @param cellspacing  Cellspacing for the table cells.
+     * @param summary      Table summary.
+     */
+    public void table(int border, String width, int cellpadding,
+                      int cellspacing, String summary) {
+        println(DocletConstants.NL +
+                "<TABLE BORDER=\"" + border +
+                "\" WIDTH=\"" + width +
+                "\" CELLPADDING=\"" + cellpadding +
+                "\" CELLSPACING=\"" + cellspacing +
+                "\" SUMMARY=\"" + summary + "\">");
+    }
+
+    /**
      * Print HTML &lt;TABLE BORDER="border" CELLPADDING="cellpadding"
      * CELLSPACING="cellspacing"&gt; tag.
      *
@@ -805,6 +864,23 @@
     }
 
     /**
+     * Print HTML &lt;TABLE BORDER="border" CELLPADDING="cellpadding"
+     * CELLSPACING="cellspacing" SUMMARY="summary"&gt; tag.
+     *
+     * @param border       Border size.
+     * @param cellpadding  Cellpadding for the table cells.
+     * @param cellspacing  Cellspacing for the table cells.
+     * @param summary      Table summary.
+     */
+    public void table(int border, int cellpadding, int cellspacing, String summary) {
+        println(DocletConstants.NL +
+                "<TABLE BORDER=\"" + border +
+                "\" CELLPADDING=\"" + cellpadding +
+                "\" CELLSPACING=\"" + cellspacing +
+                "\" SUMMARY=\"" + summary + "\">");
+    }
+
+    /**
      * Print HTML &lt;TABLE BORDER="border" WIDTH="width"&gt;
      *
      * @param border       Border size.
@@ -899,6 +975,23 @@
     }
 
     /**
+     * Print &lt;CAPTION CLASS="stylename"&gt; tag. Adds a newline character
+     * at the end.
+     *
+     * @param stylename style to be applied.
+     */
+    public void captionStyle(String stylename) {
+        println("<CAPTION CLASS=\"" + stylename + "\">");
+    }
+
+    /**
+     * Print &lt;/CAPTION&gt; tag. Add a newline character at the end.
+     */
+    public void captionEnd() {
+        println("</CAPTION>");
+    }
+
+    /**
      * Print &lt;TR BGCOLOR="color" CLASS="stylename"&gt; tag. Adds a newline character
      * at the end.
      *
@@ -939,6 +1032,23 @@
     }
 
     /**
+     * Print &lt;TH CLASS="stylename" SCOPE="scope" NOWRAP&gt; tag.
+     *
+     * @param stylename style to be applied.
+     * @param scope the scope attribute.
+     */
+    public void thScopeNoWrap(String stylename, String scope) {
+        print("<TH CLASS=\"" + stylename + "\" SCOPE=\"" + scope + "\" NOWRAP>");
+    }
+
+    /*
+     * Returns a header for Modifier and Type column of a table.
+     */
+    public String getModifierTypeHeader() {
+        return modifierTypeHeader;
+    }
+
+    /**
      * Print &lt;TH align="align" COLSPAN=i&gt; tag.
      *
      * @param align the align attribute.
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/resources/standard.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/resources/standard.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -83,6 +83,17 @@
 doclet.Deprecated_Methods=Deprecated Methods
 doclet.Deprecated_Enum_Constants=Deprecated Enum Constants
 doclet.Deprecated_Annotation_Type_Members=Deprecated Annotation Type Elements
+doclet.deprecated_classes=deprecated classes
+doclet.deprecated_enums=deprecated enums
+doclet.deprecated_interfaces=deprecated interfaces
+doclet.deprecated_exceptions=deprecated exceptions
+doclet.deprecated_annotation_types=deprecated annotation types
+doclet.deprecated_errors=deprecated errors
+doclet.deprecated_fields=deprecated fields
+doclet.deprecated_constructors=deprecated constructors
+doclet.deprecated_methods=deprecated methods
+doclet.deprecated_enum_constants=deprecated enum constants
+doclet.deprecated_annotation_type_members=deprecated annotation type elements
 doclet.Frame_Output=Frame Output
 doclet.Docs_generated_by_Javadoc=Documentation generated by Javadoc.
 doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
@@ -171,6 +182,7 @@
 doclet.Style_line_9=Example of smaller, sans-serif font in frames
 doclet.Style_line_10=Navigation bar fonts and colors
 doclet.Style_line_11=Dark Blue
+doclet.Style_line_12=Table caption style
 doclet.ClassUse_Packages.that.use.0=Packages that use {0}
 doclet.ClassUse_Uses.of.0.in.1=Uses of {0} in {1}
 doclet.ClassUse_Classes.in.0.used.by.1=Classes in {0} used by {1}
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/PackageSummaryWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/PackageSummaryWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -64,7 +64,7 @@
      * @param classes the array of classes to document.
      * @param label the label for this table.
      */
-    public abstract void writeClassesSummary(ClassDoc[] classes, String label);
+    public abstract void writeClassesSummary(ClassDoc[] classes, String label, String tableSummary, String[] tableHeader);
 
     /**
      * Write the header for the summary.
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/SerializedFormWriter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/SerializedFormWriter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * 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 @@
 
 package com.sun.tools.doclets.internal.toolkit;
 
+import java.io.*;
+
 import com.sun.javadoc.*;
-import java.io.*;
 
 /**
  * The interface for writing serialized form output.
@@ -147,22 +148,27 @@
             String fieldDimensions, String fieldName);
 
         /**
-         * Write the footer.
-         *
-         * @param member the member to write the header for.
+         * Write the member footer.
          */
-        public void writeMemberFooter(FieldDoc member);
+        public void writeMemberFooter();
 
         /**
-         * Check to see if member details should be printed. If
+         * Check to see if overview details should be printed. If
          * nocomment option set or if there is no text to be printed
-         * for deprecation info, inline comment, no serial tag or inline tags,
-         * do not print member details.
+         * for deprecation info, inline comment or tags,
+         * do not print overview details.
          *
-         * @param member the member to check details for.
-         * @return true if details need to be printed
+         * @param field the field to check overview details for.
+         * @return true if overview details need to be printed
          */
-        public boolean shouldPrintMemberDetails(FieldDoc member);
+        public boolean shouldPrintOverview(FieldDoc field);
+
+        /**
+         * Write the footer.
+         *
+         * @param heading the heading that was written.
+         */
+        public void writeFooter (String heading);
     }
 
     /**
@@ -193,10 +199,8 @@
 
         /**
          * Write the footer.
-         *
-         * @param member the member to write the header for.
          */
-        public void writeMemberFooter(MethodDoc member);
+        public void writeMemberFooter();
 
         /**
          * Write the deprecated information for this member.
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PackageSummaryBuilder.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PackageSummaryBuilder.java	Fri Apr 10 13:05:12 2009 -0700
@@ -40,6 +40,7 @@
  * Do not use it as an API
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  * @since 1.5
  */
 public class PackageSummaryBuilder extends AbstractBuilder {
@@ -184,7 +185,15 @@
          * Build the summary for the classes in this package.
          */
         public void buildClassSummary() {
-                ClassDoc[] classes =
+            String classTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Class_Summary"),
+                    configuration.getText("doclet.classes"));
+            String[] classTableHeader = new String[] {
+                configuration.getText("doclet.Class"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] classes =
                         packageDoc.isIncluded()
                                 ? packageDoc.ordinaryClasses()
                                 : configuration.classDocCatalog.ordinaryClasses(
@@ -192,7 +201,8 @@
                 if (classes.length > 0) {
                         packageWriter.writeClassesSummary(
                                 classes,
-                                configuration.getText("doclet.Class_Summary"));
+                                configuration.getText("doclet.Class_Summary"),
+                                classTableSummary, classTableHeader);
                 }
         }
 
@@ -200,7 +210,15 @@
          * Build the summary for the interfaces in this package.
          */
         public void buildInterfaceSummary() {
-                ClassDoc[] interfaces =
+            String interfaceTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Interface_Summary"),
+                    configuration.getText("doclet.interfaces"));
+            String[] interfaceTableHeader = new String[] {
+                configuration.getText("doclet.Interface"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] interfaces =
                         packageDoc.isIncluded()
                                 ? packageDoc.interfaces()
                                 : configuration.classDocCatalog.interfaces(
@@ -208,7 +226,8 @@
                 if (interfaces.length > 0) {
                         packageWriter.writeClassesSummary(
                                 interfaces,
-                                configuration.getText("doclet.Interface_Summary"));
+                                configuration.getText("doclet.Interface_Summary"),
+                                interfaceTableSummary, interfaceTableHeader);
                 }
         }
 
@@ -216,7 +235,15 @@
          * Build the summary for the enums in this package.
          */
         public void buildAnnotationTypeSummary() {
-                ClassDoc[] annotationTypes =
+            String annotationtypeTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Annotation_Types_Summary"),
+                    configuration.getText("doclet.annotationtypes"));
+            String[] annotationtypeTableHeader = new String[] {
+                configuration.getText("doclet.AnnotationType"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] annotationTypes =
                         packageDoc.isIncluded()
                                 ? packageDoc.annotationTypes()
                                 : configuration.classDocCatalog.annotationTypes(
@@ -224,7 +251,8 @@
                 if (annotationTypes.length > 0) {
                         packageWriter.writeClassesSummary(
                                 annotationTypes,
-                                configuration.getText("doclet.Annotation_Types_Summary"));
+                                configuration.getText("doclet.Annotation_Types_Summary"),
+                                annotationtypeTableSummary, annotationtypeTableHeader);
                 }
         }
 
@@ -232,7 +260,15 @@
          * Build the summary for the enums in this package.
          */
         public void buildEnumSummary() {
-                ClassDoc[] enums =
+            String enumTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Enum_Summary"),
+                    configuration.getText("doclet.enums"));
+            String[] enumTableHeader = new String[] {
+                configuration.getText("doclet.Enum"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] enums =
                         packageDoc.isIncluded()
                                 ? packageDoc.enums()
                                 : configuration.classDocCatalog.enums(
@@ -240,7 +276,8 @@
                 if (enums.length > 0) {
                         packageWriter.writeClassesSummary(
                                 enums,
-                                configuration.getText("doclet.Enum_Summary"));
+                                configuration.getText("doclet.Enum_Summary"),
+                                enumTableSummary, enumTableHeader);
                 }
         }
 
@@ -248,7 +285,15 @@
          * Build the summary for the exceptions in this package.
          */
         public void buildExceptionSummary() {
-                ClassDoc[] exceptions =
+            String exceptionTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Exception_Summary"),
+                    configuration.getText("doclet.exceptions"));
+            String[] exceptionTableHeader = new String[] {
+                configuration.getText("doclet.Exception"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] exceptions =
                         packageDoc.isIncluded()
                                 ? packageDoc.exceptions()
                                 : configuration.classDocCatalog.exceptions(
@@ -256,7 +301,8 @@
                 if (exceptions.length > 0) {
                         packageWriter.writeClassesSummary(
                                 exceptions,
-                                configuration.getText("doclet.Exception_Summary"));
+                                configuration.getText("doclet.Exception_Summary"),
+                                exceptionTableSummary, exceptionTableHeader);
                 }
         }
 
@@ -264,7 +310,15 @@
          * Build the summary for the errors in this package.
          */
         public void buildErrorSummary() {
-                ClassDoc[] errors =
+            String errorTableSummary =
+                    configuration.getText("doclet.Member_Table_Summary",
+                    configuration.getText("doclet.Error_Summary"),
+                    configuration.getText("doclet.errors"));
+            String[] errorTableHeader = new String[] {
+                configuration.getText("doclet.Error"),
+                configuration.getText("doclet.Description")
+            };
+            ClassDoc[] errors =
                         packageDoc.isIncluded()
                                 ? packageDoc.errors()
                                 : configuration.classDocCatalog.errors(
@@ -272,7 +326,8 @@
                 if (errors.length > 0) {
                         packageWriter.writeClassesSummary(
                                 errors,
-                                configuration.getText("doclet.Error_Summary"));
+                                configuration.getText("doclet.Error_Summary"),
+                                errorTableSummary, errorTableHeader);
                 }
         }
 
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,13 +25,14 @@
 
 package com.sun.tools.doclets.internal.toolkit.builders;
 
-import com.sun.tools.doclets.internal.toolkit.util.*;
-import com.sun.tools.doclets.internal.toolkit.*;
-import com.sun.javadoc.*;
 import java.io.*;
 import java.lang.reflect.*;
 import java.util.*;
 
+import com.sun.javadoc.*;
+import com.sun.tools.doclets.internal.toolkit.util.*;
+import com.sun.tools.doclets.internal.toolkit.*;
+
 /**
  * Builds the serialized form.
  *
@@ -40,6 +41,7 @@
  * Do not use it as an API
  *
  * @author Jamie Ho
+ * @author Bhavesh Patel (Modified)
  * @since 1.5
  */
 public class SerializedFormBuilder extends AbstractBuilder {
@@ -379,7 +381,7 @@
      * Build the method footer.
      */
     public void buildMethodFooter() {
-        methodWriter.writeMemberFooter((MethodDoc) currentMember);
+        methodWriter.writeMemberFooter();
     }
 
     /**
@@ -405,15 +407,18 @@
                 Util.asList(classDoc.serializableFields()).get(0);
             // Check to see if there are inline comments, tags or deprecation
             // information to be printed.
-            if (fieldWriter.shouldPrintMemberDetails(serialPersistentField)) {
+            if (fieldWriter.shouldPrintOverview(serialPersistentField)) {
                 fieldWriter.writeHeader(
-                    configuration.getText("doclet.Serialized_Form_class"));
+                        configuration.getText("doclet.Serialized_Form_class"));
                 fieldWriter.writeMemberDeprecatedInfo(serialPersistentField);
                 if (!configuration.nocomment) {
                     fieldWriter.writeMemberDescription(serialPersistentField);
                     fieldWriter.writeMemberTags(serialPersistentField);
                 }
-                fieldWriter.writeMemberFooter(serialPersistentField);
+                // Footer required to close the definition list tag
+                // for serialization overview.
+                fieldWriter.writeFooter(
+                        configuration.getText("doclet.Serialized_Form_class"));
             }
         }
     }
@@ -476,11 +481,11 @@
     }
 
     /**
-     * Build the field footer.
+     * Build the field sub footer.
      */
-    public void buildFieldFooter() {
+    public void buildFieldSubFooter() {
         if (! currentClass.definesSerializableFields()) {
-            fieldWriter.writeMemberFooter((FieldDoc) currentMember);
+            fieldWriter.writeMemberFooter();
         }
     }
 
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclet.xml	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclet.xml	Fri Apr 10 13:05:12 2009 -0700
@@ -1,205 +1,205 @@
-<?xml version='1.0' encoding='utf-8'?>
-
-<!--
- Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
- DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-
- This code is free software; you can redistribute it and/or modify it
- under the terms of the GNU General Public License version 2 only, as
- published by the Free Software Foundation.  Sun designates this
- particular file as subject to the "Classpath" exception as provided
- by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- CA 95054 USA or visit www.sun.com if you need additional information or
- have any questions.
--->
-
-
-<Doclet>
-
-    <PackageDoc>
-        <PackageHeader/>
-        <Summary>
-            <SummaryHeader/>
-            <InterfaceSummary/>
-            <ClassSummary/>
-            <EnumSummary/>
-            <ExceptionSummary/>
-            <ErrorSummary/>
-            <AnnotationTypeSummary/>
-            <SummaryFooter/>
-        </Summary>
-        <PackageDescription/>
-        <PackageTags/>
-        <PackageFooter/>
-    </PackageDoc>
-    
-    <AnnotationTypeDoc>
-        <AnnotationTypeHeader/>
-        <DeprecationInfo/>
-        <AnnotationTypeSignature/>
-        <AnnotationTypeDescription/>
-        <AnnotationTypeTagInfo/>
-        <MemberSummary>
-        	<AnnotationTypeRequiredMemberSummary/>
-            <AnnotationTypeOptionalMemberSummary/>
-        </MemberSummary>
-        <AnnotationTypeRequiredMemberDetails>
-            <Header/>
-            <AnnotationTypeRequiredMember>
-                <MemberHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <MemberComments/>
-                <TagInfo/>
-                <MemberFooter/>
-            </AnnotationTypeRequiredMember>
-        </AnnotationTypeRequiredMemberDetails>
-        <AnnotationTypeOptionalMemberDetails>
-            <AnnotationTypeOptionalMember>
-                <MemberHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <MemberComments/>
-                <TagInfo/>
-                <DefaultValueInfo/>
-                <MemberFooter/>
-            </AnnotationTypeOptionalMember>
-            <Footer/>
-        </AnnotationTypeOptionalMemberDetails>        
-        <AnnotationTypeFooter/>
-    </AnnotationTypeDoc>
-    
-    <ClassDoc>
-        <ClassHeader/>
-        <ClassTree/>
-        <TypeParamInfo/>
-        <SuperInterfacesInfo/>
-        <ImplementedInterfacesInfo/>        
-        <SubClassInfo/>
-        <SubInterfacesInfo/>
-        <InterfaceUsageInfo/>
-        <NestedClassInfo/>
-        <DeprecationInfo/>
-        <ClassSignature/>
-        <ClassDescription/>
-        <ClassTagInfo/>
-        <MemberSummary>
-            <NestedClassesSummary/>
-            <NestedClassesInheritedSummary/>
-            <EnumConstantsSummary/>
-            <FieldsSummary/>
-            <FieldsInheritedSummary/>  
-            <ConstructorsSummary/>
-            <MethodsSummary/>
-            <MethodsInheritedSummary/>
-        </MemberSummary>
-        <EnumConstantsDetails>
-            <Header/>
-            <EnumConstant>
-                <EnumConstantHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <EnumConstantComments/>
-                <TagInfo/>
-                <EnumConstantFooter/>
-            </EnumConstant>
-            <Footer/>
-        </EnumConstantsDetails>
-        <FieldDetails>
-            <Header/>
-            <FieldDoc>
-                <FieldHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <FieldComments/>
-                <TagInfo/>
-                <FieldFooter/>
-            </FieldDoc>
-            <Footer/>
-        </FieldDetails>
-        <ConstructorDetails>
-            <Header/>
-            <ConstructorDoc>
-                <ConstructorHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <ConstructorComments/>
-                <TagInfo/>
-                <ConstructorFooter/>
-            </ConstructorDoc>
-            <Footer/>
-        </ConstructorDetails>
-        <MethodDetails>
-            <Header/>
-            <MethodDoc>
-                <MethodHeader/>
-                <Signature/>
-                <DeprecationInfo/>
-                <MethodComments/>
-                <TagInfo/>
-                <MethodFooter/>
-            </MethodDoc>
-            <Footer/>
-        </MethodDetails>
-        <ClassFooter/>
-    </ClassDoc>
-    
-    <ConstantSummary>
-        <Header/>
-        <Contents/>
-        <ConstantSummaries>
-            <PackageConstantSummary>
-                <PackageHeader/>
-                <ClassConstantSummary>
-                    <ClassHeader/>
-                    <ConstantMembers/>
-                    <ClassFooter/>
-                </ClassConstantSummary>     
-            </PackageConstantSummary>
-        </ConstantSummaries>    
-        <Footer/>
-    </ConstantSummary>
-    
-    <SerializedForm>
-        <Header/>
-        <SerializedFormSummaries>
-            <PackageSerializedForm>
-                <PackageHeader/>
-                <ClassSerializedForm>
-                    <ClassHeader/>
-                    <SerialUIDInfo/>
-                    <MethodHeader/>
-                    <SerializableMethods>
-                        <MethodSubHeader/>
-                        <DeprecatedMethodInfo/>
-                        <MethodInfo>
-                            <MethodDescription/>
-                            <MethodTags/>
-                        </MethodInfo>
-                        <MethodFooter/>
-                    </SerializableMethods>
-                    <FieldHeader/>
-                    <SerializableFields>
-                        <FieldSubHeader/>
-                        <FieldDeprecationInfo/>
-                        <FieldInfo/>
-                        <FieldFooter/>
-                    </SerializableFields>                  
-                </ClassSerializedForm>
-            </PackageSerializedForm>
-        </SerializedFormSummaries>
-        <Footer/>
-    </SerializedForm>
-</Doclet>
+<?xml version='1.0' encoding='utf-8'?>
+
+<!--
+ Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
+ DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+ This code is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License version 2 only, as
+ published by the Free Software Foundation.  Sun designates this
+ particular file as subject to the "Classpath" exception as provided
+ by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ CA 95054 USA or visit www.sun.com if you need additional information or
+ have any questions.
+-->
+
+
+<Doclet>
+
+    <PackageDoc>
+        <PackageHeader/>
+        <Summary>
+            <SummaryHeader/>
+            <InterfaceSummary/>
+            <ClassSummary/>
+            <EnumSummary/>
+            <ExceptionSummary/>
+            <ErrorSummary/>
+            <AnnotationTypeSummary/>
+            <SummaryFooter/>
+        </Summary>
+        <PackageDescription/>
+        <PackageTags/>
+        <PackageFooter/>
+    </PackageDoc>
+    
+    <AnnotationTypeDoc>
+        <AnnotationTypeHeader/>
+        <DeprecationInfo/>
+        <AnnotationTypeSignature/>
+        <AnnotationTypeDescription/>
+        <AnnotationTypeTagInfo/>
+        <MemberSummary>
+        	<AnnotationTypeRequiredMemberSummary/>
+            <AnnotationTypeOptionalMemberSummary/>
+        </MemberSummary>
+        <AnnotationTypeRequiredMemberDetails>
+            <Header/>
+            <AnnotationTypeRequiredMember>
+                <MemberHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <MemberComments/>
+                <TagInfo/>
+                <MemberFooter/>
+            </AnnotationTypeRequiredMember>
+        </AnnotationTypeRequiredMemberDetails>
+        <AnnotationTypeOptionalMemberDetails>
+            <AnnotationTypeOptionalMember>
+                <MemberHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <MemberComments/>
+                <TagInfo/>
+                <DefaultValueInfo/>
+                <MemberFooter/>
+            </AnnotationTypeOptionalMember>
+            <Footer/>
+        </AnnotationTypeOptionalMemberDetails>        
+        <AnnotationTypeFooter/>
+    </AnnotationTypeDoc>
+    
+    <ClassDoc>
+        <ClassHeader/>
+        <ClassTree/>
+        <TypeParamInfo/>
+        <SuperInterfacesInfo/>
+        <ImplementedInterfacesInfo/>        
+        <SubClassInfo/>
+        <SubInterfacesInfo/>
+        <InterfaceUsageInfo/>
+        <NestedClassInfo/>
+        <DeprecationInfo/>
+        <ClassSignature/>
+        <ClassDescription/>
+        <ClassTagInfo/>
+        <MemberSummary>
+            <NestedClassesSummary/>
+            <NestedClassesInheritedSummary/>
+            <EnumConstantsSummary/>
+            <FieldsSummary/>
+            <FieldsInheritedSummary/>  
+            <ConstructorsSummary/>
+            <MethodsSummary/>
+            <MethodsInheritedSummary/>
+        </MemberSummary>
+        <EnumConstantsDetails>
+            <Header/>
+            <EnumConstant>
+                <EnumConstantHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <EnumConstantComments/>
+                <TagInfo/>
+                <EnumConstantFooter/>
+            </EnumConstant>
+            <Footer/>
+        </EnumConstantsDetails>
+        <FieldDetails>
+            <Header/>
+            <FieldDoc>
+                <FieldHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <FieldComments/>
+                <TagInfo/>
+                <FieldFooter/>
+            </FieldDoc>
+            <Footer/>
+        </FieldDetails>
+        <ConstructorDetails>
+            <Header/>
+            <ConstructorDoc>
+                <ConstructorHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <ConstructorComments/>
+                <TagInfo/>
+                <ConstructorFooter/>
+            </ConstructorDoc>
+            <Footer/>
+        </ConstructorDetails>
+        <MethodDetails>
+            <Header/>
+            <MethodDoc>
+                <MethodHeader/>
+                <Signature/>
+                <DeprecationInfo/>
+                <MethodComments/>
+                <TagInfo/>
+                <MethodFooter/>
+            </MethodDoc>
+            <Footer/>
+        </MethodDetails>
+        <ClassFooter/>
+    </ClassDoc>
+    
+    <ConstantSummary>
+        <Header/>
+        <Contents/>
+        <ConstantSummaries>
+            <PackageConstantSummary>
+                <PackageHeader/>
+                <ClassConstantSummary>
+                    <ClassHeader/>
+                    <ConstantMembers/>
+                    <ClassFooter/>
+                </ClassConstantSummary>     
+            </PackageConstantSummary>
+        </ConstantSummaries>    
+        <Footer/>
+    </ConstantSummary>
+    
+    <SerializedForm>
+        <Header/>
+        <SerializedFormSummaries>
+            <PackageSerializedForm>
+                <PackageHeader/>
+                <ClassSerializedForm>
+                    <ClassHeader/>
+                    <SerialUIDInfo/>
+                    <MethodHeader/>
+                    <SerializableMethods>
+                        <MethodSubHeader/>
+                        <DeprecatedMethodInfo/>
+                        <MethodInfo>
+                            <MethodDescription/>
+                            <MethodTags/>
+                        </MethodInfo>
+                        <MethodFooter/>
+                    </SerializableMethods>
+                    <FieldHeader/>
+                    <SerializableFields>
+                        <FieldSubHeader/>
+                        <FieldDeprecationInfo/>
+                        <FieldInfo/>
+                        <FieldSubFooter/>
+                    </SerializableFields>
+                </ClassSerializedForm>
+            </PackageSerializedForm>
+        </SerializedFormSummaries>
+        <Footer/>
+    </SerializedForm>
+</Doclet>
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -82,6 +82,7 @@
 doclet.Errors=Errors
 doclet.Classes=Classes
 doclet.Packages=Packages
+doclet.packages=packages
 doclet.All_Classes=All Classes
 doclet.All_Superinterfaces=All Superinterfaces:
 doclet.All_Implemented_Interfaces=All Implemented Interfaces:
@@ -92,14 +93,20 @@
 doclet.Class=Class
 doclet.AnnotationType=Annotation Type
 doclet.annotationtype=annotation type
+doclet.annotationtypes=annotation types
 doclet.Enum=Enum
 doclet.enum=enum
+doclet.enums=enums
 doclet.interface=interface
+doclet.interfaces=interfaces
 doclet.class=class
+doclet.classes=classes
 doclet.Error=Error
 doclet.error=error
+doclet.errors=errors
 doclet.Exception=Exception
 doclet.exception=exception
+doclet.exceptions=exceptions
 doclet.extended_by=extended by
 doclet.extends=extends
 doclet.Package_private=(package private)
@@ -125,6 +132,32 @@
 doclet.value_tag_invalid_constant=@value tag (which references {0}) can only be used in constants.
 doclet.dest_dir_create=Creating destination directory: "{0}"
 doclet.in={0} in {1}
+doclet.Use_Table_Summary=Use table, listing {0}, and an explanation
+doclet.Constants_Table_Summary={0} table, listing constant fields, and values
+doclet.Member_Table_Summary={0} table, listing {1}, and an explanation
+doclet.fields=fields
+doclet.constructors=constructors
+doclet.methods=methods
+doclet.annotation_type_optional_members=optional elements
+doclet.annotation_type_required_members=required elements
+doclet.enum_constants=enum constants
+doclet.nested_classes=nested classes
+doclet.subclasses=subclasses
+doclet.subinterfaces=subinterfaces
+doclet.Modifier=Modifier
+doclet.Type=Type
+doclet.Field=Field
+doclet.Constructor=Constructor
+doclet.Method=Method
+doclet.Annotation_Type_Optional_Member=Optional Element
+doclet.Annotation_Type_Required_Member=Required Element
+doclet.Annotation_Type_Member=Annotation Type Element
+doclet.Enum_Constant=Enum Constant
+doclet.Class=Class
+doclet.Description=Description
+doclet.ConstantField=Constant Field
+doclet.Value=Value
+doclet.0_and_1={0} and {1}
 
 #Documentation for Enums
 doclet.enum_values_doc=\n\
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/DocletAbortException.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/DocletAbortException.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/SourceToHTMLConverter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/SourceToHTMLConverter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/api/Messages.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/Messages.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Printer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,324 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.tools.javac.code;
+
+import java.util.Locale;
+
+import com.sun.tools.javac.api.Messages;
+import com.sun.tools.javac.code.Type.*;
+import com.sun.tools.javac.code.Symbol.*;
+import com.sun.tools.javac.util.List;
+import com.sun.tools.javac.util.ListBuffer;
+
+import static com.sun.tools.javac.code.TypeTags.*;
+import static com.sun.tools.javac.code.BoundKind.*;
+import static com.sun.tools.javac.code.Flags.*;
+
+/**
+ * A combined type/symbol visitor for generating non-trivial localized string
+ * representation of types and symbols.
+ */
+public abstract class Printer implements Type.Visitor<String, Locale>, Symbol.Visitor<String, Locale> {
+
+    /**
+     * This method should be overriden in order to provide proper i18n support.
+     *
+     * @param locale the locale in which the string is to be rendered
+     * @param key the key corresponding to the message to be displayed
+     * @param args a list of optional arguments
+     * @return localized string representation
+     */
+    protected abstract String localize(Locale locale, String key, Object... args);
+
+    /**
+     * Create a printer with default i18n support provided my Messages.
+     * @param messages Messages class to be used for i18n
+     * @return printer visitor instance
+     */
+    public static Printer createStandardPrinter(final Messages messages) {
+        return new Printer() {
+            @Override
+            protected String localize(Locale locale, String key, Object... args) {
+                return messages.getLocalizedString(locale, key, args);
+        }};
+    }
+
+    /**
+     * Get a localized string representation for all the types in the input list.
+     *
+     * @param ts types to be displayed
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    public String visitTypes(List<Type> ts, Locale locale) {
+        ListBuffer<String> sbuf = ListBuffer.lb();
+        for (Type t : ts) {
+            sbuf.append(visit(t, locale));
+        }
+        return sbuf.toList().toString();
+    }
+
+    /**
+     * * Get a localized string represenation for all the symbols in the input list.
+     *
+     * @param ts symbols to be displayed
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    public String visitSymbols(List<Symbol> ts, Locale locale) {
+        ListBuffer<String> sbuf = ListBuffer.lb();
+        for (Symbol t : ts) {
+            sbuf.append(visit(t, locale));
+        }
+        return sbuf.toList().toString();
+    }
+
+    /**
+     * Get a localized string represenation for a given type.
+     *
+     * @param ts type to be displayed
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    public String visit(Type t, Locale locale) {
+        return t.accept(this, locale);
+    }
+
+    /**
+     * Get a localized string represenation for a given symbol.
+     *
+     * @param ts symbol to be displayed
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    public String visit(Symbol s, Locale locale) {
+        return s.accept(this, locale);
+    }
+
+    @Override
+    public String visitCapturedType(CapturedType t, Locale locale) {
+        return localize(locale, "compiler.misc.type.captureof",
+            (t.hashCode() & 0xFFFFFFFFL) % Type.CapturedType.PRIME,
+            visit(t.wildcard, locale));
+    }
+
+    @Override
+    public String visitForAll(ForAll t, Locale locale) {
+        return "<" + visitTypes(t.tvars, locale) + ">" + visit(t.qtype, locale);
+    }
+
+    @Override
+    public String visitUndetVar(UndetVar t, Locale locale) {
+        if (t.inst != null) {
+            return visit(t.inst, locale);
+        } else {
+            return visit(t.qtype, locale) + "?";
+        }
+    }
+
+    @Override
+    public String visitArrayType(ArrayType t, Locale locale) {
+        return visit(t.elemtype, locale) + "[]";
+    }
+
+    @Override
+    public String visitClassType(ClassType t, Locale locale) {
+        StringBuffer buf = new StringBuffer();
+        if (t.getEnclosingType().tag == CLASS && t.tsym.owner.kind == Kinds.TYP) {
+            buf.append(visit(t.getEnclosingType(), locale));
+            buf.append(".");
+            buf.append(className(t, false, locale));
+        } else {
+            buf.append(className(t, true, locale));
+        }
+        if (t.getTypeArguments().nonEmpty()) {
+            buf.append('<');
+            buf.append(visitTypes(t.getTypeArguments(), locale));
+            buf.append(">");
+        }
+        return buf.toString();
+    }
+
+    @Override
+    public String visitMethodType(MethodType t, Locale locale) {
+        return "(" + printMethodArgs(t.argtypes, false, locale) + ")" + visit(t.restype, locale);
+    }
+
+    @Override
+    public String visitPackageType(PackageType t, Locale locale) {
+        return t.tsym.getQualifiedName().toString();
+    }
+
+    @Override
+    public String visitWildcardType(WildcardType t, Locale locale) {
+        StringBuffer s = new StringBuffer();
+        s.append(t.kind);
+        if (t.kind != UNBOUND) {
+            s.append(visit(t.type, locale));
+        }
+        return s.toString();
+    }
+
+    @Override
+    public String visitErrorType(ErrorType t, Locale locale) {
+        return visitType(t, locale);
+    }
+
+    @Override
+    public String visitTypeVar(TypeVar t, Locale locale) {
+        return visitType(t, locale);
+    }
+
+    public String visitType(Type t, Locale locale) {
+        String s = (t.tsym == null || t.tsym.name == null)
+                ? localize(locale, "compiler.misc.type.none")
+                : t.tsym.name.toString();
+        return s;
+    }
+
+    /**
+     * Converts a class name into a (possibly localized) string. Anonymous
+     * inner classes gets converted into a localized string.
+     *
+     * @param t the type of the class whose name is to be rendered
+     * @param longform if set, the class' fullname is displayed - if unset the
+     * short name is chosen (w/o package)
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    protected String className(ClassType t, boolean longform, Locale locale) {
+        Symbol sym = t.tsym;
+        if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
+            StringBuffer s = new StringBuffer(visit(t.supertype_field, locale));
+            for (List<Type> is = t.interfaces_field; is.nonEmpty(); is = is.tail) {
+                s.append("&");
+                s.append(visit(is.head, locale));
+            }
+            return s.toString();
+        } else if (sym.name.length() == 0) {
+            String s;
+            ClassType norm = (ClassType) t.tsym.type;
+            if (norm == null) {
+                s = localize(locale, "compiler.misc.anonymous.class", (Object) null);
+            } else if (norm.interfaces_field.nonEmpty()) {
+                s = localize(locale, "compiler.misc.anonymous.class",
+                        visit(norm.interfaces_field.head, locale));
+            } else {
+                s = localize(locale, "compiler.misc.anonymous.class",
+                        visit(norm.supertype_field, locale));
+            }
+            return s;
+        } else if (longform) {
+            return sym.getQualifiedName().toString();
+        } else {
+            return sym.name.toString();
+        }
+    }
+
+    /**
+     * Converts a set of method argument types into their corresponding
+     * localized string representation.
+     *
+     * @param args arguments to be rendered
+     * @param varArgs if true, the last method argument is regarded as a vararg
+     * @param locale the locale in which the string is to be rendered
+     * @return localized string representation
+     */
+    protected String printMethodArgs(List<Type> args, boolean varArgs, Locale locale) {
+        if (!varArgs) {
+            return visitTypes(args, locale);
+        } else {
+            StringBuffer buf = new StringBuffer();
+            while (args.tail.nonEmpty()) {
+                buf.append(visit(args.head, locale));
+                args = args.tail;
+                buf.append(',');
+            }
+            if (args.head.tag == ARRAY) {
+                buf.append(visit(((ArrayType) args.head).elemtype, locale));
+                buf.append("...");
+            } else {
+                buf.append(visit(args.head, locale));
+            }
+            return buf.toString();
+        }
+    }
+
+    @Override
+    public String visitClassSymbol(ClassSymbol sym, Locale locale) {
+        return sym.name.isEmpty()
+                ? localize(locale, "compiler.misc.anonymous.class", sym.flatname)
+                : sym.fullname.toString();
+    }
+
+    @Override
+    public String visitMethodSymbol(MethodSymbol s, Locale locale) {
+        if ((s.flags() & BLOCK) != 0) {
+            return s.owner.name.toString();
+        } else {
+            String ms = (s.name == s.name.table.names.init)
+                    ? s.owner.name.toString()
+                    : s.name.toString();
+            if (s.type != null) {
+                if (s.type.tag == FORALL) {
+                    ms = "<" + visitTypes(s.type.getTypeArguments(), locale) + ">" + ms;
+                }
+                ms += "(" + printMethodArgs(
+                        s.type.getParameterTypes(),
+                        (s.flags() & VARARGS) != 0,
+                        locale) + ")";
+            }
+            return ms;
+        }
+    }
+
+    @Override
+    public String visitOperatorSymbol(OperatorSymbol s, Locale locale) {
+        return visitMethodSymbol(s, locale);
+    }
+
+    @Override
+    public String visitPackageSymbol(PackageSymbol s, Locale locale) {
+        return s.isUnnamed()
+                ? localize(locale, "compiler.misc.unnamed.package")
+                : s.fullname.toString();
+    }
+
+    @Override
+    public String visitTypeSymbol(TypeSymbol s, Locale locale) {
+        return visitSymbol(s, locale);
+    }
+
+    @Override
+    public String visitVarSymbol(VarSymbol s, Locale locale) {
+        return visitSymbol(s, locale);
+    }
+
+    @Override
+    public String visitSymbol(Symbol s, Locale locale) {
+        return s.name.toString();
+    }
+}
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,8 @@
 
 import java.util.*;
 
+import com.sun.tools.javac.api.Messages;
+
 import com.sun.tools.javac.util.*;
 import com.sun.tools.javac.util.List;
 
@@ -1010,8 +1012,8 @@
                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
-                                if (upcast ? giveWarning(a, highSub) || giveWarning(a, lowSub)
-                                           : giveWarning(highSub, a) || giveWarning(lowSub, a))
+                                if (upcast ? giveWarning(a, b) :
+                                    giveWarning(b, a))
                                     warnStack.head.warnUnchecked();
                                 return true;
                             }
@@ -2019,7 +2021,7 @@
                 return t;
             else
                 return visit(t);
-        }
+            }
 
         List<Type> subst(List<Type> ts) {
             if (from.tail == null)
@@ -2279,225 +2281,21 @@
     }
     // </editor-fold>
 
-    // <editor-fold defaultstate="collapsed" desc="printType">
     /**
-     * Visitor for generating a string representation of a given type
+     * Helper method for generating a string representation of a given type
      * accordingly to a given locale
      */
     public String toString(Type t, Locale locale) {
-        return typePrinter.visit(t, locale);
+        return Printer.createStandardPrinter(messages).visit(t, locale);
     }
-    // where
-    private TypePrinter typePrinter = new TypePrinter();
-
-    public class TypePrinter extends DefaultTypeVisitor<String, Locale> {
-
-        public String visit(List<Type> ts, Locale locale) {
-            ListBuffer<String> sbuf = lb();
-            for (Type t : ts) {
-                sbuf.append(visit(t, locale));
-            }
-            return sbuf.toList().toString();
-        }
-
-        @Override
-        public String visitCapturedType(CapturedType t, Locale locale) {
-            return messages.getLocalizedString("compiler.misc.type.captureof",
-                        (t.hashCode() & 0xFFFFFFFFL) % Type.CapturedType.PRIME,
-                        visit(t.wildcard, locale));
-        }
-
-        @Override
-        public String visitForAll(ForAll t, Locale locale) {
-            return "<" + visit(t.tvars, locale) + ">" + visit(t.qtype, locale);
-        }
-
-        @Override
-        public String visitUndetVar(UndetVar t, Locale locale) {
-            if (t.inst != null) {
-                return visit(t.inst, locale);
-            } else {
-                return visit(t.qtype, locale) + "?";
-            }
-        }
-
-        @Override
-        public String visitArrayType(ArrayType t, Locale locale) {
-            return visit(t.elemtype, locale) + "[]";
-        }
-
-        @Override
-        public String visitClassType(ClassType t, Locale locale) {
-            StringBuffer buf = new StringBuffer();
-            if (t.getEnclosingType().tag == CLASS && t.tsym.owner.kind == Kinds.TYP) {
-                buf.append(visit(t.getEnclosingType(), locale));
-                buf.append(".");
-                buf.append(className(t, false, locale));
-            } else {
-                buf.append(className(t, true, locale));
-            }
-            if (t.getTypeArguments().nonEmpty()) {
-                buf.append('<');
-                buf.append(visit(t.getTypeArguments(), locale));
-                buf.append(">");
-            }
-            return buf.toString();
-        }
-
-        @Override
-        public String visitMethodType(MethodType t, Locale locale) {
-            return "(" + printMethodArgs(t.argtypes, false, locale) + ")" + visit(t.restype, locale);
-        }
-
-        @Override
-        public String visitPackageType(PackageType t, Locale locale) {
-            return t.tsym.getQualifiedName().toString();
-        }
 
-        @Override
-        public String visitWildcardType(WildcardType t, Locale locale) {
-            StringBuffer s = new StringBuffer();
-            s.append(t.kind);
-            if (t.kind != UNBOUND) {
-                s.append(visit(t.type, locale));
-            }
-            return s.toString();
-        }
-
-
-        public String visitType(Type t, Locale locale) {
-            String s = (t.tsym == null || t.tsym.name == null)
-                    ? messages.getLocalizedString("compiler.misc.type.none")
-                    : t.tsym.name.toString();
-            return s;
-        }
-
-        protected String className(ClassType t, boolean longform, Locale locale) {
-            Symbol sym = t.tsym;
-            if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
-                StringBuffer s = new StringBuffer(visit(supertype(t), locale));
-                for (List<Type> is = interfaces(t); is.nonEmpty(); is = is.tail) {
-                    s.append("&");
-                    s.append(visit(is.head, locale));
-                }
-                return s.toString();
-            } else if (sym.name.length() == 0) {
-                String s;
-                ClassType norm = (ClassType) t.tsym.type;
-                if (norm == null) {
-                    s = getLocalizedString(locale, "compiler.misc.anonymous.class", (Object) null);
-                } else if (interfaces(norm).nonEmpty()) {
-                    s = getLocalizedString(locale, "compiler.misc.anonymous.class",
-                            visit(interfaces(norm).head, locale));
-                } else {
-                    s = getLocalizedString(locale, "compiler.misc.anonymous.class",
-                            visit(supertype(norm), locale));
-                }
-                return s;
-            } else if (longform) {
-                return sym.getQualifiedName().toString();
-            } else {
-                return sym.name.toString();
-            }
-        }
-
-        protected String printMethodArgs(List<Type> args, boolean varArgs, Locale locale) {
-            if (!varArgs) {
-                return visit(args, locale);
-            } else {
-                StringBuffer buf = new StringBuffer();
-                while (args.tail.nonEmpty()) {
-                    buf.append(visit(args.head, locale));
-                    args = args.tail;
-                    buf.append(',');
-                }
-                if (args.head.tag == ARRAY) {
-                    buf.append(visit(((ArrayType) args.head).elemtype, locale));
-                    buf.append("...");
-                } else {
-                    buf.append(visit(args.head, locale));
-                }
-                return buf.toString();
-            }
-        }
-
-        protected String getLocalizedString(Locale locale, String key, Object... args) {
-            return messages.getLocalizedString(key, args);
-        }
-    };
-    // </editor-fold>
-
-    // <editor-fold defaultstate="collapsed" desc="printSymbol">
     /**
-     * Visitor for generating a string representation of a given symbol
+     * Helper method for generating a string representation of a given type
      * accordingly to a given locale
      */
     public String toString(Symbol t, Locale locale) {
-        return symbolPrinter.visit(t, locale);
+        return Printer.createStandardPrinter(messages).visit(t, locale);
     }
-    // where
-    private SymbolPrinter symbolPrinter = new SymbolPrinter();
-
-    public class SymbolPrinter extends DefaultSymbolVisitor<String, Locale> {
-
-        @Override
-        public String visitClassSymbol(ClassSymbol sym, Locale locale) {
-            return sym.name.isEmpty()
-                    ? getLocalizedString(locale, "compiler.misc.anonymous.class", sym.flatname)
-                    : sym.fullname.toString();
-        }
-
-        @Override
-        public String visitMethodSymbol(MethodSymbol s, Locale locale) {
-            if ((s.flags() & BLOCK) != 0) {
-                return s.owner.name.toString();
-            } else {
-                String ms = (s.name == names.init)
-                        ? s.owner.name.toString()
-                        : s.name.toString();
-                if (s.type != null) {
-                    if (s.type.tag == FORALL) {
-                        ms = "<" + typePrinter.visit(s.type.getTypeArguments(), locale) + ">" + ms;
-                    }
-                    ms += "(" + typePrinter.printMethodArgs(
-                            s.type.getParameterTypes(),
-                            (s.flags() & VARARGS) != 0,
-                            locale) + ")";
-                }
-                return ms;
-            }
-        }
-
-        @Override
-        public String visitOperatorSymbol(OperatorSymbol s, Locale locale) {
-            return visitMethodSymbol(s, locale);
-        }
-
-        @Override
-        public String visitPackageSymbol(PackageSymbol s, Locale locale) {
-            return s.name.isEmpty()
-                    ? getLocalizedString(locale, "compiler.misc.unnamed.package")
-                    : s.fullname.toString();
-        }
-
-        @Override
-        public String visitSymbol(Symbol s, Locale locale) {
-            return s.name.toString();
-        }
-
-        public String visit(List<Symbol> ts, Locale locale) {
-            ListBuffer<String> sbuf = lb();
-            for (Symbol t : ts) {
-                sbuf.append(visit(t, locale));
-            }
-            return sbuf.toList().toString();
-        }
-
-        protected String getLocalizedString(Locale locale, String key, Object... args) {
-            return messages.getLocalizedString(key, args);
-        }
-    };
-    // </editor-fold>
 
     // <editor-fold defaultstate="collapsed" desc="toString">
     /**
@@ -3128,7 +2926,7 @@
             return t;
     }
     // where
-        private List<Type> freshTypeVariables(List<Type> types) {
+        public List<Type> freshTypeVariables(List<Type> types) {
             ListBuffer<Type> result = lb();
             for (Type t : types) {
                 if (t.tag == WILDCARD) {
@@ -3224,9 +3022,11 @@
     }
 
     private boolean giveWarning(Type from, Type to) {
-        // To and from are (possibly different) parameterizations
-        // of the same class or interface
-        return to.isParameterized() && !containsType(to.allparams(), from.allparams());
+        Type subFrom = asSub(from, to.tsym);
+        return to.isParameterized() &&
+                (!(isUnbounded(to) ||
+                isSubtype(from, to) ||
+                ((subFrom != null) && isSameType(subFrom, to))));
     }
 
     private List<Type> superClosure(Type t, Type s) {
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1545,10 +1545,10 @@
 
 
     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
-        checkNonCyclic1(pos, t, new HashSet<TypeVar>());
+        checkNonCyclic1(pos, t, List.<TypeVar>nil());
     }
 
-    private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
+    private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
         final TypeVar tv;
         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
             return;
@@ -1558,7 +1558,7 @@
             log.error(pos, "cyclic.inheritance", t);
         } else if (t.tag == TYPEVAR) {
             tv = (TypeVar)t;
-            seen.add(tv);
+            seen = seen.prepend(tv);
             for (Type b : types.getBounds(tv))
                 checkNonCyclic1(pos, b, seen);
         }
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java	Fri Apr 10 13:05:12 2009 -0700
@@ -3012,6 +3012,7 @@
                                                   vardefinit).setType(tree.var.type);
             indexDef.sym = tree.var.sym;
             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
+            body.endpos = TreeInfo.endPos(tree.body);
             result = translate(make.
                 ForLoop(List.of(init),
                         cond,
--- a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/main/Main.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/Main.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/main/OptionName.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/OptionName.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/processing/JavacRoundEnvironment.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/processing/JavacRoundEnvironment.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -111,6 +111,7 @@
      */
     public Set<? extends Element> getElementsAnnotatedWith(TypeElement a) {
         Set<Element> result = Collections.emptySet();
+        Types typeUtil = processingEnv.getTypeUtils();
         if (a.getKind() != ElementKind.ANNOTATION_TYPE)
             throw new IllegalArgumentException(NOT_AN_ANNOTATION_TYPE + a);
 
@@ -122,7 +123,7 @@
             throw new AssertionError("Bad implementation type for " + tm);
 
         ElementScanner6<Set<Element>, DeclaredType> scanner =
-            new AnnotationSetScanner(result);
+            new AnnotationSetScanner(result, typeUtil);
 
         for (Element element : rootElements)
             result = scanner.scan(element, annotationTypeElement);
@@ -135,9 +136,11 @@
         ElementScanner6<Set<Element>, DeclaredType> {
         // Insertion-order preserving set
         Set<Element> annotatedElements = new LinkedHashSet<Element>();
+        Types typeUtil;
 
-        AnnotationSetScanner(Set<Element> defaultSet) {
+        AnnotationSetScanner(Set<Element> defaultSet, Types typeUtil) {
             super(defaultSet);
+            this.typeUtil = typeUtil;
         }
 
         @Override
@@ -145,7 +148,7 @@
             java.util.List<? extends AnnotationMirror> annotationMirrors =
                 processingEnv.getElementUtils().getAllAnnotationMirrors(e);
             for (AnnotationMirror annotationMirror : annotationMirrors) {
-                if (annotationMirror.getAnnotationType().equals(p))
+                if (typeUtil.isSameType(annotationMirror.getAnnotationType(), p))
                     annotatedElements.add(e);
             }
             e.accept(this, p);
--- a/langtools/src/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -836,6 +836,9 @@
 compiler.misc.type.captureof=\
     capture#{0} of {1}
 
+compiler.misc.type.captureof.1=\
+    capture#{0}
+
 compiler.misc.type.none=\
     <none>
 
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1999-2006 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,10 @@
 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.MultilineLimit;
 import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
 import com.sun.tools.javac.api.Formattable;
+import com.sun.tools.javac.code.Printer;
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.Type.CapturedType;
 import com.sun.tools.javac.file.JavacFileManager;
 
 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
@@ -60,16 +64,31 @@
      * JavacMessages object used by this formatter for i18n.
      */
     protected JavacMessages messages;
+
+    /**
+     * Configuration object used by this formatter
+     */
     private SimpleConfiguration config;
+
+    /**
+     * Current depth level of the disgnostic being formatted
+     * (!= 0 for subdiagnostics)
+     */
     protected int depth = 0;
 
     /**
+     * Printer instance to be used for formatting types/symbol
+     */
+    protected Printer printer;
+
+    /**
      * Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object.
      * @param messages
      */
     protected AbstractDiagnosticFormatter(JavacMessages messages, SimpleConfiguration config) {
         this.messages = messages;
         this.config = config;
+        this.printer = new FormatterPrinter();
     }
 
     public String formatKind(JCDiagnostic d, Locale l) {
@@ -83,6 +102,14 @@
         }
     }
 
+    @Override
+    public String format(JCDiagnostic d, Locale locale) {
+        printer = new FormatterPrinter();
+        return formatDiagnostic(d, locale);
+    }
+
+    abstract String formatDiagnostic(JCDiagnostic d, Locale locale);
+
     public String formatPosition(JCDiagnostic d, PositionKind pk,Locale l) {
         assert (d.getPosition() != Position.NOPOS);
         return String.valueOf(getPosition(d, pk));
@@ -143,12 +170,21 @@
         else if (arg instanceof Iterable<?>) {
             return formatIterable(d, (Iterable<?>)arg, l);
         }
-        else if (arg instanceof JavaFileObject)
+        else if (arg instanceof Type) {
+            return printer.visit((Type)arg, l);
+        }
+        else if (arg instanceof Symbol) {
+            return printer.visit((Symbol)arg, l);
+        }
+        else if (arg instanceof JavaFileObject) {
             return JavacFileManager.getJavacBaseFileName((JavaFileObject)arg);
-        else if (arg instanceof Formattable)
+        }
+        else if (arg instanceof Formattable) {
             return ((Formattable)arg).toString(l, messages);
-        else
+        }
+        else {
             return String.valueOf(arg);
+        }
     }
 
     /**
@@ -404,4 +440,43 @@
             return caretEnabled;
         }
     }
+
+    /**
+     * An enhanced printer for formatting types/symbols used by
+     * AbstractDiagnosticFormatter. Provides alternate numbering of captured
+     * types (they are numbered starting from 1 on each new diagnostic, instead
+     * of relying on the underlying hashcode() method which generates unstable
+     * output). Also detects cycles in wildcard messages (e.g. if the wildcard
+     * type referred by a given captured type C contains C itself) which might
+     * lead to infinite loops.
+     */
+    protected class FormatterPrinter extends Printer {
+
+        List<Type> allCaptured = List.nil();
+        List<Type> seenCaptured = List.nil();
+
+        @Override
+        protected String localize(Locale locale, String key, Object... args) {
+            return AbstractDiagnosticFormatter.this.localize(locale, key, args);
+        }
+
+        @Override
+        public String visitCapturedType(CapturedType t, Locale locale) {
+            if (seenCaptured.contains(t))
+                return localize(locale, "compiler.misc.type.captureof.1",
+                    allCaptured.indexOf(t) + 1);
+            else {
+                try {
+                    seenCaptured = seenCaptured.prepend(t);
+                    allCaptured = allCaptured.append(t);
+                    return localize(locale, "compiler.misc.type.captureof",
+                        allCaptured.indexOf(t) + 1,
+                        visit(t.wildcard, locale));
+                }
+                finally {
+                    seenCaptured = seenCaptured.tail;
+                }
+            }
+        }
+    }
 }
--- a/langtools/src/share/classes/com/sun/tools/javac/util/BasicDiagnosticFormatter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/BasicDiagnosticFormatter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2005-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -82,7 +82,7 @@
         super(msgs, new BasicConfiguration());
     }
 
-    public String format(JCDiagnostic d, Locale l) {
+    public String formatDiagnostic(JCDiagnostic d, Locale l) {
         if (l == null)
             l = messages.getCurrentLocale();
         String format = selectFormat(d);
--- a/langtools/src/share/classes/com/sun/tools/javac/util/LayoutCharacters.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/LayoutCharacters.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/util/Log.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/Log.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javac/util/RawDiagnosticFormatter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/RawDiagnosticFormatter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -54,7 +54,7 @@
     }
 
     //provide common default formats
-    public String format(JCDiagnostic d, Locale l) {
+    public String formatDiagnostic(JCDiagnostic d, Locale l) {
         try {
             StringBuffer buf = new StringBuffer();
             if (d.getPosition() != Position.NOPOS) {
@@ -82,17 +82,11 @@
     public String formatMessage(JCDiagnostic d, Locale l) {
         StringBuilder buf = new StringBuilder();
         Collection<String> args = formatArguments(d, l);
-        buf.append(d.getCode());
-        String sep = ": ";
-        for (Object o : args) {
-            buf.append(sep);
-            buf.append(o);
-            sep = ", ";
-        }
+        buf.append(localize(null, d.getCode(), args.toArray()));
         if (d.isMultiline() && getConfiguration().getVisible().contains(DiagnosticPart.SUBDIAGNOSTICS)) {
             List<String> subDiags = formatSubdiagnostics(d, null);
             if (subDiags.nonEmpty()) {
-                sep = "";
+                String sep = "";
                 buf.append(",{");
                 for (String sub : formatSubdiagnostics(d, null)) {
                     buf.append(sep);
@@ -117,4 +111,17 @@
         else
             return s;
     }
+
+    @Override
+    protected String localize(Locale l, String key, Object... args) {
+        StringBuilder buf = new StringBuilder();
+        buf.append(key);
+        String sep = ": ";
+        for (Object o : args) {
+            buf.append(sep);
+            buf.append(o);
+            sep = ", ";
+        }
+        return buf.toString();
+    }
 }
--- a/langtools/src/share/classes/com/sun/tools/javadoc/ClassDocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/ClassDocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/Comment.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/Comment.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2000-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/DocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/DocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/DocletInvoker.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/DocletInvoker.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/ExecutableMemberDocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/ExecutableMemberDocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/FieldDocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/FieldDocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/Messager.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/Messager.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2004 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/PackageDocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/PackageDocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/RootDocImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/RootDocImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/SourcePositionImpl.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/SourcePositionImpl.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javadoc/TypeMaker.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/TypeMaker.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javah/Gen.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javah/Gen.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/com/sun/tools/javap/InternalError.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/com/sun/tools/javap/InternalError.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2007-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/javax/annotation/processing/Filer.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/javax/annotation/processing/Filer.java	Fri Apr 10 13:05:12 2009 -0700
@@ -35,9 +35,11 @@
  * processor.  Files created in this way will be known to the
  * annotation processing tool implementing this interface, better
  * enabling the tool to manage them.  Source and class files so
- * created will be considered for processing by the tool after the
- * {@code close} method has been called on the {@code Writer} or
- * {@code OutputStream} used to write the contents of the file.
+ * created will be {@linkplain RoundEnvironment#getRootElements
+ * considered for processing} by the tool in a subsequent {@linkplain
+ * RoundEnvironment round of processing} after the {@code close}
+ * method has been called on the {@code Writer} or {@code
+ * OutputStream} used to write the contents of the file.
  *
  * Three kinds of files are distinguished: source files, class files,
  * and auxiliary resource files.
--- a/langtools/src/share/classes/sun/tools/javap/JavapPrinter.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/src/share/classes/sun/tools/javap/JavapPrinter.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2002-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/com/sun/javadoc/AuthorDD/AuthorDD.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/AuthorDD/AuthorDD.java	Fri Apr 10 13:05:12 2009 -0700
@@ -91,7 +91,7 @@
 
             // Test multiple @author tags:
 
-            { "<DT><STRONG>Author:</STRONG></DT>"+NL+"  <DD>Doug Kramer, Jamie, Neal</DD>"+NL,
+            { "<DT><STRONG>Author:</STRONG></DT>"+NL+"  <DD>Doug Kramer, Jamie, Neal</DD>",
                                   BUGID + FS + "p1" + FS + "C1.html" },
 
         };
--- a/langtools/test/com/sun/javadoc/testClassCrossReferences/TestClassCrossReferences.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testClassCrossReferences/TestClassCrossReferences.java	Fri Apr 10 13:05:12 2009 -0700
@@ -48,7 +48,7 @@
             "<A HREF=\"http://java.sun.com/j2se/1.4/docs/api/java/math/BigInteger.html?is-external=true#gcd(java.math.BigInteger)\" " +
                 "title=\"class or interface in java.math\"><CODE>Link to external member gcd</CODE></A>"},
         {BUG_ID + FS + "C.html",
-            "<STRONG>Overrides:</STRONG><DD><CODE>toString</CODE> in class <CODE>java.lang.Object</CODE>"}
+            "<STRONG>Overrides:</STRONG></DT><DD><CODE>toString</CODE> in class <CODE>java.lang.Object</CODE>"}
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
     private static final String[] ARGS =
--- a/langtools/test/com/sun/javadoc/testConstructorIndent/TestConstructorIndent.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testConstructorIndent/TestConstructorIndent.java	Fri Apr 10 13:05:12 2009 -0700
@@ -45,9 +45,10 @@
 
     //Input for string search tests.
     private static final String[][] TEST = {
-        {BUG_ID + FS + "C.html", "<DL>"+NL+"<DD>This is just a simple constructor."+ NL +
-            "<P>"+NL+"<DL>"+NL+"<DT><STRONG>Parameters:</STRONG><DD><CODE>i</CODE> - a param.</DL>"+NL +
-            "</DL>"
+        {BUG_ID + FS + "C.html", "<DL>" + NL + "<DD>This is just a simple constructor." + NL +
+            "<P>" + NL + "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Parameters:</STRONG>" +
+            "</DT><DD><CODE>i</CODE> - a param.</DD></DL>" + NL +
+            "</DD>" + NL + "</DL>"
         }
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
--- a/langtools/test/com/sun/javadoc/testDeprecatedDocs/TestDeprecatedDocs.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testDeprecatedDocs/TestDeprecatedDocs.java	Fri Apr 10 13:05:12 2009 -0700
@@ -78,13 +78,12 @@
 
         {TARGET_FILE2, "<STRONG>Deprecated.</STRONG>" + NL +
                 "<P>" + NL +
-            "<DL>" + NL +
-            "<DT><PRE><FONT SIZE=\"-1\">@Deprecated" + NL +
+            "<PRE><FONT SIZE=\"-1\">@Deprecated" + NL +
             "</FONT>public class <STRONG>DeprecatedClassByAnnotation</STRONG>"},
 
         {TARGET_FILE2, "public int <STRONG>field</STRONG></PRE>" + NL +
             "<DL>" + NL +
-            "<DD><STRONG>Deprecated.</STRONG>&nbsp;<DL>"},
+            "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD></DL>"},
 
         {TARGET_FILE2, "<FONT SIZE=\"-1\">@Deprecated" + NL +
             "</FONT>public <STRONG>DeprecatedClassByAnnotation</STRONG>()</PRE>" + NL +
--- a/langtools/test/com/sun/javadoc/testExternalOverridenMethod/TestExternalOverridenMethod.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testExternalOverridenMethod/TestExternalOverridenMethod.java	Fri Apr 10 13:05:12 2009 -0700
@@ -39,13 +39,13 @@
     private static final String BUG_ID = "4857717";
     private static final String[][] TEST = {
         {BUG_ID + FS + "pkg" + FS + "XReader.html",
-            "<STRONG>Overrides:</STRONG><DD><CODE><A HREF=\"" +
+            "<STRONG>Overrides:</STRONG></DT><DD><CODE><A HREF=\"" +
             "http://java.sun.com/j2se/1.4.1/docs/api/java/io/FilterReader.html?is-external=true#read()\"" +
                 " title=\"class or interface in java.io\">read</A></CODE> in class " +
                 "<CODE><A HREF=\"http://java.sun.com/j2se/1.4.1/docs/api/java/io/FilterReader.html?is-external=true\"" +
                 " title=\"class or interface in java.io\">FilterReader</A>"},
         {BUG_ID + FS + "pkg" + FS + "XReader.html",
-            "<STRONG>Specified by:</STRONG><DD><CODE><A HREF=\"" +
+            "<STRONG>Specified by:</STRONG></DT><DD><CODE><A HREF=\"" +
             "http://java.sun.com/j2se/1.4.1/docs/api/java/io/DataInput.html?is-external=true#readInt()\"" +
             " title=\"class or interface in java.io\">readInt</A></CODE> in interface " +
             "<CODE><A HREF=\"http://java.sun.com/j2se/1.4.1/docs/api/java/io/DataInput.html?is-external=true\"" +
--- a/langtools/test/com/sun/javadoc/testHeadings/TestHeadings.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testHeadings/TestHeadings.java	Fri Apr 10 13:05:12 2009 -0700
@@ -47,14 +47,16 @@
     private static final String[][] TEST = {
         //Package summary
         {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\">" + NL +
-            "<STRONG>Class Summary</STRONG></FONT></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Class</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
         },
 
         // Class documentation
         {BUG_ID + FS + "pkg1" + FS + "C1.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\">" + NL +
-            "<STRONG>Field Summary</STRONG></FONT></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Field and Description</TH>"
         },
         {BUG_ID + FS + "pkg1" + FS + "C1.html",
             "<TH ALIGN=\"left\"><STRONG>Methods inherited from class " +            "java.lang.Object</STRONG></TH>"
@@ -62,29 +64,32 @@
 
         // Class use documentation
         {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\">" + NL +
-            "Packages that use <A HREF=\"../../pkg1/C1.html\" " +            "title=\"class in pkg1\">C1</A></FONT></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Description</TH>"
         },
         {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
             "<TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\">" + NL +
             "Uses of <A HREF=\"../../pkg1/C1.html\" " +            "title=\"class in pkg1\">C1</A> in " +            "<A HREF=\"../../pkg2/package-summary.html\">pkg2</A></FONT></TH>"
         },
         {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\">Fields in " +            "<A HREF=\"../../pkg2/package-summary.html\">pkg2</A> " +            "declared as <A HREF=\"../../pkg1/C1.html\" " +            "title=\"class in pkg1\">C1</A></FONT></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Field and Description</TH>"
         },
 
         // Deprecated
         {BUG_ID + FS + "deprecated-list.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\">" + NL +
-            "<STRONG>Deprecated Methods</STRONG></FONT></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Method and Description</TH>"
         },
 
         // Constant values
         {BUG_ID + FS + "constant-values.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"3\">pkg1.<A HREF=\"pkg1/C1.html\" " +            "title=\"class in pkg1\">C1</A></TH>"
-        },
-        {BUG_ID + FS + "constant-values.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"3\">pkg1.<A HREF=\"pkg1/C1.html\" " +            "title=\"class in pkg1\">C1</A></TH>"
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Constant Field</TH>" + NL +
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>Value</TH>"
         },
 
         // Serialized Form
--- a/langtools/test/com/sun/javadoc/testHref/TestHref.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testHref/TestHref.java	Fri Apr 10 13:05:12 2009 -0700
@@ -67,7 +67,7 @@
         },
         //@see test.
         {BUG_ID + FS + "pkg" + FS + "C2.html",
-            "See Also:</STRONG><DD><A HREF=\"../pkg/C1.html#method(int, int, java.util.ArrayList)\">"
+            "See Also:</STRONG></DT><DD><A HREF=\"../pkg/C1.html#method(int, int, java.util.ArrayList)\">"
         },
 
         //Header does not link to the page itself.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/TestHtmlDefinitionListTag.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,378 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6786690 6820360
+ * @summary This test verifies the nesting of definition list tags.
+ * @author Bhavesh Patel
+ * @library ../lib/
+ * @build JavadocTester
+ * @build TestHtmlDefinitionListTag
+ * @run main TestHtmlDefinitionListTag
+ */
+
+public class TestHtmlDefinitionListTag extends JavadocTester {
+
+    private static final String BUG_ID = "6786690-6820360";
+
+    // Test common to all runs of javadoc. The class signature should print
+    // properly enclosed definition list tags and the Annotation Type
+    // Optional Element should print properly nested definition list tags
+    // for default value.
+    private static final String[][] TEST_ALL = {
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<PRE>public class " +
+                 "<STRONG>C1</STRONG>" + NL + "extends " +
+                 "java.lang.Object" + NL + "implements " +
+                 "java.io.Serializable</PRE>"},
+        {BUG_ID + FS + "pkg1" + FS + "C4.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Default:</STRONG></DT><DD>true</DD>" + NL +
+                 "</DL>" + NL + "</DD>" + NL + "</DL>"}};
+
+    // Test for normal run of javadoc in which various ClassDocs and
+    // serialized form should have properly nested definition list tags
+    // enclosing comments, tags and deprecated information.
+    private static final String[][] TEST_CMNT_DEPR = {
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<DL>" + NL +
+                 "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>JDK1.0</DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>JDK1.0</DD>" + NL + "<DT><STRONG>See Also:</STRONG></DT><DD>" +
+                 "<A HREF=\"../pkg1/C2.html\" title=\"class in pkg1\">" +
+                 "<CODE>C2</CODE></A>, " + NL +
+                 "<A HREF=\"../serialized-form.html#pkg1.C1\">" +
+                 "Serialized Form</A></DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I></DD>" +
+                 "<DD>This field indicates whether the C1 is undecorated." + NL +
+                 "<P>" + NL + "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>" +
+                 "Since:</STRONG></DT>" + NL + "  <DD>1.4</DD>" + NL + "<DT>" +
+                 "<STRONG>See Also:</STRONG></DT><DD>" +
+                 "<A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\"><CODE>" +
+                 "setUndecorated(boolean)</CODE></A></DD></DL>" + NL +"</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DD>Constructor." + NL + "<P>" + NL + "</DD>" + NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Parameters:</STRONG></DT><DD>" +
+                 "<CODE>title</CODE> - the title</DD><DD><CODE>test</CODE>" +
+                 " - boolean value</DD>" + NL + "<DT><STRONG>Throws:</STRONG></DT>" + NL +
+                 "<DD><CODE>java.lang.IllegalArgumentException</CODE>" +
+                 " - if the <code>owner</code>'s" + NL + "     <code>GraphicsConfiguration" +
+                 "</code> is not from a screen device</DD>" + NL +"<DD><CODE>" +
+                 "HeadlessException</CODE></DD></DL>" + NL + "</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DD>Method comments." + NL + "<P>" + NL +
+                 "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Parameters:" +
+                 "</STRONG></DT><DD><CODE>undecorated</CODE> - <code>true</code>" +
+                 " if no decorations are" + NL + "         to be enabled;" + NL +
+                 "         <code>false</code> if decorations are to be enabled." +
+                 "</DD><DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>1.4</DD>" + NL + "<DT><STRONG>See Also:</STRONG></DT>" +
+                 "<DD><A HREF=\"../pkg1/C1.html#readObject()\"><CODE>" +
+                 "readObject()</CODE></A></DD></DL>" + NL + "</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Throws:</STRONG></DT>" + NL + "<DD><CODE>" +
+                 "java.io.IOException</CODE></DD><DT><STRONG>See Also:" +
+                 "</STRONG></DT><DD>" +
+                 "<A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.ModalExclusionType.html", "<DL>" + NL +
+                 "<DD>No modal exclusion." + NL + "<P>" + NL +"</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL>" + NL + "<DD>Constructor." + NL +
+                 "<P>" + NL +"</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version 1.5, replaced " +
+                 "by" + NL + " <A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD><DD>Set visible." + NL + "<P>" + NL + "</DD>" +NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Parameters:</STRONG></DT><DD>" +
+                 "<CODE>set</CODE> - boolean</DD><DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>1.4</DD></DL>" + NL + "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C3.html", "<DL>" + NL + "<DD>Comment." + NL +
+                 "<P>" + NL + "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Throws:</STRONG></DT>" + NL + "<DD><CODE>" +
+                 "java.io.IOException</CODE></DD><DT><STRONG>See Also:</STRONG>" +
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version " +
+                 "1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I></DD>" +
+                 "<DD>This field indicates whether the C1 is undecorated." + NL +
+                 "<P>" + NL + "</DD>" + NL + "<DD>&nbsp;</DD>" + NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>1.4</DD>" + NL + "<DT><STRONG>See Also:</STRONG>" +
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD><DD>Reads the object stream." + NL + "<P>" + NL +
+                 "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Throws:" +
+                 "</STRONG></DT>" + NL + "<DD><CODE><code>" +
+                 "IOException</code></CODE></DD>" + NL +
+                 "<DD><CODE>java.io.IOException</CODE></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD><DD>" +
+                 "The name for this class." + NL + "<P>" + NL + "</DD>" + NL +
+                 "<DD>&nbsp;</DD>" + NL + "</DL>"}};
+
+    // Test with -nocomment option. The ClassDocs and serialized form should
+    // have properly nested definition list tags enclosing deprecated
+    // information and should not display definition lists for comments
+    // and tags.
+    private static final String[][] TEST_NOCMNT = {
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version 1.5, replaced by" + NL +
+                 " <A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\"><CODE>" +
+                 "setUndecorated(boolean)</CODE></A>.</I></DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C5.html", "<PRE>" + NL +
+                 "protected <STRONG>C5</STRONG>()</PRE>" + NL + "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C5.html", "<PRE>" + NL +
+                 "public void <STRONG>printInfo</STRONG>()</PRE>" + NL + "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<PRE>" + NL + "boolean <STRONG>" +
+                 "undecorated</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\"><CODE>" +
+                 "setUndecorated(boolean)</CODE></A>.</I></DD></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<PRE>" + NL + "int <STRONG>" +
+                 "publicKey</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;</DD></DL>"}};
+
+    // Test with -nodeprecated option. The ClassDocs should have properly nested
+    // definition list tags enclosing comments and tags. The ClassDocs should not
+    // display definition list for deprecated information. The serialized form
+    // should display properly nested definition list tags for comments, tags
+    // and deprecated information.
+    private static final String[][] TEST_NODEPR = {
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<DL>" + NL +
+                 "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>JDK1.0</DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>JDK1.0</DD>" + NL + "<DT><STRONG>See Also:</STRONG></DT><DD>" +
+                 "<A HREF=\"../pkg1/C2.html\" title=\"class in pkg1\">" +
+                 "<CODE>C2</CODE></A>, " + NL +
+                 "<A HREF=\"../serialized-form.html#pkg1.C1\">" +
+                 "Serialized Form</A></DD></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DD>Constructor." + NL + "<P>" + NL + "</DD>" + NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Parameters:</STRONG></DT><DD>" +
+                 "<CODE>title</CODE> - the title</DD><DD><CODE>test</CODE>" +
+                 " - boolean value</DD>" + NL + "<DT><STRONG>Throws:</STRONG></DT>" + NL +
+                 "<DD><CODE>java.lang.IllegalArgumentException</CODE>" +
+                 " - if the <code>owner</code>'s" + NL + "     <code>GraphicsConfiguration" +
+                 "</code> is not from a screen device</DD>" + NL +"<DD><CODE>" +
+                 "HeadlessException</CODE></DD></DL>" + NL + "</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL +
+                 "<DD>Method comments." + NL + "<P>" + NL +
+                 "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Parameters:" +
+                 "</STRONG></DT><DD><CODE>undecorated</CODE> - <code>true</code>" +
+                 " if no decorations are" + NL + "         to be enabled;" + NL +
+                 "         <code>false</code> if decorations are to be enabled." +
+                 "</DD><DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>1.4</DD>" + NL + "<DT><STRONG>See Also:</STRONG></DT>" +
+                 "<DD><A HREF=\"../pkg1/C1.html#readObject()\"><CODE>" +
+                 "readObject()</CODE></A></DD></DL>" + NL + "</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Throws:</STRONG></DT>" + NL + "<DD><CODE>" +
+                 "java.io.IOException</CODE></DD><DT><STRONG>See Also:" +
+                 "</STRONG></DT><DD>" +
+                 "<A HREF=\"../pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.ModalExclusionType.html", "<DL>" + NL +
+                 "<DD>No modal exclusion." + NL + "<P>" + NL +"</DD>" + NL +
+                 "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL>" + NL + "<DD>Constructor." + NL +
+                 "<P>" + NL +"</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C3.html", "<DL>" + NL + "<DD>Comment." + NL +
+                 "<P>" + NL + "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Throws:</STRONG></DT>" + NL + "<DD><CODE>" +
+                 "java.io.IOException</CODE></DD><DT><STRONG>See Also:</STRONG>" +
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version " +
+                 "1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I></DD>" +
+                 "<DD>This field indicates whether the C1 is undecorated." + NL +
+                 "<P>" + NL + "</DD>" + NL + "<DD>&nbsp;</DD>" + NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "  <DD>1.4</DD>" + NL + "<DT><STRONG>See Also:</STRONG>" +
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD><DD>Reads the object stream." + NL + "<P>" + NL +
+                 "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Throws:" +
+                 "</STRONG></DT>" + NL + "<DD><CODE><code>" +
+                 "IOException</code></CODE></DD>" + NL +
+                 "<DD><CODE>java.io.IOException</CODE></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD><DD>" +
+                 "The name for this class." + NL + "<P>" + NL + "</DD>" + NL +
+                 "<DD>&nbsp;</DD>" + NL + "</DL>"}};
+
+    // Test with -nocomment and -nodeprecated options. The ClassDocs whould
+    // not display definition lists for any member details. The serialized
+    // form should display properly nested definition list tags for
+    // deprecated information only.
+    private static final String[][] TEST_NOCMNT_NODEPR = {
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<PRE>" + NL + "public void " +
+                 "<STRONG>readObject</STRONG>()" + NL + "                throws" +
+                 " java.io.IOException</PRE>" + NL + "<HR>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<PRE>" +NL + "public <STRONG>" +
+                 "C2</STRONG>()</PRE>" + NL + "<HR>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.ModalExclusionType.html", "<PRE>" + NL +
+                 "public static final " +
+                 "<A HREF=\"../pkg1/C1.ModalExclusionType.html\" " +
+                 "title=\"enum in pkg1\">C1.ModalExclusionType</A> <STRONG>" +
+                 "APPLICATION_EXCLUDE</STRONG></PRE>" + NL + "<HR>"},
+        {BUG_ID + FS + "serialized-form.html", "<PRE>" + NL + "boolean <STRONG>" +
+                 "undecorated</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\"><CODE>" +
+                 "setUndecorated(boolean)</CODE></A>.</I></DD></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
+                 " 1.5, replaced by" + NL +
+                 " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
+                 "</DD></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<PRE>" + NL + "int <STRONG>" +
+                 "publicKey</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
+                 "Deprecated.</STRONG>&nbsp;</DD></DL>"}};
+
+    // Test for valid HTML generation which should not comprise of empty
+    // definition list tags.
+    private static final String[][] NEGATED_TEST = {
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.ModalExclusionType.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.ModalExclusionType.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.ModalType.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C2.ModalType.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C3.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C3.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C4.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C4.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C5.html", "<DL></DL>"},
+        {BUG_ID + FS + "pkg1" + FS + "C5.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "overview-tree.html", "<DL></DL>"},
+        {BUG_ID + FS + "overview-tree.html", "<DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL></DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "</DL>"}};
+
+    private static final String[] ARGS1 =
+        new String[] {
+            "-d", BUG_ID, "-sourcepath", SRC_DIR, "pkg1"};
+
+    private static final String[] ARGS2 =
+        new String[] {
+            "-d", BUG_ID, "-nocomment", "-sourcepath", SRC_DIR, "pkg1"};
+
+    private static final String[] ARGS3 =
+        new String[] {
+            "-d", BUG_ID, "-nodeprecated", "-sourcepath", SRC_DIR, "pkg1"};
+
+    private static final String[] ARGS4 =
+        new String[] {
+            "-d", BUG_ID, "-nocomment", "-nodeprecated", "-sourcepath", SRC_DIR, "pkg1"};
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestHtmlDefinitionListTag tester = new TestHtmlDefinitionListTag();
+        run(tester, ARGS1, TEST_ALL, NEGATED_TEST);
+        run(tester, ARGS1, TEST_CMNT_DEPR, NEGATED_TEST);
+        run(tester, ARGS2, TEST_ALL, NEGATED_TEST);
+        run(tester, ARGS2, TEST_NOCMNT, TEST_CMNT_DEPR);
+        run(tester, ARGS3, TEST_ALL, NEGATED_TEST);
+        run(tester, ARGS3, TEST_NODEPR, TEST_NOCMNT_NODEPR);
+        run(tester, ARGS4, TEST_ALL, NEGATED_TEST);
+        run(tester, ARGS4, TEST_NOCMNT_NODEPR, TEST_CMNT_DEPR);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/C1.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+/**
+ * A class comment for testing.
+ *
+ * @author      Bhavesh Patel
+ * @see C2
+ * @since       JDK1.0
+ */
+
+public class C1 implements Serializable {
+
+    /**
+     * This field indicates whether the C1 is undecorated.
+     *
+     * @see #setUndecorated(boolean)
+     * @since 1.4
+     * @serial
+     * @deprecated As of JDK version 1.5, replaced by
+     * {@link C1#setUndecorated(boolean) setUndecorated(boolean)}.
+     */
+     @Deprecated
+    public boolean undecorated = false;
+
+    private String title;
+
+    /**
+     * This enum specifies the possible modal exclusion types.
+     *
+     * @since 1.6
+     */
+    public static enum ModalExclusionType {
+        /**
+         * No modal exclusion.
+         */
+        NO_EXCLUDE,
+        /**
+         * <code>APPLICATION_EXCLUDE</code> indicates that a top-level window
+         * won't be blocked by any application-modal dialogs. Also, it isn't
+         * blocked by document-modal dialogs from outside of its child hierarchy.
+         */
+        APPLICATION_EXCLUDE
+    };
+
+    /**
+     * Constructor.
+     *
+     * @param title the title
+     * @param test boolean value
+     * @exception IllegalArgumentException if the <code>owner</code>'s
+     *     <code>GraphicsConfiguration</code> is not from a screen device
+     * @exception HeadlessException
+     */
+     public C1(String title, boolean test) {
+
+     }
+
+     public C1(String title) {
+
+     }
+
+    /**
+     * Method comments.
+     * @param  undecorated <code>true</code> if no decorations are
+     *         to be enabled;
+     *         <code>false</code> if decorations are to be enabled.
+     * @see    #readObject()
+     * @since 1.4
+     */
+    public void setUndecorated(boolean undecorated) {
+        /* Make sure we don't run in the middle of peer creation.*/
+    }
+
+    /**
+     * @see #setUndecorated(boolean)
+     */
+    public void readObject() throws IOException {
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/C2.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import java.io.ObjectInputStream;
+import java.io.IOException;
+import java.io.Serializable;
+
+/**
+ * A class comment for testing.
+ *
+ * @author      Bhavesh Patel
+ * @see C1
+ * @since       JDK1.0
+ */
+
+public class C2 implements Serializable {
+
+    /**
+     * This field indicates title.
+     */
+    String title;
+
+    public static enum ModalType {
+        NO_EXCLUDE
+    };
+
+    /**
+     * Constructor.
+     *
+     */
+     public C2() {
+
+     }
+
+     public C2(String title) {
+
+     }
+
+     /**
+     * Set visible.
+     *
+     * @param set boolean
+     * @since 1.4
+     * @deprecated As of JDK version 1.5, replaced by
+     * {@link C1#setUndecorated(boolean) setUndecorated(boolean)}.
+     */
+     @Deprecated
+     public void setVisible(boolean set) {
+     }
+
+     /**
+     * Reads the object stream.
+     *
+     * @param s ObjectInputStream
+     * @throws <code>IOException</code>
+     * @deprecated As of JDK version 1.5, replaced by
+     * {@link C1#setUndecorated(boolean) setUndecorated(boolean)}.
+     */
+     @Deprecated
+     public void readObject(ObjectInputStream s) throws IOException {
+     }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/C3.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * Test Annotation class.
+ *
+ * @author Bhavesh Patel
+ * @since 1.5
+ */
+@Retention(RetentionPolicy.SOURCE)
+public @interface C3 {
+    /**
+     * Comment.
+     */
+    String[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/C4.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/*
+ * The @Inherited annotation has no effect when applied to an interface.
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+@Inherited
+public @interface C4 {
+    boolean value() default true;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/C5.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import java.io.Serializable;
+
+/**
+ * Test for Serializable
+ *
+ * @author Bhavesh Patel
+ * @deprecated This class is no longer used.
+ */
+@Deprecated
+public abstract class C5 implements Serializable {
+
+    /**
+     * The name for this class.
+     *
+     * @serial
+     */
+    private String name;
+
+    /**
+     * @serial
+     */
+    private int publicKey;
+
+    /**
+     * Constructor for serialization only.
+     */
+    protected C5() {
+
+    }
+
+    /**
+     * Prints general information.
+     *
+     */
+    public void printInfo() {
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlDefinitionListTag/pkg1/package-info.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * Test package 1.
+ *
+ * @since JDK1.0
+ */
+package pkg1;
--- a/langtools/test/com/sun/javadoc/testHtmlStrongTag/TestHtmlStrongTag.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testHtmlStrongTag/TestHtmlStrongTag.java	Fri Apr 10 13:05:12 2009 -0700
@@ -38,14 +38,15 @@
 
     private static final String BUG_ID = "6786028";
     private static final String[][] TEST1 = {
-        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<STRONG>Method Summary</STRONG>"},
-        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<STRONG>See Also:</STRONG>"},
-        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<STRONG>Class Summary</STRONG>"}};
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<STRONG>See Also:</STRONG>"}};
     private static final String[][] NEGATED_TEST1 = {
-        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<B>"}};
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<STRONG>Method Summary</STRONG>"},
+        {BUG_ID + FS + "pkg1" + FS + "C1.html", "<B>"},
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<STRONG>Class Summary</STRONG>"}};
     private static final String[][] TEST2 = {
+        {BUG_ID + FS + "pkg2" + FS + "C2.html", "<B>Comments:</B>"}};
+    private static final String[][] NEGATED_TEST2 = {
         {BUG_ID + FS + "pkg2" + FS + "C2.html", "<STRONG>Method Summary</STRONG>"},
-        {BUG_ID + FS + "pkg2" + FS + "C2.html", "<B>Comments:</B>"},
         {BUG_ID + FS + "pkg1" + FS + "package-summary.html", "<STRONG>Class Summary</STRONG>"}};
 
     private static final String[] ARGS1 =
@@ -62,7 +63,7 @@
     public static void main(String[] args) {
         TestHtmlStrongTag tester = new TestHtmlStrongTag();
         run(tester, ARGS1, TEST1, NEGATED_TEST1);
-        run(tester, ARGS2, TEST2, NO_TEST);
+        run(tester, ARGS2, TEST2, NEGATED_TEST2);
         tester.printSummary();
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/TestHtmlTableTags.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,478 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug      6786688
+ * @summary  HTML tables should have table summary, caption and table headers.
+ * @author   Bhavesh Patel
+ * @library  ../lib/
+ * @build    JavadocTester
+ * @build    TestHtmlTableTags
+ * @run main TestHtmlTableTags
+ */
+
+public class TestHtmlTableTags extends JavadocTester {
+
+    //Test information.
+    private static final String BUG_ID = "6786688";
+
+    //Javadoc arguments.
+    private static final String[] ARGS = new String[] {
+        "-d", BUG_ID, "-sourcepath", SRC_DIR, "-use", "pkg1", "pkg2"
+    };
+
+    //Input for string tests for HTML table tags.
+    private static final String[][] TABLE_TAGS_TEST = {
+        /*
+         * Test for validating summary for HTML tables
+         */
+
+        //Package summary
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Class Summary table, " +
+            "listing classes, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Interface Summary table, " +
+            "listing interfaces, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Enum Summary table, " +
+            "listing enums, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Annotation Types Summary table, " +
+            "listing annotation types, and an explanation\">"
+        },
+        // Class documentation
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Field Summary table, " +
+            "listing fields, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Method Summary table, " +
+            "listing methods, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Nested Class Summary table, " +
+            "listing nested classes, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Constructor Summary table, " +
+            "listing constructors, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.ModalExclusionType.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Enum Constant Summary table, " +
+            "listing enum constants, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C3.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Required Element Summary table, " +
+            "listing required elements, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C4.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Optional Element Summary table, " +
+            "listing optional elements, and an explanation\">"
+        },
+        // Class use documentation
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "I1.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing packages, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing fields, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing methods, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing fields, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing methods, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.ModalExclusionType.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing packages, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.ModalExclusionType.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing methods, and an explanation\">"
+        },
+        // Package use documentation
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing packages, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing classes, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing packages, and an explanation\">"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Use table, " +
+            "listing classes, and an explanation\">"
+        },
+        // Deprecated
+        {BUG_ID + FS + "deprecated-list.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Deprecated Fields table, " +
+            "listing deprecated fields, and an explanation\">"
+        },
+        {BUG_ID + FS + "deprecated-list.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Deprecated Methods table, " +
+            "listing deprecated methods, and an explanation\">"
+        },
+        // Constant values
+        {BUG_ID + FS + "constant-values.html",
+            "<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" " +
+            "SUMMARY=\"Constant Field Values table, listing " +
+            "constant fields, and values\">"
+        },
+        // Overview Summary
+        {BUG_ID + FS + "overview-summary.html",
+            "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" " +
+            "CELLSPACING=\"0\" SUMMARY=\"Packages table, " +
+            "listing packages, and an explanation\">"
+        },
+
+        /*
+         * Test for validating caption for HTML tables
+         */
+
+        //Package summary
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Class Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Interface Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Enum Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Annotation Types Summary</CAPTION>"
+        },
+        // Class documentation
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Field Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Method Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Nested Class Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Constructor Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.ModalExclusionType.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Enum Constant Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C3.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Required Element Summary</CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C4.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Optional Element Summary</CAPTION>"
+        },
+        // Class use documentation
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "I1.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Packages that use <A HREF=\"../../pkg1/I1.html\" " +
+            "title=\"interface in pkg1\">I1</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> " +
+            "declared as <A HREF=\"../../pkg1/C1.html\" title=\"class in pkg1\">" +
+            "C1</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> " +
+            "with parameters of type <A HREF=\"../../pkg1/C1.html\" " +
+            "title=\"class in pkg1\">C1</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "Fields in <A HREF=\"../../pkg1/package-summary.html\">pkg1</A> " +
+            "declared as <A HREF=\"../../pkg2/C2.html\" title=\"class in pkg2\">" +
+            "C2</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "Methods in <A HREF=\"../../pkg1/package-summary.html\">pkg1</A> " +
+            "with parameters of type <A HREF=\"../../pkg2/C2.html\" " +
+            "title=\"class in pkg2\">C2</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.ModalExclusionType.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> " +
+            "that return <A HREF=\"../../pkg2/C2.ModalExclusionType.html\" " +
+            "title=\"enum in pkg2\">C2.ModalExclusionType</A></CAPTION>"
+        },
+        // Package use documentation
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Packages that use <A HREF=\"../pkg1/package-summary.html\">" +
+            "pkg1</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Classes in <A HREF=\"../pkg1/package-summary.html\">pkg1</A> " +
+            "used by <A HREF=\"../pkg1/package-summary.html\">pkg1</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Packages that use <A HREF=\"../pkg2/package-summary.html\">" +
+            "pkg2</A></CAPTION>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Classes in <A HREF=\"../pkg2/package-summary.html\">pkg2</A> " +
+            "used by <A HREF=\"../pkg1/package-summary.html\">pkg1</A></CAPTION>"
+        },
+        // Deprecated
+        {BUG_ID + FS + "deprecated-list.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Deprecated Fields</CAPTION>"
+        },
+        {BUG_ID + FS + "deprecated-list.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Deprecated Methods</CAPTION>"
+        },
+        // Constant values
+        {BUG_ID + FS + "constant-values.html",
+            "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+            "pkg1.<A HREF=\"pkg1/C1.html\" title=\"class in pkg1\">C1</A></CAPTION>"
+        },
+        // Overview Summary
+        {BUG_ID + FS + "overview-summary.html",
+            "<CAPTION CLASS=\"TableCaption\">" + NL +
+            "Packages</CAPTION>"
+        },
+
+        /*
+         * Test for validating headers for HTML tables
+         */
+
+        //Package summary
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Class</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-summary.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Interface</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Enum</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-summary.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Annotation Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Description</TH>"
+        },
+        // Class documentation
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Field and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "C1.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Method and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Class and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Constructor and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C2.ModalExclusionType.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Enum Constant and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C3.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Required Element and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "C4.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Optional Element and Description</TH>"
+        },
+        // Class use documentation
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "I1.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Field and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "class-use" + FS + "C1.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Method and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Field and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Method and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.ModalExclusionType.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "C2.ModalExclusionType.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Method and Description</TH>"
+        },
+        // Package use documentation
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg1" + FS + "package-use.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Class and Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        },
+        {BUG_ID + FS + "pkg2" + FS + "package-use.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Class and Description</TH>"
+        },
+        // Deprecated
+        {BUG_ID + FS + "deprecated-list.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Field and Description</TH>"
+        },
+        {BUG_ID + FS + "deprecated-list.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Method and Description</TH>"
+        },
+        // Constant values
+        {BUG_ID + FS + "constant-values.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Modifier and Type</TH>" + NL + "<TH CLASS=\"TableHeader\"" +
+            " SCOPE=\"col\" NOWRAP>Constant Field</TH>" + NL +
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>Value</TH>"
+        },
+        // Overview Summary
+        {BUG_ID + FS + "overview-summary.html",
+            "<TH CLASS=\"TableHeader\" SCOPE=\"col\" NOWRAP>" +
+            "Package</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+            " NOWRAP>Description</TH>"
+        }
+    };
+    private static final String[][] NEGATED_TEST = NO_TEST;
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestHtmlTableTags tester = new TestHtmlTableTags();
+        run(tester, ARGS, TABLE_TAGS_TEST, NEGATED_TEST);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg1/C1.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+import pkg2.*;
+
+/**
+ * A test class.
+ *
+ * @author Bhavesh Patel
+ */
+public class C1 implements I1 {
+
+    /**
+     * Test field for class.
+     */
+    public C2 field;
+
+    /**
+     * Constant value.
+     */
+    public static final String CONSTANT1 = "C1";
+
+    /**
+     * A test constructor.
+     */
+    C1() {
+    }
+
+    /**
+     * Method thats does some processing.
+     *
+     * @param param some parameter that is passed.
+     * @return a sample object.
+     */
+    public C2 method(C2 param) {
+        return param;
+    }
+
+    /**
+     * Method that is implemented.
+     *
+     * @param a some random value.
+     * @param b some random value.
+     */
+    public void method1(int a, int b) {
+    }
+
+    /**
+     * Another inherited method.
+     * @param c some value.
+     */
+    public void method2(int c) {
+    }
+
+    /**
+     * @deprecated don't use this anymore.
+     */
+    public void deprecatedMethod() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg1/I1.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg1;
+
+/**
+ * A sample interface used to test table tags.
+ *
+ * @author Bhavesh Patel
+ */
+public interface I1 {
+
+    /**
+     * A test method.
+     *
+     * @param a blah.
+     * @param b blah.
+     */
+    void method1(int a, int b);
+
+    /**
+     * Another test method.
+     *
+     * @param c blah.
+     */
+    void method2(int c);
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg1/package-info.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * Test package 1 used to test table tags.
+ */
+package pkg1;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg2/C2.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg2;
+
+import pkg1.*;
+
+/**
+ * Another test class.
+ *
+ * @author Bhavesh Patel
+ */
+public class C2 {
+
+    /**
+     * A test field.
+     */
+    public C1 field;
+
+    /**
+     * @deprecated don't use this field anymore.
+     */
+    public C1 dep_field;
+
+    /**
+     * A sample enum.
+     */
+    public static enum ModalExclusionType {
+        /**
+         * Test comment.
+         */
+        NO_EXCLUDE,
+        /**
+         * Another comment.
+         */
+        APPLICATION_EXCLUDE
+    };
+
+    /**
+     * A string constant.
+     */
+    public static final String CONSTANT1 = "C2";
+
+    /**
+     * A sample method.
+     *
+     * @param param some parameter.
+     * @return a test object.
+     */
+    public C1 method(C1 param) {
+        return param;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg2/C3.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg2;
+
+import java.lang.annotation.*;
+
+/**
+ * Test Annotation class.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface C3 {
+    /**
+     * Comment.
+     */
+    String[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg2/C4.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package pkg2;
+
+import java.lang.annotation.*;
+
+/*
+ * A sample interface.
+ */
+public @interface C4 {
+    boolean value() default true;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/pkg2/package-info.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * Test package 2 used to test table tags.
+ */
+package pkg2;
--- a/langtools/test/com/sun/javadoc/testIndex/TestIndex.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testIndex/TestIndex.java	Fri Apr 10 13:05:12 2009 -0700
@@ -73,10 +73,10 @@
         {BUG_ID + FS + "index-all.html",
             "<DT><A HREF=\"./pkg/C.html#Java\"><STRONG>Java</STRONG></A> - " + NL +
             "Static variable in class pkg.<A HREF=\"./pkg/C.html\" title=\"class in pkg\">C</A>" + NL +
-            "<DD>&nbsp;" + NL +
+            "</DT><DD>&nbsp;</DD>" + NL + NL +
             "<DT><A HREF=\"./pkg/C.html#JDK\"><STRONG>JDK</STRONG></A> - " + NL +
             "Static variable in class pkg.<A HREF=\"./pkg/C.html\" title=\"class in pkg\">C</A>" + NL +
-            "<DD>&nbsp;"},
+            "</DT><DD>&nbsp;</DD>"},
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
 
--- a/langtools/test/com/sun/javadoc/testInterface/TestInterface.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testInterface/TestInterface.java	Fri Apr 10 13:05:12 2009 -0700
@@ -55,7 +55,7 @@
 
         // Make sure known implementing class list is correct and omits type parameters.
         {BUG_ID + FS + "pkg" + FS + "Interface.html",
-            "<DT><STRONG>All Known Implementing Classes:</STRONG> " +
+            "<DT><STRONG>All Known Implementing Classes:</STRONG></DT> " +
             "<DD><A HREF=\"../pkg/Child.html\" " +
             "title=\"class in pkg\">Child</A>, " +
             "<A HREF=\"../pkg/Parent.html\" title=\"class in pkg\">" +
@@ -63,7 +63,9 @@
 
          // Make sure "All Implemented Interfaces": has substituted type parameters
          {BUG_ID + FS + "pkg" + FS + "Child.html",
-            "<STRONG>All Implemented Interfaces:</STRONG> <DD><A HREF=\"../pkg/Interface.html\" title=\"interface in pkg\">Interface</A>&lt;T&gt;"
+            "<STRONG>All Implemented Interfaces:</STRONG></DT> <DD>" +
+            "<A HREF=\"../pkg/Interface.html\" title=\"interface in pkg\">" +
+            "Interface</A>&lt;T&gt;"
          },
          //Make sure Class Tree has substituted type parameters.
          {BUG_ID + FS + "pkg" + FS + "Child.html",
@@ -75,15 +77,15 @@
          },
          //Make sure "Direct Know Subclasses" omits type parameters
         {BUG_ID + FS + "pkg" + FS + "Parent.html",
-            "<STRONG>Direct Known Subclasses:</STRONG> <DD><A HREF=\"../pkg/Child.html\" title=\"class in pkg\">Child</A>"
+            "<STRONG>Direct Known Subclasses:</STRONG></DT> <DD><A HREF=\"../pkg/Child.html\" title=\"class in pkg\">Child</A>"
         },
         //Make sure "Specified By" has substituted type parameters.
         {BUG_ID + FS + "pkg" + FS + "Child.html",
-            "<STRONG>Specified by:</STRONG><DD><CODE><A HREF=\"../pkg/Interface.html#method()\">method</A></CODE> in interface <CODE><A HREF=\"../pkg/Interface.html\" title=\"interface in pkg\">Interface</A>&lt;<A HREF=\"../pkg/Child.html\" title=\"type parameter in Child\">T</A>&gt;</CODE>"
+            "<STRONG>Specified by:</STRONG></DT><DD><CODE><A HREF=\"../pkg/Interface.html#method()\">method</A></CODE> in interface <CODE><A HREF=\"../pkg/Interface.html\" title=\"interface in pkg\">Interface</A>&lt;<A HREF=\"../pkg/Child.html\" title=\"type parameter in Child\">T</A>&gt;</CODE>"
          },
         //Make sure "Overrides" has substituted type parameters.
         {BUG_ID + FS + "pkg" + FS + "Child.html",
-            "<STRONG>Overrides:</STRONG><DD><CODE><A HREF=\"../pkg/Parent.html#method()\">method</A></CODE> in class <CODE><A HREF=\"../pkg/Parent.html\" title=\"class in pkg\">Parent</A>&lt;<A HREF=\"../pkg/Child.html\" title=\"type parameter in Child\">T</A>&gt;</CODE>"
+            "<STRONG>Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg/Parent.html#method()\">method</A></CODE> in class <CODE><A HREF=\"../pkg/Parent.html\" title=\"class in pkg\">Parent</A>&lt;<A HREF=\"../pkg/Child.html\" title=\"type parameter in Child\">T</A>&gt;</CODE>"
          },
     };
     private static final String[][] NEGATED_TEST = {
--- a/langtools/test/com/sun/javadoc/testLinkOption/TestLinkOption.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testLinkOption/TestLinkOption.java	Fri Apr 10 13:05:12 2009 -0700
@@ -63,7 +63,8 @@
             "title=\"class or interface in java.lang\">Object</A>&nbsp;p3)"
         },
         {BUG_ID + "-1" + FS + "java" + FS + "lang" + FS + "StringBuilderChild.html",
-                "public abstract class <STRONG>StringBuilderChild</STRONG><DT>extends <A HREF=\"http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html?is-external=true\" title=\"class or interface in java.lang\">Object</A>"
+                "public abstract class <STRONG>StringBuilderChild</STRONG>" + NL +
+                "extends <A HREF=\"http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html?is-external=true\" title=\"class or interface in java.lang\">Object</A>"
         },
 
     };
--- a/langtools/test/com/sun/javadoc/testLinkTaglet/TestLinkTaglet.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testLinkTaglet/TestLinkTaglet.java	Fri Apr 10 13:05:12 2009 -0700
@@ -59,7 +59,7 @@
             " Link to another inner class: <A HREF=\"../pkg/C.InnerC2.html\" title=\"class in pkg\"><CODE>C.InnerC2</CODE></A>"
         },
         {BUG_ID + FS + "pkg" + FS + "C.InnerC2.html",
-            "Enclosing class:</STRONG><DD><A HREF=\"../pkg/C.html\" title=\"class in pkg\">C</A>"
+            "Enclosing class:</STRONG></DT><DD><A HREF=\"../pkg/C.html\" title=\"class in pkg\">C</A>"
         },
     };
     private static final String[][] NEGATED_TEST = {
--- a/langtools/test/com/sun/javadoc/testMemberInheritence/TestMemberInheritence.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testMemberInheritence/TestMemberInheritence.java	Fri Apr 10 13:05:12 2009 -0700
@@ -74,7 +74,7 @@
 
          // Test overriding/implementing methods with generic parameters.
                  {BUG_ID + FS + "pkg" + FS + "BaseClass.html",
-         "<DT><STRONG>Specified by:</STRONG><DD><CODE><A HREF=\"../pkg/BaseInterface.html#getAnnotation(java.lang.Class)\">getAnnotation</A></CODE> in interface <CODE><A HREF=\"../pkg/BaseInterface.html\" title=\"interface in pkg\">BaseInterface</A></CODE></DL>"},
+         "<DT><STRONG>Specified by:</STRONG></DT><DD><CODE><A HREF=\"../pkg/BaseInterface.html#getAnnotation(java.lang.Class)\">getAnnotation</A></CODE> in interface <CODE><A HREF=\"../pkg/BaseInterface.html\" title=\"interface in pkg\">BaseInterface</A></CODE></DD>"+NL+"</DL>"},
 
          // Test diamond inheritence member summary (6256068)
                  {BUG_ID + FS + "diamond" + FS + "Z.html",
--- a/langtools/test/com/sun/javadoc/testNewLanguageFeatures/TestNewLanguageFeatures.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testNewLanguageFeatures/TestNewLanguageFeatures.java	Fri Apr 10 13:05:12 2009 -0700
@@ -54,11 +54,12 @@
             {BUG_ID + FS + "pkg" + FS + "Coin.html", "Enum Coin</H2>"},
             //Make sure enum signature is correct.
             {BUG_ID + FS + "pkg" + FS + "Coin.html", "public enum "+
-                "<STRONG>Coin</STRONG><DT>extends java.lang.Enum&lt;" +
+                "<STRONG>Coin</STRONG>" + NL + "extends java.lang.Enum&lt;" +
                 "<A HREF=\"../pkg/Coin.html\" title=\"enum in pkg\">Coin</A>&gt;"
             },
             //Check for enum constant section
-            {BUG_ID + FS + "pkg" + FS + "Coin.html", "<STRONG>Enum Constant Summary</STRONG>"},
+            {BUG_ID + FS + "pkg" + FS + "Coin.html", "<CAPTION CLASS=\"TableCaption\">" + NL +
+                     "Enum Constant Summary</CAPTION>"},
             //Detail for enum constant
             {BUG_ID + FS + "pkg" + FS + "Coin.html",
                 "<STRONG><A HREF=\"../pkg/Coin.html#Dime\">Dime</A></STRONG>"},
@@ -79,20 +80,20 @@
                 "Class TypeParameters&lt;E&gt;</H2>"},
             //Check class type parameters section.
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
-                "<DT><STRONG>Type Parameters:</STRONG><DD><CODE>E</CODE> - " +
+                "<DT><STRONG>Type Parameters:</STRONG></DT><DD><CODE>E</CODE> - " +
                 "the type parameter for this class."},
             //Type parameters in @see/@link
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
-                "<DT><STRONG>See Also:</STRONG><DD><A HREF=\"../pkg/TypeParameters.html\" " +
-                    "title=\"class in pkg\"><CODE>TypeParameters</CODE></A></DL>"},
+                "<DT><STRONG>See Also:</STRONG></DT><DD><A HREF=\"../pkg/TypeParameters.html\" " +
+                    "title=\"class in pkg\"><CODE>TypeParameters</CODE></A></DD></DL>"},
             //Method that uses class type parameter.
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
                 "(<A HREF=\"../pkg/TypeParameters.html\" title=\"type " +
                     "parameter in TypeParameters\">E</A>&nbsp;param)"},
             //Method type parameter section.
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
-                "<STRONG>Type Parameters:</STRONG><DD><CODE>T</CODE> - This is the first " +
-                    "type parameter.<DD><CODE>V</CODE> - This is the second type " +
+                "<STRONG>Type Parameters:</STRONG></DT><DD><CODE>T</CODE> - This is the first " +
+                    "type parameter.</DD><DD><CODE>V</CODE> - This is the second type " +
                     "parameter."},
             //Signature of method with type parameters
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
@@ -117,17 +118,17 @@
             //Signature of subclass that has type parameters.
             {BUG_ID + FS + "pkg" + FS + "TypeParameterSubClass.html",
                 "public class <STRONG>TypeParameterSubClass&lt;T extends java.lang.String&gt;" +
-                "</STRONG><DT>extends <A HREF=\"../pkg/TypeParameterSuperClass.html\" " +
+                "</STRONG>" + NL + "extends <A HREF=\"../pkg/TypeParameterSuperClass.html\" " +
                 "title=\"class in pkg\">TypeParameterSuperClass</A>&lt;T&gt;"},
 
             //Interface generic parameter substitution
             //Signature of subclass that has type parameters.
             {BUG_ID + FS + "pkg" + FS + "TypeParameters.html",
-                "<STRONG>All Implemented Interfaces:</STRONG> <DD><A HREF=\"../pkg/SubInterface.html\" title=\"interface in pkg\">SubInterface</A>&lt;E&gt;, <A HREF=\"../pkg/SuperInterface.html\" title=\"interface in pkg\">SuperInterface</A>&lt;E&gt;</DD>"},
+                "<STRONG>All Implemented Interfaces:</STRONG></DT> <DD><A HREF=\"../pkg/SubInterface.html\" title=\"interface in pkg\">SubInterface</A>&lt;E&gt;, <A HREF=\"../pkg/SuperInterface.html\" title=\"interface in pkg\">SuperInterface</A>&lt;E&gt;</DD>"},
             {BUG_ID + FS + "pkg" + FS + "SuperInterface.html",
-                "<STRONG>All Known Subinterfaces:</STRONG> <DD><A HREF=\"../pkg/SubInterface.html\" title=\"interface in pkg\">SubInterface</A>&lt;V&gt;</DD>"},
+                "<STRONG>All Known Subinterfaces:</STRONG></DT> <DD><A HREF=\"../pkg/SubInterface.html\" title=\"interface in pkg\">SubInterface</A>&lt;V&gt;</DD>"},
             {BUG_ID + FS + "pkg" + FS + "SubInterface.html",
-                "<STRONG>All Superinterfaces:</STRONG> <DD><A HREF=\"../pkg/SuperInterface.html\" title=\"interface in pkg\">SuperInterface</A>&lt;V&gt;</DD>"},
+                "<STRONG>All Superinterfaces:</STRONG></DT> <DD><A HREF=\"../pkg/SuperInterface.html\" title=\"interface in pkg\">SuperInterface</A>&lt;V&gt;</DD>"},
 
             //=================================
             // VAR ARG TESTING
@@ -158,15 +159,17 @@
                 "public @interface <STRONG>AnnotationType</STRONG>"},
             //Make sure member summary headings are correct.
             {BUG_ID + FS + "pkg" + FS + "AnnotationType.html",
-                "<STRONG>Required Element Summary</STRONG>"},
+                "<CAPTION CLASS=\"TableCaption\">" + NL +
+                "Required Element Summary</CAPTION>"},
             {BUG_ID + FS + "pkg" + FS + "AnnotationType.html",
-                "<STRONG>Optional Element Summary</STRONG>"},
+                "<CAPTION CLASS=\"TableCaption\">" + NL +
+                "Optional Element Summary</CAPTION>"},
             //Make sure element detail heading is correct
             {BUG_ID + FS + "pkg" + FS + "AnnotationType.html",
                 "Element Detail"},
             //Make sure default annotation type value is printed when necessary.
             {BUG_ID + FS + "pkg" + FS + "AnnotationType.html",
-                "<STRONG>Default:</STRONG><DD>\"unknown\"</DD>"},
+                "<STRONG>Default:</STRONG></DT><DD>\"unknown\"</DD>"},
 
             //=================================
             // ANNOTATION TYPE USAGE TESTING
@@ -182,7 +185,8 @@
                 "<FONT SIZE=\"-1\">" +
                 "<A HREF=\"../pkg/AnnotationType.html\" title=\"annotation in pkg\">@AnnotationType</A>(<A HREF=\"../pkg/AnnotationType.html#optional()\">optional</A>=\"Class Annotation\","+NL +
                 "                <A HREF=\"../pkg/AnnotationType.html#required()\">required</A>=1994)"+NL +
-                "</FONT>public class <STRONG>AnnotationTypeUsage</STRONG><DT>extends java.lang.Object</DL>"},
+                "</FONT>public class <STRONG>AnnotationTypeUsage</STRONG>" + NL +
+                "extends java.lang.Object"},
 
             //FIELD
             {BUG_ID + FS + "pkg" + FS + "AnnotationTypeUsage.html",
@@ -270,8 +274,7 @@
             {BUG_ID + FS + "pkg1" + FS + "B.html",
                 "<PRE><FONT SIZE=\"-1\"><A HREF=\"../pkg1/A.html\" title=\"annotation in pkg1\">@A</A>"},
             {BUG_ID + FS + "pkg1" + FS + "B.html",
-                "</FONT>public interface <STRONG>B</STRONG></DL>" + NL +
-                    "</PRE>"},
+                "</FONT>public interface <STRONG>B</STRONG></PRE>"},
 
 
             //==============================================================
@@ -286,39 +289,57 @@
 
             //ClassUseTest1: <T extends Foo & Foo2>
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
-                 "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" " +
+                     "title=\"class in pkg2\">Foo</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
                 "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest1.html\" title=\"class in pkg2\">ClassUseTest1&lt;T extends Foo & Foo2&gt;</A></STRONG></CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" " +
+                     "title=\"class in pkg2\">Foo</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
                 "<TD><CODE><STRONG>ClassUseTest1.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest1.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo.html\" " +
+                     "title=\"class in pkg2\">Foo</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo.html",
                 "<A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A>&lt;<A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A>&gt;</CODE></FONT></TD>"
             },
 
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> declared as <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> declared as <A HREF=\"../../pkg2/ParamTest.html\" " +
+                     "title=\"class in pkg2\">ParamTest</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
                 "<A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A>&lt;<A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A>&gt;</CODE></FONT></TD>"
             },
 
            {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo2.html",
-            "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo2.html\" title=\"interface in pkg2\">Foo2</A></FONT></TH>"
+                    "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                    "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                    "</A> with type parameters of type <A HREF=\"../../pkg2/Foo2.html\" " +
+                    "title=\"interface in pkg2\">Foo2</A></CAPTION>"
            },
            {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo2.html",
             "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest1.html\" title=\"class in pkg2\">ClassUseTest1&lt;T extends Foo & Foo2&gt;</A></STRONG></CODE>"
            },
            {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo2.html",
-               "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo2.html\" title=\"interface in pkg2\">Foo2</A></FONT></TH>"
+                    "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                    "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                    "</A> with type parameters of type <A HREF=\"../../pkg2/Foo2.html\" " +
+                    "title=\"interface in pkg2\">Foo2</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo2.html",
                "<TD><CODE><STRONG>ClassUseTest1.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest1.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
@@ -326,44 +347,66 @@
 
             //ClassUseTest2: <T extends ParamTest<Foo3>>
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
-              "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" " +
+                     "title=\"class in pkg2\">ParamTest</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
               "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest2.html\" title=\"class in pkg2\">ClassUseTest2&lt;T extends ParamTest&lt;<A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A>&gt;&gt;</A></STRONG></CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
-              "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" " +
+                     "title=\"class in pkg2\">ParamTest</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
               "<TD><CODE><STRONG>ClassUseTest2.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest2.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
-              "<TH ALIGN=\"left\" COLSPAN=\"2\">Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> declared as <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Fields in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> declared as <A HREF=\"../../pkg2/ParamTest.html\" " +
+                     "title=\"class in pkg2\">ParamTest</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
               "<A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A>&lt;<A HREF=\"../../pkg2/Foo.html\" title=\"class in pkg2\">Foo</A>&gt;</CODE></FONT></TD>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
-              "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest.html\" " +
+                     "title=\"class in pkg2\">ParamTest</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest.html",
               "&lt;T extends <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A>&lt;<A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A>&gt;&gt;"
             },
 
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo3.html\" " +
+                     "title=\"class in pkg2\">Foo3</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
                 "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest2.html\" title=\"class in pkg2\">ClassUseTest2&lt;T extends ParamTest&lt;<A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A>&gt;&gt;</A></STRONG></CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo3.html\" " +
+                     "title=\"class in pkg2\">Foo3</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
                 "<TD><CODE><STRONG>ClassUseTest2.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest2.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> that return types with arguments of type <A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> that return types with arguments of type " +
+                     "<A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">" +
+                     "Foo3</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo3.html",
                 "&lt;T extends <A HREF=\"../../pkg2/ParamTest.html\" title=\"class in pkg2\">ParamTest</A>&lt;<A HREF=\"../../pkg2/Foo3.html\" title=\"class in pkg2\">Foo3</A>&gt;&gt;"
@@ -371,38 +414,61 @@
 
             //ClassUseTest3: <T extends ParamTest2<List<? extends Foo4>>>
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">ParamTest2</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type " +
+                     "<A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">" +
+                     "ParamTest2</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
                 "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html\" title=\"class in pkg2\">ClassUseTest3&lt;T extends ParamTest2&lt;java.util.List&lt;? extends Foo4&gt;&gt;&gt;</A></STRONG></CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">ParamTest2</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type " +
+                     "<A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">" +
+                     "ParamTest2</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
                 "<TD><CODE><STRONG>ClassUseTest3.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">ParamTest2</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type " +
+                     "<A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">" +
+                     "ParamTest2</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "ParamTest2.html",
                 "&lt;T extends <A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">ParamTest2</A>&lt;java.util.List&lt;? extends <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A>&gt;&gt;&gt;"
             },
 
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Classes in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type " +
+                     "<A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">" +
+                     "Foo4</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
                 "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html\" title=\"class in pkg2\">ClassUseTest3&lt;T extends ParamTest2&lt;java.util.List&lt;? extends Foo4&gt;&gt;&gt;</A></STRONG></CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type parameters of type <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type parameters of type <A HREF=\"../../pkg2/Foo4.html\" " +
+                     "title=\"class in pkg2\">Foo4</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
                 "<TD><CODE><STRONG>ClassUseTest3.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html#method(T)\">method</A></STRONG>(T&nbsp;t)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> that return types with arguments of type <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A></FONT></TH>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Methods in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> that return types with arguments of type " +
+                     "<A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">" +
+                     "Foo4</A></CAPTION>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
                 "&lt;T extends <A HREF=\"../../pkg2/ParamTest2.html\" title=\"class in pkg2\">ParamTest2</A>&lt;java.util.List&lt;? extends <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A>&gt;&gt;&gt;"
@@ -410,81 +476,147 @@
 
             //Type parameters in constructor and method args
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Method parameters in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type arguments of type <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
-                "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
-                "<TD><CODE><STRONG>ClassUseTest3.</STRONG><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html#method(java.util.Set)\">method</A></STRONG>(java.util.Set&lt;<A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A>&gt;&nbsp;p)</CODE>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Method parameters in <A HREF=\"../../pkg2/package-summary.html\">pkg2" +
+                     "</A> with type arguments of type <A HREF=\"../../pkg2/Foo4.html\" " +
+                     "title=\"class in pkg2\">Foo4</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Modifier and Type" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Method and Description</TH>" + NL +
+                     "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
+                     "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
+                     "<TD><CODE><STRONG>ClassUseTest3.</STRONG><STRONG>" +
+                     "<A HREF=\"../../pkg2/ClassUseTest3.html#method(java.util.Set)\">" +
+                     "method</A></STRONG>(java.util.Set&lt;<A HREF=\"../../pkg2/Foo4.html\" " +
+                     "title=\"class in pkg2\">Foo4</A>&gt;&nbsp;p)</CODE>"
             },
             {BUG_ID + FS + "pkg2" + FS + "class-use" + FS + "Foo4.html",
-                "<TH ALIGN=\"left\" COLSPAN=\"2\">Constructor parameters in <A HREF=\"../../pkg2/package-summary.html\">pkg2</A> with type arguments of type <A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html#ClassUseTest3(java.util.Set)\">ClassUseTest3</A></STRONG>(java.util.Set&lt;<A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">Foo4</A>&gt;&nbsp;p)</CODE>"
+                     "<CAPTION CLASS=\"TableSubCaption\">" + NL +
+                     "Constructor parameters in <A HREF=\"../../pkg2/package-summary.html\">" +
+                     "pkg2</A> with type arguments of type <A HREF=\"../../pkg2/Foo4.html\" " +
+                     "title=\"class in pkg2\">Foo4</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Constructor and Description" +
+                     "</TH>" + NL + "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD><CODE><STRONG><A HREF=\"../../pkg2/ClassUseTest3.html#ClassUseTest3" +
+                     "(java.util.Set)\">ClassUseTest3</A></STRONG>(java.util.Set&lt;" +
+                     "<A HREF=\"../../pkg2/Foo4.html\" title=\"class in pkg2\">" +
+                     "Foo4</A>&gt;&nbsp;p)</CODE>"
             },
 
             //=================================
             // Annotatation Type Usage
             //=================================
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "<FONT SIZE=\"+2\">" + NL +
-                "Packages with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD><A HREF=\"../../pkg/package-summary.html\"><STRONG>pkg</STRONG></A></TD>"
+                     "Packages with annotations of type " +
+                     "<A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Package" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Description</TH>" + NL + "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD><A HREF=\"../../pkg/package-summary.html\"><STRONG>pkg" +
+                     "</STRONG></A></TD>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Classes in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
-                "<CODE>&nbsp;class</CODE></FONT></TD>" + NL +
-                "<TD><CODE><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html\" title=\"class in pkg\">AnnotationTypeUsage</A></STRONG></CODE>"
+                     "Classes in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Modifier and Type" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Class and Description</TH>" + NL +
+                     "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
+                     "<CODE>&nbsp;class</CODE></FONT></TD>" + NL +
+                     "<TD><CODE><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html\" " +
+                     "title=\"class in pkg\">AnnotationTypeUsage</A></STRONG></CODE>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Fields in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
-                "<CODE>&nbsp;int</CODE></FONT></TD>" + NL +
-                "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html#field\">field</A></STRONG></CODE>"
+                     "Fields in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Modifier and Type" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Field and Description</TH>" + NL +
+                     "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
+                     "<CODE>&nbsp;int</CODE></FONT></TD>" + NL +
+                     "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG>" +
+                     "<A HREF=\"../../pkg/AnnotationTypeUsage.html#field\">field" +
+                     "</A></STRONG></CODE>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Methods in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
-                "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
-                "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html#method()\">method</A></STRONG>()</CODE>"
+                     "Methods in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Modifier and Type" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Method and Description</TH>" + NL +
+                     "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
+                     "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
+                     "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG>" +
+                     "<A HREF=\"../../pkg/AnnotationTypeUsage.html#method()\">" +
+                     "method</A></STRONG>()</CODE>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Method parameters in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
-                "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
-                "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html#methodWithParams(int, int)\">methodWithParams</A></STRONG>(int&nbsp;documented," + NL +
-                "                 int&nbsp;undocmented)</CODE>"
+                     "Method parameters in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Modifier and Type" +
+                     "</TH>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Method and Description</TH>" + NL +
+                     "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><FONT SIZE=\"-1\">" + NL +
+                     "<CODE>&nbsp;void</CODE></FONT></TD>" + NL +
+                     "<TD><CODE><STRONG>AnnotationTypeUsage.</STRONG><STRONG>" +
+                     "<A HREF=\"../../pkg/AnnotationTypeUsage.html#methodWithParams" +
+                     "(int, int)\">methodWithParams</A></STRONG>(int&nbsp;documented," + NL +
+                     "                 int&nbsp;undocmented)</CODE>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Constructors in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD><CODE><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html#AnnotationTypeUsage()\">AnnotationTypeUsage</A></STRONG>()</CODE>"
+                     "Constructors in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Constructor and Description" +
+                     "</TH>" + NL + "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD><CODE><STRONG><A HREF=\"../../pkg/" +
+                     "AnnotationTypeUsage.html#AnnotationTypeUsage()\">" +
+                     "AnnotationTypeUsage</A></STRONG>()</CODE>"
             },
 
             {BUG_ID + FS + "pkg" + FS + "class-use" + FS + "AnnotationType.html",
-                "Constructor parameters in <A HREF=\"../../pkg/package-summary.html\">pkg</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" title=\"annotation in pkg\">AnnotationType</A></FONT></TH>" + NL +
-                "</TR>" + NL +
-                "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
-                "<TD><CODE><STRONG><A HREF=\"../../pkg/AnnotationTypeUsage.html#AnnotationTypeUsage(int, int)\">AnnotationTypeUsage</A></STRONG>(int&nbsp;documented," + NL +
-                "                    int&nbsp;undocmented)</CODE>"
+                     "Constructor parameters in <A HREF=\"../../pkg/package-summary.html\">pkg" +
+                     "</A> with annotations of type <A HREF=\"../../pkg/AnnotationType.html\" " +
+                     "title=\"annotation in pkg\">AnnotationType</A></CAPTION>" + NL +
+                     "<TR>" + NL + "<TH CLASS=\"TableHeader\" SCOPE=\"col\"" +
+                     " NOWRAP>Constructor and Description" +
+                     "</TH>" + NL + "</TR>" + NL +
+                     "<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">" + NL +
+                     "<TD><CODE><STRONG><A HREF=\"../../pkg/" +
+                     "AnnotationTypeUsage.html#AnnotationTypeUsage(int, int)\">" +
+                     "AnnotationTypeUsage</A></STRONG>(int&nbsp;documented," + NL +
+                     "                    int&nbsp;undocmented)</CODE>"
             },
 
             //=================================
@@ -525,7 +657,7 @@
             "<FONT SIZE=\"-1\">" + NL +
             "<A HREF=\"../pkg/AnnotationTypeUndocumented.html\" title=\"annotation in pkg\">@AnnotationTypeUndocumented</A>(<A HREF=\"../pkg/AnnotationType.html#optional\">optional</A>=\"Class Annotation\"," + NL +
             "                <A HREF=\"../pkg/AnnotationType.html#required\">required</A>=1994)" + NL +
-            "</FONT>public class <STRONG>AnnotationTypeUsage</STRONG><DT>extends java.lang.Object</DL>"},
+            "</FONT>public class <STRONG>AnnotationTypeUsage</STRONG></DT><DT>extends java.lang.Object</DT></DL>"},
 
         //FIELD
         {BUG_ID + FS + "pkg" + FS + "AnnotationTypeUsage.html",
--- a/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethods.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethods.java	Fri Apr 10 13:05:12 2009 -0700
@@ -40,11 +40,11 @@
     private static final String[][] TEST = {
         //The public method should be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
 
         //The public method in different package should be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"}
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"}
     };
 
     private static final String[][] NEGATED_TEST = {
@@ -52,20 +52,20 @@
         //The package private method should be overriden since the base and sub class are in the same
         //package.  However, the link should not show up because the package private methods are not documented.
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
 
         //The private method in should not be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The private method in different package should not be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The package private method should not be overriden since the base and sub class are in
         //different packages.
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
     };
 
     private static final String[] ARGS =
--- a/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethodsWithPackageFlag.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethodsWithPackageFlag.java	Fri Apr 10 13:05:12 2009 -0700
@@ -40,32 +40,32 @@
     private static final String[][] TEST = {
         //The public method should be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
 
         //The public method in different package should be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
 
         //The package private method should be overriden since the base and sub class are in the same
         //package.
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
     };
 
     private static final String[][] NEGATED_TEST = {
 
         //The private method in should not be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The private method in different package should not be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The package private method should not be overriden since the base and sub class are in
         //different packages.
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
     };
 
     private static final String[] ARGS =
--- a/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethodsWithPrivateFlag.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testOverridenMethods/TestOverridenPrivateMethodsWithPrivateFlag.java	Fri Apr 10 13:05:12 2009 -0700
@@ -40,32 +40,32 @@
     private static final String[][] TEST = {
         //The public method should be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
 
         //The package private method should be overriden since the base and sub class are in the same
         //package.
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"},
 
         //The public method in different package should be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#publicMethod"},
     };
 
     private static final String[][] NEGATED_TEST = {
 
         //The private method in should not be overriden
         {BUG_ID + FS + "pkg1" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The private method in different package should not be overriden
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#privateMethod"},
 
         //The package private method should not be overriden since the base and sub class are in
         //different packages.
         {BUG_ID + FS + "pkg2" + FS + "SubClass.html",
-         "Overrides:</STRONG><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
+         "Overrides:</STRONG></DT><DD><CODE><A HREF=\"../pkg1/BaseClass.html#packagePrivateMethod"}
 
 
     };
--- a/langtools/test/com/sun/javadoc/testParamTaglet/TestParamTaglet.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testParamTaglet/TestParamTaglet.java	Fri Apr 10 13:05:12 2009 -0700
@@ -48,12 +48,12 @@
     private static final String[][] TEST = {
         //Regular param tags.
         {BUG_ID + FS + "pkg" + FS + "C.html",
-            "<STRONG>Parameters:</STRONG><DD><CODE>param1</CODE> - testing 1 2 3." +
+            "<STRONG>Parameters:</STRONG></DT><DD><CODE>param1</CODE> - testing 1 2 3.</DD>" +
                 "<DD><CODE>param2</CODE> - testing 1 2 3."
         },
         //Param tags that don't match with any real parameters.
         {BUG_ID + FS + "pkg" + FS + "C.html",
-            "<STRONG>Parameters:</STRONG><DD><CODE><I>p1</I></CODE> - testing 1 2 3." +
+            "<STRONG>Parameters:</STRONG></DT><DD><CODE><I>p1</I></CODE> - testing 1 2 3.</DD>" +
                 "<DD><CODE><I>p2</I></CODE> - testing 1 2 3."
         },
         //{@inherit} doc misuse does not cause doclet to throw exception.
--- a/langtools/test/com/sun/javadoc/testPrivateClasses/TestPrivateClasses.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testPrivateClasses/TestPrivateClasses.java	Fri Apr 10 13:05:12 2009 -0700
@@ -96,11 +96,11 @@
 
         //Make sure implemented interfaces from private superclass are inherited
         {BUG_ID + "-1" + FS + "pkg" + FS + "PublicInterface.html",
-            "<STRONG>All Known Implementing Classes:</STRONG> <DD><A HREF=\"../pkg/PublicChild.html\" " +
+            "<STRONG>All Known Implementing Classes:</STRONG></DT> <DD><A HREF=\"../pkg/PublicChild.html\" " +
             "title=\"class in pkg\">PublicChild</A>"},
 
         {BUG_ID + "-1" + FS + "pkg" + FS + "PublicChild.html",
-            "<STRONG>All Implemented Interfaces:</STRONG> <DD><A HREF=\"../pkg/PublicInterface.html\" " +
+            "<STRONG>All Implemented Interfaces:</STRONG></DT> <DD><A HREF=\"../pkg/PublicInterface.html\" " +
             "title=\"interface in pkg\">PublicInterface</A>"},
 
         //Generic interface method test.
@@ -174,18 +174,18 @@
         },
         // Should document that a method overrides method from private class.
        {BUG_ID + "-2" + FS + "pkg" + FS + "PublicChild.html",
-            "<STRONG>Overrides:</STRONG><DD><CODE>" +
+            "<STRONG>Overrides:</STRONG></DT><DD><CODE>" +
             "<A HREF=\"../pkg/PrivateParent.html#methodOverridenFromParent(char[], int, T, V, java.util.List)\">" +
             "methodOverridenFromParent</A></CODE> in class <CODE>" +
             "<A HREF=\"../pkg/PrivateParent.html\" title=\"class in pkg\">" +
-            "PrivateParent</A></CODE></DL>"},
+            "PrivateParent</A></CODE></DD>" + NL + "</DL>"},
        // Should document that a method is specified by private interface.
        {BUG_ID + "-2" + FS + "pkg" + FS + "PublicChild.html",
-            "<STRONG>Specified by:</STRONG><DD><CODE>" +
+            "<STRONG>Specified by:</STRONG></DT><DD><CODE>" +
             "<A HREF=\"../pkg/PrivateInterface.html#methodInterface(int)\">" +
             "methodInterface</A></CODE> in interface <CODE>" +
             "<A HREF=\"../pkg/PrivateInterface.html\" title=\"interface in pkg\">" +
-            "PrivateInterface</A></CODE></DL>" + NL + "</DD>"},
+            "PrivateInterface</A></CODE></DD>" + NL + "</DL>" + NL + "</DD>"},
        // Method inheritence from non-public superinterface.
        {BUG_ID + "-2" + FS + "pkg" + FS + "PublicInterface.html",
             "Methods inherited from interface " +
@@ -209,12 +209,12 @@
 
       //Make sure implemented interfaces from private superclass are inherited
       {BUG_ID + "-2" + FS + "pkg" + FS + "PublicInterface.html",
-        "<STRONG>All Known Implementing Classes:</STRONG> <DD><A HREF=\"../pkg/PrivateParent.html\" " +
+        "<STRONG>All Known Implementing Classes:</STRONG></DT> <DD><A HREF=\"../pkg/PrivateParent.html\" " +
         "title=\"class in pkg\">PrivateParent</A>, " +
         "<A HREF=\"../pkg/PublicChild.html\" title=\"class in pkg\">PublicChild</A>"},
 
       {BUG_ID + "-2" + FS + "pkg" + FS + "PublicChild.html",
-        "<STRONG>All Implemented Interfaces:</STRONG> <DD><A HREF=\"../pkg/PrivateInterface.html\" " +
+        "<STRONG>All Implemented Interfaces:</STRONG></DT> <DD><A HREF=\"../pkg/PrivateInterface.html\" " +
         "title=\"interface in pkg\">PrivateInterface</A>, " +
         "<A HREF=\"../pkg/PublicInterface.html\" title=\"interface in pkg\">" +
         "PublicInterface</A>"},
@@ -226,7 +226,7 @@
             "<CODE><A HREF=\"../pkg2/I.html#hello(T)\">I</A></CODE></STRONG>"},
 
       {BUG_ID + "-2" + FS + "pkg2" + FS + "C.html",
-            "<STRONG>Specified by:</STRONG><DD><CODE><A HREF=\"../pkg2/I.html#hello(T)\">" +
+            "<STRONG>Specified by:</STRONG></DT><DD><CODE><A HREF=\"../pkg2/I.html#hello(T)\">" +
             "hello</A></CODE> in interface <CODE><A HREF=\"../pkg2/I.html\" " +
             "title=\"interface in pkg2\">I</A>"},
     };
--- a/langtools/test/com/sun/javadoc/testSerializedFormDeprecationInfo/TestSerializedFormDeprecationInfo.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testSerializedFormDeprecationInfo/TestSerializedFormDeprecationInfo.java	Fri Apr 10 13:05:12 2009 -0700
@@ -41,39 +41,39 @@
     // Test for normal run of javadoc. The serialized-form.html should
     // display the inline comments, tags and deprecation information if any.
     private static final String[][] TEST_CMNT_DEPR = {
-        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><DL>" + NL + NL +
-                 "<DT><STRONG>Throws:</STRONG>" + NL + "<DD><CODE>" +
-                 "java.io.IOException</CODE><DT><STRONG>See Also:</STRONG>" +
-                 "<DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
-                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD>" + NL +
-                 "</DL>" + NL + "</DL>"},
+        {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><DL>" + NL +
+                 "<DT><STRONG>Throws:</STRONG></DT>" + NL + "<DD><CODE>" +
+                 "java.io.IOException</CODE></DD><DT><STRONG>See Also:</STRONG>" +
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
         {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
-                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
-                 " 1.5, replaced by" + NL +
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version " +
+                 "1.5, replaced by" + NL +
                  " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
-                 "<CODE>setUndecorated(boolean)</CODE></A>.</I>" +
+                 "<CODE>setUndecorated(boolean)</CODE></A>.</I></DD>" +
                  "<DD>This field indicates whether the C1 is undecorated." + NL +
-                 "<P>" + NL + "<DT><DD>&nbsp;<DL>" + NL +
-                 "<DT><STRONG>Since:</STRONG></DT>" + NL +
+                 "<P>" + NL + "</DD>" + NL + "<DD>&nbsp;</DD>" + NL +
+                 "<DD><DL>" + NL + "<DT><STRONG>Since:</STRONG></DT>" + NL +
                  "  <DD>1.4</DD>" + NL + "<DT><STRONG>See Also:</STRONG>" +
-                 "<DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
-                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DL>" + NL +
-                 "</DL>"},
+                 "</DT><DD><A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
+                 "<CODE>C1.setUndecorated(boolean)</CODE></A></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
         {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
                  "<DD><STRONG>Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
                  " 1.5, replaced by" + NL +
                  " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
                  "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
-                 "<DD>Reads the object stream." + NL + "<P>" + NL +
-                 "<DD><DL>" + NL + NL + "<DT><STRONG>Throws:" +
-                 "</STRONG>" + NL + "<DD><CODE><code>" +
-                 "IOException</code></CODE>" + NL +
-                 "<DD><CODE>java.io.IOException</CODE></DD>" + NL +
-                 "</DL>" + NL + "</DL>"},
+                 "</DD><DD>Reads the object stream." + NL + "<P>" + NL +
+                 "</DD>" + NL + "<DD><DL>" + NL + "<DT><STRONG>Throws:" +
+                 "</STRONG></DT>" + NL + "<DD><CODE><code>" +
+                 "IOException</code></CODE></DD>" + NL +
+                 "<DD><CODE>java.io.IOException</CODE></DD></DL>" + NL +
+                 "</DD>" + NL + "</DL>"},
         {BUG_ID + FS + "serialized-form.html", "<DL>" + NL +
-                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;<DD>" +
-                 "The name for this class." + NL + "<P>" + NL +
-                 "<DT><DD>&nbsp;<DL>" + NL + "</DL>" + NL + "</DL>"}};
+                 "<DD><STRONG>Deprecated.</STRONG>&nbsp;</DD><DD>" +
+                 "The name for this class." + NL + "<P>" + NL + "</DD>" + NL +
+                 "<DD>&nbsp;</DD>" + NL + "</DL>"}};
 
     // Test with -nocomment option. The serialized-form.html should
     // not display the inline comments and tags but should display deprecation
@@ -83,16 +83,16 @@
                  "undecorated</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
                  "Deprecated.</STRONG>&nbsp;<I>As of JDK version 1.5, replaced by" + NL +
                  " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\"><CODE>" +
-                 "setUndecorated(boolean)</CODE></A>.</I></DL>"},
+                 "setUndecorated(boolean)</CODE></A>.</I></DD></DL>"},
         {BUG_ID + FS + "serialized-form.html", "<DL>" + NL + "<DD><STRONG>" +
                  "Deprecated.</STRONG>&nbsp;<I>As of JDK version" +
                  " 1.5, replaced by" + NL +
                  " <A HREF=\"pkg1/C1.html#setUndecorated(boolean)\">" +
                  "<CODE>setUndecorated(boolean)</CODE></A>.</I>" + NL + "<P>" + NL +
-                 "</DL>"},
+                 "</DD></DL>"},
         {BUG_ID + FS + "serialized-form.html", "<PRE>" + NL + "int <STRONG>" +
                  "publicKey</STRONG></PRE>" + NL + "<DL>" + NL + "<DD><STRONG>" +
-                 "Deprecated.</STRONG>&nbsp;</DL>"}};
+                 "Deprecated.</STRONG>&nbsp;</DD></DL>"}};
 
     // Test with -nodeprecated option. The serialized-form.html should
     // ignore the -nodeprecated tag and display the deprecation info. This
--- a/langtools/test/com/sun/javadoc/testSummaryHeading/TestSummaryHeading.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testSummaryHeading/TestSummaryHeading.java	Fri Apr 10 13:05:12 2009 -0700
@@ -46,7 +46,8 @@
 
     //Input for string search tests.
     private static final String[][] TEST = {
-        {BUG_ID + FS + "C.html",  "<STRONG>Method Summary</STRONG>"}
+        {BUG_ID + FS + "C.html",  "<CAPTION CLASS=\"TableCaption\">" + NL +
+                 "Method Summary</CAPTION>"}
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
 
--- a/langtools/test/com/sun/javadoc/testThrowsTag/TestThrowsTag.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/com/sun/javadoc/testThrowsTag/TestThrowsTag.java	Fri Apr 10 13:05:12 2009 -0700
@@ -46,14 +46,14 @@
     //Input for string search tests.
     private static final String[][] TEST = {
         {BUG_ID + FS + "pkg" + FS + "C.html",
-            "<DD><CODE><A HREF=\"../pkg/T1.html\" title=\"class in pkg\">T1</A></CODE> - the first throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T2.html\" title=\"class in pkg\">T2</A></CODE> - the second throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T3.html\" title=\"class in pkg\">T3</A></CODE> - the third throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T4.html\" title=\"class in pkg\">T4</A></CODE> - the fourth throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T5.html\" title=\"class in pkg\">T5</A></CODE> - the first inherited throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T6.html\" title=\"class in pkg\">T6</A></CODE> - the second inherited throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T7.html\" title=\"class in pkg\">T7</A></CODE> - the third inherited throws tag." + NL +
-            "<DD><CODE><A HREF=\"../pkg/T8.html\" title=\"class in pkg\">T8</A></CODE> - the fourth inherited throws tag."
+            "<DD><CODE><A HREF=\"../pkg/T1.html\" title=\"class in pkg\">T1</A></CODE> - the first throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T2.html\" title=\"class in pkg\">T2</A></CODE> - the second throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T3.html\" title=\"class in pkg\">T3</A></CODE> - the third throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T4.html\" title=\"class in pkg\">T4</A></CODE> - the fourth throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T5.html\" title=\"class in pkg\">T5</A></CODE> - the first inherited throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T6.html\" title=\"class in pkg\">T6</A></CODE> - the second inherited throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T7.html\" title=\"class in pkg\">T7</A></CODE> - the third inherited throws tag.</DD>" + NL +
+            "<DD><CODE><A HREF=\"../pkg/T8.html\" title=\"class in pkg\">T8</A></CODE> - the fourth inherited throws tag.</DD>"
         },
     };
     private static final String[][] NEGATED_TEST = NO_TEST;
--- a/langtools/test/tools/javac/6668794/badClass/Test.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/6668794/badClass/Test.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/Diagnostics/6799605/T6799605.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug     6799605
+ * @summary Basic/Raw formatters should use type/symbol printer instead of toString()
+ * @author  mcimadamore
+ * @compile/fail/ref=T6799605.out -XDrawDiagnostics  T6799605.java
+ */
+
+class T6799605<X> {
+
+    <T extends T6799605<T>> void m(T6799605<T> x1) {}
+    <T> void m(T6799605<T> x1, T6799605<T> x2) {}
+    <T> void m(T6799605<T> x1, T6799605<T> x2, T6799605<T> x3) {}
+
+    void test(T6799605<?> t) {
+        m(t);
+        m(t, t);
+        m(t, t, t);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/Diagnostics/6799605/T6799605.out	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,4 @@
+T6799605.java:39:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>, kindname.class, T6799605<X>
+T6799605.java:40:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>, kindname.class, T6799605<X>
+T6799605.java:41:9: compiler.err.cant.resolve.location.args: kindname.method, m, , T6799605<compiler.misc.type.captureof: 1, ?>,T6799605<compiler.misc.type.captureof: 2, ?>,T6799605<compiler.misc.type.captureof: 3, ?>, kindname.class, T6799605<X>
+3 errors
--- a/langtools/test/tools/javac/NestedInnerClassNames.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/NestedInnerClassNames.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,15 +1,15 @@
-NestedInnerClassNames.java:16:5: compiler.err.already.defined: NestedInnerClassNames, unnamed package
+NestedInnerClassNames.java:16:5: compiler.err.already.defined: NestedInnerClassNames, compiler.misc.unnamed.package
 NestedInnerClassNames.java:23:9: compiler.err.already.defined: NestedInnerClassNames.foo, NestedInnerClassNames
-NestedInnerClassNames.java:34:9: compiler.err.already.defined: NestedInnerClassNames, unnamed package
+NestedInnerClassNames.java:34:9: compiler.err.already.defined: NestedInnerClassNames, compiler.misc.unnamed.package
 NestedInnerClassNames.java:45:9: compiler.err.already.defined: NestedInnerClassNames.baz, NestedInnerClassNames
 NestedInnerClassNames.java:46:13: compiler.err.already.defined: NestedInnerClassNames.baz.baz, NestedInnerClassNames.baz
 NestedInnerClassNames.java:59:9: compiler.err.already.defined: NestedInnerClassNames.foo$bar, NestedInnerClassNames
 NestedInnerClassNames.java:76:13: compiler.err.already.defined: NestedInnerClassNames.$bar, NestedInnerClassNames
 NestedInnerClassNames.java:90:13: compiler.err.already.defined: NestedInnerClassNames.bar$bar.bar, NestedInnerClassNames.bar$bar
 NestedInnerClassNames.java:109:5: compiler.err.duplicate.class: NestedInnerClassNames.foo.foo
-NestedInnerClassNames.java:19:9: compiler.err.already.defined: NestedInnerClassNames, unnamed package
+NestedInnerClassNames.java:19:9: compiler.err.already.defined: NestedInnerClassNames, compiler.misc.unnamed.package
 NestedInnerClassNames.java:28:13: compiler.err.already.defined: foo, m2()
-NestedInnerClassNames.java:40:13: compiler.err.already.defined: NestedInnerClassNames, unnamed package
+NestedInnerClassNames.java:40:13: compiler.err.already.defined: NestedInnerClassNames, compiler.misc.unnamed.package
 NestedInnerClassNames.java:52:13: compiler.err.already.defined: baz, m4()
 NestedInnerClassNames.java:53:17: compiler.err.already.defined: baz.baz, baz
 NestedInnerClassNames.java:67:13: compiler.err.already.defined: foo$bar, m5()
--- a/langtools/test/tools/javac/T6241723.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/T6241723.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,6 +1,6 @@
-T6241723.java:21:5: compiler.warn.has.been.deprecated: A1, unnamed package
+T6241723.java:21:5: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
 T6241723.java:23:7: compiler.warn.has.been.deprecated: A2.A21, A2
-T6241723.java:26:5: compiler.warn.has.been.deprecated: Z1, unnamed package
+T6241723.java:26:5: compiler.warn.has.been.deprecated: Z1, compiler.misc.unnamed.package
 T6241723.java:28:7: compiler.warn.has.been.deprecated: Z2.Z21, Z2
 - compiler.err.warnings.and.werror
 1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/cast/6467183/T6467183a.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @author mcimadamore
+ * @bug     6467183
+ * @summary
+ * @compile/fail/ref=T6467183a.out -Xlint:unchecked -Werror -XDrawDiagnostics T6467183a.java
+ */
+
+class T6467183a<T> {
+
+    class A<S> {}
+    class B extends A<Integer> {}
+    class C<X> extends A<X> {}
+
+    void cast1(B b) {
+        Object o = (A<T>)b;
+    }
+
+    void cast2(B b) {
+        Object o = (A<? extends Number>)b;
+    }
+
+    void cast3(A<Integer> a) {
+        Object o = (C<? extends Number>)a;
+    }
+
+    void cast4(A<Integer> a) {
+        Object o = (C<? extends Integer>)a;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/cast/6467183/T6467183a.out	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,6 @@
+T6467183a.java:39:26: compiler.warn.prob.found.req: (compiler.misc.unchecked.cast.to.type), T6467183a<T>.B, T6467183a<T>.A<T>
+T6467183a.java:47:41: compiler.warn.prob.found.req: (compiler.misc.unchecked.cast.to.type), T6467183a<T>.A<java.lang.Integer>, T6467183a<T>.C<? extends java.lang.Number>
+T6467183a.java:51:42: compiler.warn.prob.found.req: (compiler.misc.unchecked.cast.to.type), T6467183a<T>.A<java.lang.Integer>, T6467183a<T>.C<? extends java.lang.Integer>
+- compiler.err.warnings.and.werror
+1 error
+3 warnings
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/cast/6467183/T6467183b.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @author mcimadamore
+ * @bug     6467183
+ * @summary
+ * @compile/fail -Xlint:unchecked -Werror -XDrawDiagnostics T6467183b.java
+ */
+
+class T6665356b<T> {
+
+    class A<S> {}
+    class B<X> extends A<X> {}
+
+    void cast(A<? extends Number> a) {
+        Object o = (B<? extends Integer>)a;
+    }
+}
--- a/langtools/test/tools/javac/cast/6558559/T6558559a.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/cast/6558559/T6558559a.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/cast/6558559/T6558559b.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/cast/6558559/T6558559b.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/cast/6665356/T6665356.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/cast/6665356/T6665356.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/depDocComment/SuppressDeprecation.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/depDocComment/SuppressDeprecation.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,4 +1,4 @@
-SuppressDeprecation.java:130:17: compiler.warn.has.been.deprecated: X, unnamed package
+SuppressDeprecation.java:130:17: compiler.warn.has.been.deprecated: X, compiler.misc.unnamed.package
 SuppressDeprecation.java:82:10: compiler.warn.has.been.deprecated: g(), T
 SuppressDeprecation.java:83:14: compiler.warn.has.been.deprecated: g(), T
 SuppressDeprecation.java:84:9: compiler.warn.has.been.deprecated: var, T
--- a/langtools/test/tools/javac/generics/6723444/T6723444.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/generics/6723444/T6723444.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/generics/6729401/T6729401.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/generics/6729401/T6729401.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/generics/rare/6665356/T6665356.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/generics/rare/6665356/T6665356.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/typevars/6804733/T6804733.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6804733
+ * @summary javac generates spourious diagnostics for ill-formed type-variable bounds
+ * @author  mcimadamore
+ * @compile/fail/ref=T6804733.out -XDrawDiagnostics T6804733.java
+ */
+
+import java.util.ArrayList;
+class T6804733<S> extends ArrayList<S> {
+    <T extends S & S> void m() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/typevars/6804733/T6804733.out	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,2 @@
+T6804733.java:34:20: compiler.err.type.var.may.not.be.followed.by.other.bounds
+1 error
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test3.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test3.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,3 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
-A.java:10:21: compiler.warn.has.been.deprecated: A1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+A.java:10:21: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
 2 warnings
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test3b.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test3b.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,3 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
 - compiler.note.deprecated.filename.additional: A.java
 1 warning
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,7 +1,7 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
-A.java:10:21: compiler.warn.has.been.deprecated: A1, unnamed package
-B.java:11:9: compiler.warn.has.been.deprecated: B1, unnamed package
-B.java:11:21: compiler.warn.has.been.deprecated: B1, unnamed package
-B.java:12:9: compiler.warn.has.been.deprecated: B1, unnamed package
-B.java:12:22: compiler.warn.has.been.deprecated: B1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+A.java:10:21: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+B.java:11:9: compiler.warn.has.been.deprecated: B1, compiler.misc.unnamed.package
+B.java:11:21: compiler.warn.has.been.deprecated: B1, compiler.misc.unnamed.package
+B.java:12:9: compiler.warn.has.been.deprecated: B1, compiler.misc.unnamed.package
+B.java:12:22: compiler.warn.has.been.deprecated: B1, compiler.misc.unnamed.package
 6 warnings
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4b.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4b.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,3 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
 - compiler.note.deprecated.plural.additional
 1 warning
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4c.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4c.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,4 +1,4 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
-A.java:10:21: compiler.warn.has.been.deprecated: A1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+A.java:10:21: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
 - compiler.note.deprecated.filename: B.java
 2 warnings
--- a/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4d.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/mandatoryWarnings/deprecated/Test4d.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
-A.java:10:9: compiler.warn.has.been.deprecated: A1, unnamed package
-A.java:10:21: compiler.warn.has.been.deprecated: A1, unnamed package
-B.java:11:9: compiler.warn.has.been.deprecated: B1, unnamed package
+A.java:10:9: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+A.java:10:21: compiler.warn.has.been.deprecated: A1, compiler.misc.unnamed.package
+B.java:11:9: compiler.warn.has.been.deprecated: B1, compiler.misc.unnamed.package
 - compiler.note.deprecated.filename.additional: B.java
 3 warnings
--- a/langtools/test/tools/javac/positions/T6253161.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/positions/T6253161.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,2 +1,2 @@
-T6253161.java:19:62: compiler.warn.missing.SVUID: <anonymous T6253161$1$1>
+T6253161.java:19:62: compiler.warn.missing.SVUID: compiler.misc.anonymous.class: T6253161$1$1
 1 warning
--- a/langtools/test/tools/javac/positions/T6253161a.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/positions/T6253161a.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,2 +1,2 @@
-T6253161a.java:19:62: compiler.warn.missing.SVUID: <anonymous T6253161a$1$1>
+T6253161a.java:19:62: compiler.warn.missing.SVUID: compiler.misc.anonymous.class: T6253161a$1$1
 1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/environment/round/Foo.java	Fri Apr 10 13:05:12 2009 -0700
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+@AnnotatedElementInfo(annotationName="AnnotatedElementInfo",
+                      expectedSize=1,
+                      names="Foo")
+public class Foo {}
--- a/langtools/test/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 6397298 6400986 6425592 6449798 6453386 6508401
+ * @bug 6397298 6400986 6425592 6449798 6453386 6508401 6498938
  * @summary Tests that getElementsAnnotatedWith works properly.
  * @author  Joseph D. Darcy
  * @compile TestElementsAnnotatedWith.java
@@ -31,16 +31,22 @@
  * @compile -processor TestElementsAnnotatedWith -proc:only SurfaceAnnotations.java
  * @compile -processor TestElementsAnnotatedWith -proc:only BuriedAnnotations.java
  * @compile -processor TestElementsAnnotatedWith -proc:only Part1.java Part2.java
+ * @compile -processor TestElementsAnnotatedWith -proc:only C2.java
+ * @compile -processor TestElementsAnnotatedWith -proc:only Foo.java
+ * @compile -XD-d=. Foo.java
  * @compile -processor TestElementsAnnotatedWith -proc:only TestElementsAnnotatedWith.java
- * @compile -processor TestElementsAnnotatedWith -proc:only C2.java
  */
 
 import java.lang.annotation.Annotation;
+import java.io.*;
 import java.util.Collections;
 import java.util.Set;
 import java.util.HashSet;
+import java.util.List;
+import java.util.ArrayList;
 import java.util.Arrays;
 import javax.annotation.processing.*;
+import javax.tools.*;
 import javax.lang.model.SourceVersion;
 import javax.lang.model.element.*;
 import javax.lang.model.util.*;
@@ -120,6 +126,9 @@
                 System.err.println("AnnotatedElementInfo: " + annotatedElementInfo);
                 throw new RuntimeException();
             }
+
+            if("TestElementsAnnotatedWith".equals(firstType.getSimpleName().toString()))
+               writeClassFile(); // Start another round to test class file input
         } else {
             // If processing is over without an error, the specified
             // elements should be empty so an empty set should be returned.
@@ -161,6 +170,37 @@
         } catch(IllegalArgumentException iae) {}
     }
 
+    /*
+     * Hack alert!  The class file read below is generated by the
+     * "@compile -XD-d=. Foo.java" directive above.  This sneakily
+     * overrides the output location to the current directory where a
+     * subsequent @compile can read the file.  This could be improved
+     * if either a new directive like @process accepted class file
+     * arguments (the javac command accepts such arguments but
+     * @compile does not) or the test.src and test.classes properties
+     * were set to be read with @compile jobs.
+     */
+    private void writeClassFile() {
+        try {
+            Filer filer = processingEnv.getFiler();
+            JavaFileObject jfo = filer.createClassFile("Foo");
+            OutputStream os = jfo.openOutputStream();
+            // Copy the bytes over
+            System.out.println((new File(".")).getAbsolutePath());
+            InputStream io = new BufferedInputStream(new FileInputStream(new File(".", "Foo.class")));
+            int datum = io.read();
+            while(datum != -1) {
+                os.write(datum);
+                datum = io.read();
+            }
+            os.close();
+        } catch (IOException io) {
+            throw new RuntimeException(io);
+        }
+
+
+    }
+
     @Override
     public SourceVersion getSupportedSourceVersion() {
         return SourceVersion.latest();
--- a/langtools/test/tools/javac/processing/model/testgetallmembers/Main.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/processing/model/testgetallmembers/Main.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/warnings/Deprecation.lintAll.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/warnings/Deprecation.lintAll.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,3 @@
-Deprecation.java:18:24: compiler.warn.has.been.deprecated: Deprecation, unnamed package
-Deprecation.java:55:24: compiler.warn.has.been.deprecated: Deprecation, unnamed package
+Deprecation.java:18:24: compiler.warn.has.been.deprecated: Deprecation, compiler.misc.unnamed.package
+Deprecation.java:55:24: compiler.warn.has.been.deprecated: Deprecation, compiler.misc.unnamed.package
 2 warnings
--- a/langtools/test/tools/javac/warnings/Deprecation.lintDeprecation.out	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javac/warnings/Deprecation.lintDeprecation.out	Fri Apr 10 13:05:12 2009 -0700
@@ -1,3 +1,3 @@
-Deprecation.java:18:24: compiler.warn.has.been.deprecated: Deprecation, unnamed package
-Deprecation.java:55:24: compiler.warn.has.been.deprecated: Deprecation, unnamed package
+Deprecation.java:18:24: compiler.warn.has.been.deprecated: Deprecation, compiler.misc.unnamed.package
+Deprecation.java:55:24: compiler.warn.has.been.deprecated: Deprecation, compiler.misc.unnamed.package
 2 warnings
--- a/langtools/test/tools/javadoc/6176978/T6176978.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javadoc/6176978/T6176978.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javadoc/6176978/X.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javadoc/6176978/X.java	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javap/T4884240.java	Mon Mar 09 15:32:10 2009 -0700
+++ b/langtools/test/tools/javap/T4884240.java	Fri Apr 10 13:05:12 2009 -0700
@@ -16,7 +16,7 @@
  *
  * 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-15301 USA.
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
--- a/make/Defs-internal.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/make/Defs-internal.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1995-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/make/jdk-rules.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/make/jdk-rules.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # 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 @@
 	  $(MAKE) $(JDK_CLOBBER_TARGETS) $(JDK_BUILD_ARGUMENTS) ; )
 
 jdk-sanity::
-	@( $(CD) $(JDK_TOPDIR)/make && \
+	( $(CD) $(JDK_TOPDIR)/make && \
 	  $(MAKE) sanity HOTSPOT_IMPORT_CHECK=false $(JDK_BUILD_ARGUMENTS) ; )
 
 compare-images: compare-image
--- a/make/jprt.config	Mon Mar 09 15:32:10 2009 -0700
+++ b/make/jprt.config	Fri Apr 10 13:05:12 2009 -0700
@@ -1,7 +1,7 @@
 #!echo "This is not a shell script"
 #############################################################################
 #
-# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -358,6 +358,13 @@
     ALT_SPONSOR2DIR=C:/sponsor_binaries 
     export ALT_SPONSOR2DIR
 
+    # JPRT systems can never run msival2.exe, set this to avoid them
+    SKIP_MSIVAL2=true
+    export SKIP_MSIVAL2
+    # Not easy to do
+    SKIP_COMPARE_IMAGES=true
+    export SKIP_COMPARE_IMAGES
+
 fi
 
 # Export PATH setting
--- a/make/jprt.gmk	Mon Mar 09 15:32:10 2009 -0700
+++ b/make/jprt.gmk	Fri Apr 10 13:05:12 2009 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright 2006-2008 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 2006-2009 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
 JPRT_ARCHIVE_BUNDLE=$(ABS_OUTPUTDIR)/$(DEFAULT_BUILD_FLAVOR)-bundle.zip
 JPRT_ARCHIVE_INSTALL_BUNDLE=$(ABS_OUTPUTDIR)/$(DEFAULT_BUILD_FLAVOR)-install-bundle.zip
 
-jprt_build_product:  all_product_build
+jprt_build_product:  sanity all_product_build
 	( $(CD) $(OUTPUTDIR)/j2sdk-image && \
 	  $(ZIPEXE) -q -r $(JPRT_ARCHIVE_BUNDLE) . )
 ifdef HAVE_JPRT_SAVE_BUNDLES