changeset 1230:e3b4eb55a696

Merge
author lana
date Wed, 08 Apr 2009 15:40:56 -0700
parents a33222e53611 d1c43d1f5676
children e61d93fc8ed1
files make/common/shared/Compiler.gmk make/jprt.config src/share/classes/sun/misc/JavaIODeleteOnExitAccess.java
diffstat 124 files changed, 4657 insertions(+), 2950 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Thu Apr 02 10:16:53 2009 -0700
+++ b/.hgtags	Wed Apr 08 15:40:56 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/THIRD_PARTY_README	Thu Apr 02 10:16:53 2009 -0700
+++ b/THIRD_PARTY_README	Wed Apr 08 15:40:56 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/make/com/sun/jmx/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/com/sun/jmx/Makefile	Wed Apr 08 15:40:56 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/make/common/Defs-linux.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/Defs-linux.gmk	Wed Apr 08 15:40:56 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/make/common/Defs-solaris.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/Defs-solaris.gmk	Wed Apr 08 15:40:56 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/make/common/Defs-windows.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/Defs-windows.gmk	Wed Apr 08 15:40:56 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/make/common/Defs.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/Defs.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Compiler-gcc.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Compiler-gcc.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Compiler-msvc.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Compiler-msvc.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Compiler-sun.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Compiler-sun.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Compiler.gmk	Thu Apr 02 10:16:53 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/make/common/shared/Defs-java.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Defs-java.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Defs-solaris.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Defs-solaris.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Defs-versions.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Defs-windows.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Defs-windows.gmk	Wed Apr 08 15:40:56 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)
+  _NEEDS_MSVCRNN = true
+else
+  ifeq ($(VS2008),)
+    _NEEDS_MSVCRNN = false
+  else
+    _NEEDS_MSVCRNN = true
+  endif
+endif
 
-  # 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)/system32
-    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)
-  
+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/make/common/shared/Defs.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Defs.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Platform.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Platform.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Sanity-Settings.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Sanity-Settings.gmk	Wed Apr 08 15:40:56 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/make/common/shared/Sanity.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/common/shared/Sanity.gmk	Wed Apr 08 15:40:56 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/make/docs/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/docs/Makefile	Wed Apr 08 15:40:56 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/make/java/fdlibm/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/java/fdlibm/Makefile	Wed Apr 08 15:40:56 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/make/java/java/FILES_java.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/java/java/FILES_java.gmk	Wed Apr 08 15:40:56 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/make/java/management/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/java/management/Makefile	Wed Apr 08 15:40:56 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/make/java/nio/FILES_java.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/java/nio/FILES_java.gmk	Wed Apr 08 15:40:56 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/make/java/redist/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/java/redist/Makefile	Wed Apr 08 15:40:56 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/make/javax/management/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/javax/management/Makefile	Wed Apr 08 15:40:56 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/make/javax/swing/beaninfo/SwingBeans.gmk	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/javax/swing/beaninfo/SwingBeans.gmk	Wed Apr 08 15:40:56 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/make/jdk_generic_profile.sh	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/jdk_generic_profile.sh	Wed Apr 08 15:40:56 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/make/jprt.config	Thu Apr 02 10:16:53 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/make/jprt.properties	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/jprt.properties	Wed Apr 08 15:40:56 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/make/sun/management/Makefile	Thu Apr 02 10:16:53 2009 -0700
+++ b/make/sun/management/Makefile	Wed Apr 08 15:40:56 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/src/share/classes/com/sun/servicetag/resources/register.html	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/com/sun/servicetag/resources/register.html	Wed Apr 08 15:40:56 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/src/share/classes/com/sun/servicetag/resources/register_ja.html	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/com/sun/servicetag/resources/register_ja.html	Wed Apr 08 15:40:56 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/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html	Wed Apr 08 15:40:56 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/src/share/classes/java/io/Console.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/io/Console.java	Wed Apr 08 15:40:56 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/src/share/classes/java/io/DeleteOnExitHook.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/io/DeleteOnExitHook.java	Wed Apr 08 15:40:56 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/src/share/classes/java/io/File.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/io/File.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/ApplicationShutdownHooks.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/ApplicationShutdownHooks.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/Class.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/Class.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/Shutdown.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/Shutdown.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/StringCoding.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/StringCoding.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/System.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/System.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/Thread.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/Thread.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/reflect/Constructor.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/reflect/Constructor.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/reflect/Field.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/reflect/Field.java	Wed Apr 08 15:40:56 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/src/share/classes/java/lang/reflect/Method.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/lang/reflect/Method.java	Wed Apr 08 15:40:56 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/src/share/classes/java/net/SocketPermission.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/net/SocketPermission.java	Wed Apr 08 15:40:56 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/src/share/classes/java/nio/file/SecureDirectoryStream.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/nio/file/SecureDirectoryStream.java	Wed Apr 08 15:40:56 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/src/share/classes/java/security/Permission.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/security/Permission.java	Wed Apr 08 15:40:56 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/src/share/classes/java/util/ArrayList.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/util/ArrayList.java	Wed Apr 08 15:40:56 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/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java	Wed Apr 08 15:40:56 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/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java	Wed Apr 08 15:40:56 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/src/share/classes/java/util/regex/Matcher.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/util/regex/Matcher.java	Wed Apr 08 15:40:56 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/src/share/classes/java/util/regex/Pattern.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/java/util/regex/Pattern.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/launcher/LauncherHelper.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/launcher/LauncherHelper.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/management/Agent.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/management/Agent.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/misc/ClassLoaderUtil.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/ClassLoaderUtil.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/misc/FloatingDecimal.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/FloatingDecimal.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/misc/JavaIOAccess.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/JavaIOAccess.java	Wed Apr 08 15:40:56 2009 -0700
@@ -29,6 +29,5 @@
 
 public interface JavaIOAccess {
     public Console console();
-    public Runnable consoleRestoreHook();
     public Charset charset();
 }
--- a/src/share/classes/sun/misc/JavaIODeleteOnExitAccess.java	Thu Apr 02 10:16:53 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/src/share/classes/sun/misc/JavaLangAccess.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/JavaLangAccess.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/misc/SharedSecrets.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/misc/SharedSecrets.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/nio/cs/ArrayDecoder.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/nio/cs/ArrayEncoder.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/nio/cs/ISO_8859_1.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/nio/cs/ISO_8859_1.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/nio/cs/SingleByte.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/nio/cs/SingleByte.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/nio/cs/US_ASCII.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/nio/cs/US_ASCII.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/reflect/annotation/AnnotationParser.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/jgss/spnego/NegTokenInit.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/jgss/spnego/NegTokenInit.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/krb5/Realm.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/krb5/Realm.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/pkcs11/P11Key.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/pkcs11/P11Key.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/provider/SeedGenerator.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/provider/SeedGenerator.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/provider/certpath/OCSPResponse.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/provider/certpath/PKIXMasterCertPathValidator.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/provider/certpath/PKIXMasterCertPathValidator.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/tools/KeyTool.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/tools/KeyTool.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/x509/AuthorityInfoAccessExtension.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/x509/AuthorityInfoAccessExtension.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/x509/CertAndKeyGen.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/x509/CertAndKeyGen.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/x509/OCSPNoCheckExtension.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/x509/OIDMap.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/x509/OIDMap.java	Wed Apr 08 15:40:56 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/src/share/classes/sun/security/x509/PKIXExtensions.java	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/classes/sun/security/x509/PKIXExtensions.java	Wed Apr 08 15:40:56 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/src/share/lib/security/java.policy	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/lib/security/java.policy	Wed Apr 08 15:40:56 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/src/share/native/java/util/zip/zip_util.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/java/util/zip/zip_util.c	Wed Apr 08 15:40:56 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/src/share/native/java/util/zip/zip_util.h	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/java/util/zip/zip_util.h	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Wed Apr 08 15:40:56 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);
+    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 ;
 }
@@ -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/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Wed Apr 08 15:40:56 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/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Thu Apr 02 10:16:53 2009 -0700
+++ b/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Wed Apr 08 15:40:56 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)
+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)
-{
-    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)) {</