6812738: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes with PCKS11 provider
authorvaleriep
Tue, 03 Mar 2009 19:50:59 -0800
changeset 2180 9994f4f08a59
parent 2173 519bbd41590c
child 2181 4b9176c37982
6812738: SSL stress test with GF leads to 32 bit max process size in less than 5 minutes with PCKS11 provider Summary: Removed finalize() and add more error handling to native code Reviewed-by: vinnie
jdk/src/share/classes/sun/security/pkcs11/P11Key.java
jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java
jdk/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_general.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c
jdk/src/share/native/sun/security/pkcs11/wrapper/p11_util.c
jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h
--- a/jdk/src/share/classes/sun/security/pkcs11/P11Key.java	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11Key.java	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 package sun.security.pkcs11;
 
 import java.io.*;
+import java.lang.ref.*;
 import java.math.BigInteger;
 import java.util.*;
 
@@ -67,9 +68,6 @@
     // type of key, one of (PUBLIC, PRIVATE, SECRET)
     final String type;
 
-    // session in which the key was created, relevant for session objects
-    final Session session;
-
     // token instance
     final Token token;
 
@@ -85,10 +83,12 @@
     // flags indicating whether the key is a token object, sensitive, extractable
     final boolean tokenObject, sensitive, extractable;
 
+    // weak reference notification clean up for session keys
+    private final SessionKeyRef sessionKeyRef;
+
     P11Key(String type, Session session, long keyID, String algorithm,
             int keyLength, CK_ATTRIBUTE[] attributes) {
         this.type = type;
-        this.session = session;
         this.token = session.token;
         this.keyID = keyID;
         this.algorithm = algorithm;
@@ -111,7 +111,9 @@
         this.sensitive = sensitive;
         this.extractable = extractable;
         if (tokenObject == false) {
-            session.addObject();
+            sessionKeyRef = new SessionKeyRef(this, keyID, session);
+        } else {
+            sessionKeyRef = null;
         }
     }
 
@@ -236,24 +238,6 @@
         }
     }
 
-    protected void finalize() throws Throwable {
-        if (tokenObject || (token.isValid() == false)) {
-            super.finalize();
-            return;
-        }
-        Session newSession = null;
-        try {
-            newSession = token.getOpSession();
-            token.p11.C_DestroyObject(newSession.id(), keyID);
-        } catch (PKCS11Exception e) {
-            // ignore
-        } finally {
-            token.releaseSession(newSession);
-            session.removeObject();
-            super.finalize();
-        }
-    }
-
     private final static CK_ATTRIBUTE[] A0 = new CK_ATTRIBUTE[0];
 
     private static CK_ATTRIBUTE[] getAttributes(Session session, long keyID,
@@ -1055,5 +1039,65 @@
                 + "\n  parameters: " + params;
         }
     }
+}
 
+final class SessionKeyRef extends WeakReference<P11Key>
+    implements Comparable<SessionKeyRef> {
+    private static ReferenceQueue<P11Key> refQueue =
+        new ReferenceQueue<P11Key>();
+    private static Set<SessionKeyRef> refList =
+        Collections.synchronizedSortedSet(new TreeSet<SessionKeyRef>());
+
+    static ReferenceQueue<P11Key> referenceQueue() {
+        return refQueue;
+    }
+
+    static final private int MAX_ITERATIONS = 2;
+
+    private static void drainRefQueueBounded() {
+        int iterations = 0;
+        while (iterations < MAX_ITERATIONS) {
+            SessionKeyRef next = (SessionKeyRef) refQueue.poll();
+            if (next != null) next.dispose();
+            ++iterations;
+        }
+    }
+
+    // handle to the native key
+    private long keyID;
+    private Session session;
+
+    SessionKeyRef(P11Key key , long keyID, Session session) {
+        super(key, refQueue);
+        this.keyID = keyID;
+        this.session = session;
+        this.session.addObject();
+        refList.add(this);
+        // TBD: run at some interval and not every time?
+        drainRefQueueBounded();
+    }
+
+    void dispose() {
+        refList.remove(this);
+        if (session.token.isValid()) {
+            Session newSession = null;
+            try {
+                newSession = session.token.getOpSession();
+                session.token.p11.C_DestroyObject(newSession.id(), keyID);
+            } catch (PKCS11Exception e) {
+                // ignore
+            } finally {
+                session.token.releaseSession(newSession);
+                session.removeObject();
+            }
+        }
+    }
+
+    public int compareTo(SessionKeyRef other) {
+        if (this.keyID == other.keyID) {
+            return 0;
+        } else {
+            return (this.keyID < other.keyID) ? -1 : 1;
+        }
+    }
 }
--- a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -191,7 +191,9 @@
                 throw new InvalidKeyException
                                 ("Unwrap has to be used with private keys");
             }
-            encrypt = false;
+            // No further setup needed for C_Unwrap(). We'll initialize later
+            // if we can't use C_Unwrap().
+            return;
         } else {
             throw new InvalidKeyException("Unsupported mode: " + opmode);
         }
@@ -452,7 +454,7 @@
                 long keyID = token.p11.C_UnwrapKey(s.id(),
                         new CK_MECHANISM(mechanism), p11Key.keyID, wrappedKey,
                         attributes);
-                return P11Key.secretKey(session, keyID, algorithm, 48 << 3,
+                return P11Key.secretKey(s, keyID, algorithm, 48 << 3,
                         attributes);
             } catch (PKCS11Exception e) {
                 throw new InvalidKeyException("unwrap() failed", e);
@@ -461,6 +463,7 @@
             }
         }
         // XXX implement unwrap using C_Unwrap() for all keys
+        implInit(Cipher.DECRYPT_MODE, p11Key);
         if (wrappedKey.length > maxInputSize) {
             throw new InvalidKeyException("Key is too long for unwrapping");
         }
--- a/jdk/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11SecretKeyFactory.java	Tue Mar 03 19:50:59 2009 -0800
@@ -151,7 +151,7 @@
                         session = token.getObjSession();
                         long newKeyID = token.p11.C_CopyObject(session.id(),
                                 p11Key.keyID, extraAttrs);
-                        p11Key = (P11Key) (P11Key.secretKey(p11Key.session,
+                        p11Key = (P11Key) (P11Key.secretKey(session,
                                 newKeyID, p11Key.algorithm, p11Key.keyLength,
                                 extraAttrs));
                     } catch (PKCS11Exception p11e) {
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -89,21 +89,24 @@
 
     /* load CK_DATE class */
     jDateClass = (*env)->FindClass(env, CLASS_DATE);
-    assert(jDateClass != 0);
+    if (jDateClass == NULL) { return NULL; }
 
     /* load CK_DATE constructor */
     jCtrId = (*env)->GetMethodID(env, jDateClass, "<init>", "([C[C[C)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jYear = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->year), 4);
+    if (jYear == NULL) { return NULL; }
     jMonth = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->month), 2);
+    if (jMonth == NULL) { return NULL; }
     jDay = ckCharArrayToJCharArray(env, (CK_CHAR_PTR)(ckpDate->day), 2);
+    if (jDay == NULL) { return NULL; }
 
     /* create new CK_DATE object */
     jDateObject =
       (*env)->NewObject(env, jDateClass, jCtrId, jYear, jMonth, jDay);
-    assert(jDateObject != 0);
+    if (jDateObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jDateClass);
@@ -131,11 +134,11 @@
 
     /* load CK_VERSION class */
     jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
-    assert(jVersionClass != 0);
+    if (jVersionClass == NULL) { return NULL; }
 
     /* load CK_VERSION constructor */
     jCtrId = (*env)->GetMethodID(env, jVersionClass, "<init>", "(II)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep both fields */
     jMajor = ckpVersion->major;
@@ -144,7 +147,7 @@
     /* create new CK_VERSION object */
     jVersionObject =
       (*env)->NewObject(env, jVersionClass, jCtrId, jMajor, jMinor);
-    assert(jVersionObject != 0);
+    if (jVersionObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jVersionClass);
@@ -171,11 +174,11 @@
 
     /* load CK_SESSION_INFO class */
     jSessionInfoClass = (*env)->FindClass(env, CLASS_SESSION_INFO);
-    assert(jSessionInfoClass != 0);
+    if (jSessionInfoClass == NULL) { return NULL; }
 
     /* load CK_SESSION_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jSessionInfoClass, "<init>", "(JJJJ)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jSlotID = ckULongToJLong(ckpSessionInfo->slotID);
@@ -187,7 +190,7 @@
     jSessionInfoObject =
       (*env)->NewObject(env, jSessionInfoClass, jCtrId, jSlotID, jState,
                         jFlags, jDeviceError);
-    assert(jSessionInfoObject != 0);
+    if (jSessionInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jSessionInfoClass);
@@ -211,20 +214,21 @@
     jobject jPValue = NULL;
 
     jAttributeClass = (*env)->FindClass(env, CLASS_ATTRIBUTE);
-    assert(jAttributeClass != 0);
+    if (jAttributeClass == NULL) { return NULL; }
 
     /* load CK_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jAttributeClass, "<init>", "(JLjava/lang/Object;)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep both fields */
     jType = ckULongToJLong(ckpAttribute->type);
     jPValue = ckAttributeValueToJObject(env, ckpAttribute);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     /* create new CK_ATTRIBUTE object */
     jAttributeObject =
       (*env)->NewObject(env, jAttributeClass, jCtrId, jType, jPValue);
-    assert(jAttributeObject != 0);
+    if (jAttributeObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jAttributeClass);
@@ -252,23 +256,27 @@
         return NULL;
     }
 
-    /* allocate memory for CK_VERSION pointer */
-    ckpVersion = (CK_VERSION_PTR) malloc(sizeof(CK_VERSION));
-
     /* get CK_VERSION class */
     jVersionClass = (*env)->GetObjectClass(env, jVersion);
-    assert(jVersionClass != 0);
+    if (jVersionClass == NULL) { return NULL; }
 
     /* get Major */
     jFieldID = (*env)->GetFieldID(env, jVersionClass, "major", "B");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jMajor = (*env)->GetByteField(env, jVersion, jFieldID);
-    ckpVersion->major = jByteToCKByte(jMajor);
 
     /* get Minor */
     jFieldID = (*env)->GetFieldID(env, jVersionClass, "minor", "B");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jMinor = (*env)->GetByteField(env, jVersion, jFieldID);
+
+    /* allocate memory for CK_VERSION pointer */
+    ckpVersion = (CK_VERSION_PTR) malloc(sizeof(CK_VERSION));
+    if (ckpVersion == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
+    ckpVersion->major = jByteToCKByte(jMajor);
     ckpVersion->minor = jByteToCKByte(jMinor);
 
     return ckpVersion ;
@@ -292,18 +300,36 @@
     jchar *jTempChars;
     CK_ULONG i;
 
-    /* allocate memory for CK_DATE pointer */
-    ckpDate = (CK_DATE *) malloc(sizeof(CK_DATE));
+    if (jDate == NULL) {
+        return NULL;
+    }
 
     /* get CK_DATE class */
     jDateClass = (*env)->FindClass(env, CLASS_DATE);
-    assert(jDateClass != 0);
+    if (jDateClass == NULL) { return NULL; }
 
     /* get Year */
     jFieldID = (*env)->GetFieldID(env, jDateClass, "year", "[C");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return NULL; }
     jYear = (*env)->GetObjectField(env, jDate, jFieldID);
 
+    /* get Month */
+    jFieldID = (*env)->GetFieldID(env, jDateClass, "month", "[C");
+    if (jFieldID == NULL) { return NULL; }
+    jMonth = (*env)->GetObjectField(env, jDate, jFieldID);
+
+    /* get Day */
+    jFieldID = (*env)->GetFieldID(env, jDateClass, "day", "[C");
+    if (jFieldID == NULL) { return NULL; }
+    jDay = (*env)->GetObjectField(env, jDate, jFieldID);
+
+    /* allocate memory for CK_DATE pointer */
+    ckpDate = (CK_DATE *) malloc(sizeof(CK_DATE));
+    if (ckpDate == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
+
     if (jYear == NULL) {
         ckpDate->year[0] = 0;
         ckpDate->year[1] = 0;
@@ -312,43 +338,66 @@
     } else {
         ckLength = (*env)->GetArrayLength(env, jYear);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jYear, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->year[i] = jCharToCKChar(jTempChars[i]);
         }
         free(jTempChars);
     }
 
-    /* get Month */
-    jFieldID = (*env)->GetFieldID(env, jDateClass, "month", "[C");
-    assert(jFieldID != 0);
-    jMonth = (*env)->GetObjectField(env, jDate, jFieldID);
-
     if (jMonth == NULL) {
         ckpDate->month[0] = 0;
         ckpDate->month[1] = 0;
     } else {
         ckLength = (*env)->GetArrayLength(env, jMonth);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jMonth, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->month[i] = jCharToCKChar(jTempChars[i]);
         }
         free(jTempChars);
     }
 
-    /* get Day */
-    jFieldID = (*env)->GetFieldID(env, jDateClass, "day", "[C");
-    assert(jFieldID != 0);
-    jDay = (*env)->GetObjectField(env, jDate, jFieldID);
-
     if (jDay == NULL) {
         ckpDate->day[0] = 0;
         ckpDate->day[1] = 0;
     } else {
         ckLength = (*env)->GetArrayLength(env, jDay);
         jTempChars = (jchar*) malloc((ckLength) * sizeof(jchar));
+        if (jTempChars == NULL) {
+            free(ckpDate);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         (*env)->GetCharArrayRegion(env, jDay, 0, ckLength, jTempChars);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpDate);
+            free(jTempChars);
+            return NULL;
+        }
+
         for (i = 0; (i < ckLength) && (i < 4) ; i++) {
             ckpDate->day[i] = jCharToCKChar(jTempChars[i]);
         }
@@ -374,23 +423,25 @@
     jlong jType;
     jobject jPValue;
 
+    // TBD: what if jAttribute == NULL?!
+
     TRACE0("\nDEBUG: jAttributeToCKAttribute");
     /* get CK_ATTRIBUTE class */
     TRACE0(", getting attribute object class");
     jAttributeClass = (*env)->GetObjectClass(env, jAttribute);
-    assert(jAttributeClass != 0);
+    if (jAttributeClass == NULL) { return ckAttribute; }
 
     /* get type */
     TRACE0(", getting type field");
     jFieldID = (*env)->GetFieldID(env, jAttributeClass, "type", "J");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return ckAttribute; }
     jType = (*env)->GetLongField(env, jAttribute, jFieldID);
     TRACE1(", type=0x%X", jType);
 
     /* get pValue */
     TRACE0(", getting pValue field");
     jFieldID = (*env)->GetFieldID(env, jAttributeClass, "pValue", "Ljava/lang/Object;");
-    assert(jFieldID != 0);
+    if (jFieldID == NULL) { return ckAttribute; }
     jPValue = (*env)->GetObjectField(env, jAttribute, jFieldID);
     TRACE1(", pValue=%p", jPValue);
 
@@ -417,36 +468,50 @@
 {
     // XXX don't return structs
     // XXX prefetch class and field ids
-    jclass jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    jclass jSsl3MasterKeyDeriveParamsClass;
     CK_SSL3_MASTER_KEY_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jobject jObject;
     jclass jSsl3RandomDataClass;
-    jobject jRandomInfo;
+    jobject jRandomInfo, jRIClientRandom, jRIServerRandom, jVersion;
 
     /* get RandomInfo */
-    jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3MasterKeyDeriveParamsClass, "RandomInfo", "Lsun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jRandomInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pClientRandom and ulClientRandomLength out of RandomInfo */
+    jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    if (jSsl3RandomDataClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pClientRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIClientRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pServerRandom and ulServerRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pServerRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIServerRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pVersion */
     fieldID = (*env)->GetFieldID(env, jSsl3MasterKeyDeriveParamsClass, "pVersion",  "Lsun/security/pkcs11/wrapper/CK_VERSION;");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    ckParam.pVersion = jVersionToCKVersionPtr(env, jObject);
+    if (fieldID == NULL) { return ckParam; }
+    jVersion = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.pVersion = jVersionToCKVersionPtr(env, jVersion);
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jRIClientRandom, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pVersion);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jRIServerRandom, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pVersion);
+        free(ckParam.RandomInfo.pClientRandom);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -457,27 +522,52 @@
  */
 CK_TLS_PRF_PARAMS jTlsPrfParamsToCKTlsPrfParam(JNIEnv *env, jobject jParam)
 {
-    jclass jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    jclass jTlsPrfParamsClass;
     CK_TLS_PRF_PARAMS ckParam;
     jfieldID fieldID;
-    jobject jObject;
+    jobject jSeed, jLabel, jOutput;
+
+    // TBD: what if jParam == NULL?!
 
+    /* get pSeed */
+    jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    if (jTlsPrfParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pSeed", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSeed), &(ckParam.ulSeedLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSeed = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* get pLabel */
     fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pLabel", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pLabel), &(ckParam.ulLabelLen));
+    if (fieldID == NULL) { return ckParam; }
+    jLabel = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* get pOutput */
+    fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pOutput", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jOutput = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* populate java values */
+    jByteArrayToCKByteArray(env, jSeed, &(ckParam.pSeed), &(ckParam.ulSeedLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jLabel, &(ckParam.pLabel), &(ckParam.ulLabelLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSeed);
+        return ckParam;
+    }
     ckParam.pulOutputLen = malloc(sizeof(CK_ULONG));
-
-    fieldID = (*env)->GetFieldID(env, jTlsPrfParamsClass, "pOutput", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOutput), ckParam.pulOutputLen);
+    if (ckParam.pulOutputLen == NULL) {
+        free(ckParam.pSeed);
+        free(ckParam.pLabel);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jOutput, &(ckParam.pOutput), ckParam.pulOutputLen);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSeed);
+        free(ckParam.pLabel);
+        free(ckParam.pulOutputLen);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -493,68 +583,91 @@
 {
     // XXX don't return structs
     // XXX prefetch class and field ids
-    jclass jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    jclass jSsl3KeyMatParamsClass, jSsl3RandomDataClass, jSsl3KeyMatOutClass;
     CK_SSL3_KEY_MAT_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jboolean jBoolean;
-    jobject jObject;
-    jobject jRandomInfo;
-    jobject jReturnedKeyMaterial;
-    jclass jSsl3RandomDataClass;
-    jclass jSsl3KeyMatOutClass;
+    jlong jMacSizeInBits, jKeySizeInBits, jIVSizeInBits;
+    jboolean jIsExport;
+    jobject jRandomInfo, jRIClientRandom, jRIServerRandom;
+    jobject jReturnedKeyMaterial, jRMIvClient, jRMIvServer;
     CK_ULONG ckTemp;
 
     /* get ulMacSizeInBits */
+    jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    if (jSsl3KeyMatParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulMacSizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulMacSizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMacSizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulKeySizeInBits */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulKeySizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulKeySizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKeySizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get ulIVSizeInBits */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "ulIVSizeInBits", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulIVSizeInBits = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIVSizeInBits = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get bIsExport */
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "bIsExport", "Z");
-    assert(fieldID != 0);
-    jBoolean = (*env)->GetBooleanField(env, jParam, fieldID);
-    ckParam.bIsExport = jBooleanToCKBBool(jBoolean);
+    if (fieldID == NULL) { return ckParam; }
+    jIsExport = (*env)->GetBooleanField(env, jParam, fieldID);
 
     /* get RandomInfo */
     jSsl3RandomDataClass = (*env)->FindClass(env, CLASS_SSL3_RANDOM_DATA);
+    if (jSsl3RandomDataClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "RandomInfo",  "Lsun/security/pkcs11/wrapper/CK_SSL3_RANDOM_DATA;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jRandomInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pClientRandom and ulClientRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pClientRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIClientRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pServerRandom and ulServerRandomLength out of RandomInfo */
     fieldID = (*env)->GetFieldID(env, jSsl3RandomDataClass, "pServerRandom", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jRandomInfo, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if (fieldID == NULL) { return ckParam; }
+    jRIServerRandom = (*env)->GetObjectField(env, jRandomInfo, fieldID);
 
     /* get pReturnedKeyMaterial */
     jSsl3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+    if (jSsl3KeyMatOutClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jSsl3KeyMatParamsClass, "pReturnedKeyMaterial",  "Lsun/security/pkcs11/wrapper/CK_SSL3_KEY_MAT_OUT;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jReturnedKeyMaterial = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* get pIVClient out of pReturnedKeyMaterial */
+    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVClient", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jRMIvClient = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
+
+    /* get pIVServer out of pReturnedKeyMaterial */
+    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVServer", "[B");
+    if (fieldID == NULL) { return ckParam; }
+    jRMIvServer = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
+
+    /* populate java values */
+    ckParam.ulMacSizeInBits = jLongToCKULong(jMacSizeInBits);
+    ckParam.ulKeySizeInBits = jLongToCKULong(jKeySizeInBits);
+    ckParam.ulIVSizeInBits = jLongToCKULong(jIVSizeInBits);
+    ckParam.bIsExport = jBooleanToCKBBool(jIsExport);
+    jByteArrayToCKByteArray(env, jRIClientRandom, &(ckParam.RandomInfo.pClientRandom), &(ckParam.RandomInfo.ulClientRandomLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jRIServerRandom, &(ckParam.RandomInfo.pServerRandom), &(ckParam.RandomInfo.ulServerRandomLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        return ckParam;
+    }
     /* allocate memory for pRetrunedKeyMaterial */
     ckParam.pReturnedKeyMaterial = (CK_SSL3_KEY_MAT_OUT_PTR) malloc(sizeof(CK_SSL3_KEY_MAT_OUT));
+    if (ckParam.pReturnedKeyMaterial == NULL) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return ckParam;
+    }
 
     // the handles are output params only, no need to fetch them from Java
     ckParam.pReturnedKeyMaterial->hClientMacSecret = 0;
@@ -562,17 +675,21 @@
     ckParam.pReturnedKeyMaterial->hClientKey = 0;
     ckParam.pReturnedKeyMaterial->hServerKey = 0;
 
-    /* get pIVClient out of pReturnedKeyMaterial */
-    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVClient", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pReturnedKeyMaterial->pIVClient), &ckTemp);
-
-    /* get pIVServer out of pReturnedKeyMaterial */
-    fieldID = (*env)->GetFieldID(env, jSsl3KeyMatOutClass, "pIVServer", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jReturnedKeyMaterial, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pReturnedKeyMaterial->pIVServer), &ckTemp);
+    jByteArrayToCKByteArray(env, jRMIvClient, &(ckParam.pReturnedKeyMaterial->pIVClient), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        free(ckParam.pReturnedKeyMaterial);
+        return ckParam;
+    }
+    jByteArrayToCKByteArray(env, jRMIvServer, &(ckParam.pReturnedKeyMaterial->pIVServer), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.RandomInfo.pClientRandom);
+        free(ckParam.RandomInfo.pServerRandom);
+        free(ckParam.pReturnedKeyMaterial);
+        free(ckParam.pReturnedKeyMaterial->pIVClient);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -811,7 +928,7 @@
         *ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
         *ckpLength = sizeof(CK_ULONG);
     } else {
-        /* printf("slow path jMechanismParameterToCKMechanismParameter\n"); */
+        TRACE0("\nSLOW PATH jMechanismParameterToCKMechanismParameter\n");
         jMechanismParameterToCKMechanismParameterSlow(env, jParam, ckpParamPtr, ckpLength);
     }
 }
@@ -819,40 +936,24 @@
 void jMechanismParameterToCKMechanismParameterSlow(JNIEnv *env, jobject jParam, CK_VOID_PTR *ckpParamPtr, CK_ULONG *ckpLength)
 {
     /* get all Java mechanism parameter classes */
-    jclass jVersionClass    = (*env)->FindClass(env, CLASS_VERSION);
-    jclass jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
-    jclass jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    jclass jVersionClass, jSsl3MasterKeyDeriveParamsClass, jSsl3KeyMatParamsClass;
+    jclass jTlsPrfParamsClass, jRsaPkcsOaepParamsClass, jPbeParamsClass;
+    jclass jPkcs5Pbkd2ParamsClass, jRsaPkcsPssParamsClass;
+    jclass jEcdh1DeriveParamsClass, jEcdh2DeriveParamsClass;
+    jclass jX942Dh1DeriveParamsClass, jX942Dh2DeriveParamsClass;
 
-    jclass jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
-    jclass jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
-    jclass jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
-    jclass jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
-    jclass jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
-
-    jclass jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-    jclass jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
-    jclass jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
-
+    /* get all Java mechanism parameter classes */
     TRACE0("\nDEBUG: jMechanismParameterToCKMechanismParameter");
 
-    /* first check the most common cases */
-/*
-    if (jParam == NULL) {
-        *ckpParamPtr = NULL;
-        *ckpLength = 0;
-    } else if ((*env)->IsInstanceOf(env, jParam, jByteArrayClass)) {
-        jByteArrayToCKByteArray(env, jParam, (CK_BYTE_PTR *)ckpParamPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jParam, jLongClass)) {
-        *ckpParamPtr = jLongObjectToCKULongPtr(env, jParam);
-        *ckpLength = sizeof(CK_ULONG);
-    } else if ((*env)->IsInstanceOf(env, jParam, jVersionClass)) {
-*/
+    /* most common cases, i.e. NULL/byte[]/long, are already handled by
+     * jMechanismParameterToCKMechanismParameter before calling this method.
+     */
+    jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+    if (jVersionClass == NULL) { return; }
     if ((*env)->IsInstanceOf(env, jParam, jVersionClass)) {
         /*
          * CK_VERSION used by CKM_SSL3_PRE_MASTER_KEY_GEN
          */
-
         CK_VERSION_PTR ckpParam;
 
         /* convert jParameter to CKParameter */
@@ -861,190 +962,311 @@
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_VERSION);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jSsl3MasterKeyDeriveParamsClass)) {
+    jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+    if (jSsl3MasterKeyDeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jSsl3MasterKeyDeriveParamsClass)) {
         /*
          * CK_SSL3_MASTER_KEY_DERIVE_PARAMS
          */
-
         CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR) malloc(sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jSsl3MasterKeyDeriveParamToCKSsl3MasterKeyDeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jSsl3KeyMatParamsClass)) {
+    jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+    if (jSsl3KeyMatParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jSsl3KeyMatParamsClass)) {
         /*
          * CK_SSL3_KEY_MAT_PARAMS
          */
-
         CK_SSL3_KEY_MAT_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_SSL3_KEY_MAT_PARAMS_PTR) malloc(sizeof(CK_SSL3_KEY_MAT_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jSsl3KeyMatParamToCKSsl3KeyMatParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_SSL3_KEY_MAT_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jTlsPrfParamsClass)) {
-        //
-        // CK_TLS_PRF_PARAMS
-        //
-
+    jTlsPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    if (jTlsPrfParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jTlsPrfParamsClass)) {
+        /*
+         * CK_TLS_PRF_PARAMS
+         */
         CK_TLS_PRF_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_TLS_PRF_PARAMS_PTR) malloc(sizeof(CK_TLS_PRF_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
-        // convert jParameter to CKParameter
+        /* convert jParameter to CKParameter */
         *ckpParam = jTlsPrfParamsToCKTlsPrfParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
-        // get length and pointer of parameter
+        /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_TLS_PRF_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
+    jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    if (jRsaPkcsOaepParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsOaepParamsClass)) {
         /*
          * CK_RSA_PKCS_OAEP_PARAMS
          */
-
         CK_RSA_PKCS_OAEP_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_RSA_PKCS_OAEP_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_OAEP_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jRsaPkcsOaepParamToCKRsaPkcsOaepParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_RSA_PKCS_OAEP_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jPbeParamsClass)) {
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jPbeParamsClass)) {
         /*
          * CK_PBE_PARAMS
          */
-
         CK_PBE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_PBE_PARAMS_PTR) malloc(sizeof(CK_PBE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jPbeParamToCKPbeParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_PBE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jPkcs5Pbkd2ParamsClass)) {
+    jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    if (jPkcs5Pbkd2ParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jPkcs5Pbkd2ParamsClass)) {
         /*
          * CK_PKCS5_PBKD2_PARAMS
          */
-
         CK_PKCS5_PBKD2_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_PKCS5_PBKD2_PARAMS_PTR) malloc(sizeof(CK_PKCS5_PBKD2_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_PKCS5_PBKD2_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsPssParamsClass)) {
+    jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    if (jRsaPkcsPssParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jRsaPkcsPssParamsClass)) {
         /*
          * CK_RSA_PKCS_PSS_PARAMS
          */
-
         CK_RSA_PKCS_PSS_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_RSA_PKCS_PSS_PARAMS_PTR) malloc(sizeof(CK_RSA_PKCS_PSS_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jRsaPkcsPssParamToCKRsaPkcsPssParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_RSA_PKCS_PSS_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jEcdh1DeriveParamsClass)) {
+    jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    if (jEcdh1DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jEcdh1DeriveParamsClass)) {
         /*
          * CK_ECDH1_DERIVE_PARAMS
          */
-
         CK_ECDH1_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_ECDH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH1_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jEcdh1DeriveParamToCKEcdh1DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_ECDH1_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jEcdh2DeriveParamsClass)) {
+    jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    if (jEcdh2DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jEcdh2DeriveParamsClass)) {
         /*
          * CK_ECDH2_DERIVE_PARAMS
          */
-
         CK_ECDH2_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_ECDH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_ECDH2_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jEcdh2DeriveParamToCKEcdh2DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_ECDH2_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jX942Dh1DeriveParamsClass)) {
+    jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    if (jX942Dh1DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jX942Dh1DeriveParamsClass)) {
         /*
          * CK_X9_42_DH1_DERIVE_PARAMS
          */
-
         CK_X9_42_DH1_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_X9_42_DH1_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH1_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jX942Dh1DeriveParamToCKX942Dh1DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_X9_42_DH1_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else if ((*env)->IsInstanceOf(env, jParam, jX942Dh2DeriveParamsClass)) {
+    jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    if (jX942Dh2DeriveParamsClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jParam, jX942Dh2DeriveParamsClass)) {
         /*
          * CK_X9_42_DH2_DERIVE_PARAMS
          */
-
         CK_X9_42_DH2_DERIVE_PARAMS_PTR ckpParam;
 
         ckpParam = (CK_X9_42_DH2_DERIVE_PARAMS_PTR) malloc(sizeof(CK_X9_42_DH2_DERIVE_PARAMS));
+        if (ckpParam == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
 
         /* convert jParameter to CKParameter */
         *ckpParam = jX942Dh2DeriveParamToCKX942Dh2DeriveParam(env, jParam);
+        if ((*env)->ExceptionCheck(env)) {
+            free(ckpParam);
+            return;
+        }
 
         /* get length and pointer of parameter */
         *ckpLength = sizeof(CK_X9_42_DH2_DERIVE_PARAMS);
         *ckpParamPtr = ckpParam;
+        return;
+    }
 
-    } else {
-        /* if everything faild up to here */
-        /* try if the parameter is a primitive Java type */
-        jObjectToPrimitiveCKObjectPtrPtr(env, jParam, ckpParamPtr, ckpLength);
-        /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
-        /* *ckpLength = 1; */
-    }
+    /* if everything faild up to here */
+    /* try if the parameter is a primitive Java type */
+    jObjectToPrimitiveCKObjectPtrPtr(env, jParam, ckpParamPtr, ckpLength);
+    /* *ckpParamPtr = jObjectToCKVoidPtr(jParam); */
+    /* *ckpLength = 1; */
 
     TRACE0("FINISHED\n");
 }
@@ -1061,36 +1283,41 @@
  */
 CK_RSA_PKCS_OAEP_PARAMS jRsaPkcsOaepParamToCKRsaPkcsOaepParam(JNIEnv *env, jobject jParam)
 {
-    jclass jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    jclass jRsaPkcsOaepParamsClass;
     CK_RSA_PKCS_OAEP_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jHashAlg, jMgf, jSource;
+    jobject jSourceData;
     CK_BYTE_PTR ckpByte;
 
     /* get hashAlg */
+    jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS);
+    if (jRsaPkcsOaepParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "hashAlg", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hashAlg = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "mgf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.mgf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get source */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "source", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.source = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sourceData and sourceDataLength */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsOaepParamsClass, "pSourceData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &ckpByte, &(ckParam.ulSourceDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSourceData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.hashAlg = jLongToCKULong(jHashAlg);
+    ckParam.mgf = jLongToCKULong(jMgf);
+    ckParam.source = jLongToCKULong(jSource);
+    jByteArrayToCKByteArray(env, jSourceData, & ckpByte, &(ckParam.ulSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
     ckParam.pSourceData = (CK_VOID_PTR) ckpByte;
 
     return ckParam ;
@@ -1105,36 +1332,50 @@
  */
 CK_PBE_PARAMS jPbeParamToCKPbeParam(JNIEnv *env, jobject jParam)
 {
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    jclass jPbeParamsClass;
     CK_PBE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jIteration;
+    jobject jInitVector, jPassword, jSalt;
     CK_ULONG ckTemp;
 
     /* get pInitVector */
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pInitVector", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pInitVector), &ckTemp);
+    if (fieldID == NULL) { return ckParam; }
+    jInitVector = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPassword and ulPasswordLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pPassword", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pPassword), &(ckParam.ulPasswordLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPassword = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pSalt and ulSaltLength */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pSalt", "[C");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jCharArrayToCKCharArray(env, jObject, &(ckParam.pSalt), &(ckParam.ulSaltLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSalt = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulIteration */
     fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "ulIteration", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulIteration = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIteration = (*env)->GetLongField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.ulIteration = jLongToCKULong(jIteration);
+    jCharArrayToCKCharArray(env, jInitVector, &(ckParam.pInitVector), &ckTemp);
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jCharArrayToCKCharArray(env, jPassword, &(ckParam.pPassword), &(ckParam.ulPasswordLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pInitVector);
+        return ckParam;
+    }
+    jCharArrayToCKCharArray(env, jSalt, &(ckParam.pSalt), &(ckParam.ulSaltLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pInitVector);
+        free(ckParam.pPassword);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1147,8 +1388,7 @@
  */
 void copyBackPBEInitializationVector(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-    jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-    jclass jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    jclass jMechanismClass, jPbeParamsClass;
     CK_PBE_PARAMS *ckParam;
     jfieldID fieldID;
     CK_MECHANISM_TYPE ckMechanismType;
@@ -1161,8 +1401,10 @@
     jchar* jInitVectorChars;
 
     /* get mechanism */
+    jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (jMechanismClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
     if (ckMechanismType != ckMechanism->mechanism) {
@@ -1170,21 +1412,25 @@
         return;
     }
 
+    jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS);
+    if (jPbeParamsClass == NULL) { return; }
     ckParam = (CK_PBE_PARAMS *) ckMechanism->pParameter;
     if (ckParam != NULL_PTR) {
         initVector = ckParam->pInitVector;
         if (initVector != NULL_PTR) {
             /* get pParameter */
             fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-            assert(fieldID != 0);
+            if (fieldID == NULL) { return; }
             jParameter = (*env)->GetObjectField(env, jMechanism, fieldID);
             fieldID = (*env)->GetFieldID(env, jPbeParamsClass, "pInitVektor", "[C");
-            assert(fieldID != 0);
+            if (fieldID == NULL) { return; }
             jInitVector = (*env)->GetObjectField(env, jParameter, fieldID);
 
             if (jInitVector != NULL) {
                 jInitVectorLength = (*env)->GetArrayLength(env, jInitVector);
                 jInitVectorChars = (*env)->GetCharArrayElements(env, jInitVector, NULL);
+                if (jInitVectorChars == NULL) { return; }
+
                 /* copy the chars to the Java buffer */
                 for (i=0; i < jInitVectorLength; i++) {
                     jInitVectorChars[i] = ckCharToJChar(initVector[i]);
@@ -1205,41 +1451,50 @@
  */
 CK_PKCS5_PBKD2_PARAMS jPkcs5Pbkd2ParamToCKPkcs5Pbkd2Param(JNIEnv *env, jobject jParam)
 {
-    jclass jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    jclass jPkcs5Pbkd2ParamsClass;
     CK_PKCS5_PBKD2_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jSaltSource, jIteration, jPrf;
+    jobject jSaltSourceData, jPrfData;
 
     /* get saltSource */
+    jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS);
+    if (jPkcs5Pbkd2ParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "saltSource", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.saltSource = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSaltSource = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSaltSourceData */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pSaltSourceData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR *) &(ckParam.pSaltSourceData), &(ckParam.ulSaltSourceDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSaltSourceData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get iterations */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "iterations", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.iterations = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jIteration = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get prf */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "prf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.prf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPrfData and ulPrfDataLength in byte */
     fieldID = (*env)->GetFieldID(env, jPkcs5Pbkd2ParamsClass, "pPrfData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR *) &(ckParam.pPrfData), &(ckParam.ulPrfDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPrfData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.saltSource = jLongToCKULong(jSaltSource);
+    jByteArrayToCKByteArray(env, jSaltSourceData, (CK_BYTE_PTR *) &(ckParam.pSaltSourceData), &(ckParam.ulSaltSourceDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    ckParam.iterations = jLongToCKULong(jIteration);
+    ckParam.prf = jLongToCKULong(jPrf);
+    jByteArrayToCKByteArray(env, jPrfData, (CK_BYTE_PTR *) &(ckParam.pPrfData), &(ckParam.ulPrfDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSaltSourceData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1253,28 +1508,32 @@
  */
 CK_RSA_PKCS_PSS_PARAMS jRsaPkcsPssParamToCKRsaPkcsPssParam(JNIEnv *env, jobject jParam)
 {
-    jclass jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    jclass jRsaPkcsPssParamsClass;
     CK_RSA_PKCS_PSS_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
+    jlong jHashAlg, jMgf, jSLen;
 
     /* get hashAlg */
+    jRsaPkcsPssParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_PSS_PARAMS);
+    if (jRsaPkcsPssParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "hashAlg", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hashAlg = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jHashAlg = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get mgf */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "mgf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.mgf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jMgf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get sLen */
     fieldID = (*env)->GetFieldID(env, jRsaPkcsPssParamsClass, "sLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.sLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jSLen = (*env)->GetLongField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.hashAlg = jLongToCKULong(jHashAlg);
+    ckParam.mgf = jLongToCKULong(jMgf);
+    ckParam.sLen = jLongToCKULong(jSLen);
 
     return ckParam ;
 }
@@ -1288,29 +1547,39 @@
  */
 CK_ECDH1_DERIVE_PARAMS jEcdh1DeriveParamToCKEcdh1DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    jclass jEcdh1DeriveParamsClass;
     CK_ECDH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
     jlong jLong;
-    jobject jObject;
+    jobject jSharedData, jPublicData;
 
     /* get kdf */
+    jEcdh1DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH1_DERIVE_PARAMS);
+    if (jEcdh1DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return ckParam; }
     jLong = (*env)->GetLongField(env, jParam, fieldID);
     ckParam.kdf = jLongToCKULong(jLong);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pSharedData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh1DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jLong);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1324,48 +1593,61 @@
  */
 CK_ECDH2_DERIVE_PARAMS jEcdh2DeriveParamToCKEcdh2DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    jclass jEcdh2DeriveParamsClass;
     CK_ECDH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf, jPrivateDataLen, jPrivateData;
+    jobject jSharedData, jPublicData, jPublicData2;
 
     /* get kdf */
+    jEcdh2DeriveParamsClass = (*env)->FindClass(env, CLASS_ECDH2_DERIVE_PARAMS);
+    if (jEcdh2DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pSharedData and ulSharedDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pSharedData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jSharedData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulPrivateDataLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "hPrivateData", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hPrivateData = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jEcdh2DeriveParamsClass, "pPublicData2", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
 
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jSharedData, &(ckParam.pSharedData), &(ckParam.ulSharedDataLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        return ckParam;
+    }
+    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pSharedData);
+        free(ckParam.pPublicData);
+        return ckParam;
+    }
     return ckParam ;
 }
 
@@ -1378,29 +1660,38 @@
  */
 CK_X9_42_DH1_DERIVE_PARAMS jX942Dh1DeriveParamToCKX942Dh1DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    jclass jX942Dh1DeriveParamsClass;
     CK_X9_42_DH1_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf;
+    jobject jOtherInfo, jPublicData;
 
     /* get kdf */
+    jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS);
+    if (jX942Dh1DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pOtherInfo", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if (fieldID == NULL) { return ckParam; }
+    jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh1DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        return ckParam;
+    }
 
     return ckParam ;
 }
@@ -1414,47 +1705,61 @@
  */
 CK_X9_42_DH2_DERIVE_PARAMS jX942Dh2DeriveParamToCKX942Dh2DeriveParam(JNIEnv *env, jobject jParam)
 {
-    jclass jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    jclass jX942Dh2DeriveParamsClass;
     CK_X9_42_DH2_DERIVE_PARAMS ckParam;
     jfieldID fieldID;
-    jlong jLong;
-    jobject jObject;
+    jlong jKdf, jPrivateDataLen, jPrivateData;
+    jobject jOtherInfo, jPublicData, jPublicData2;
 
     /* get kdf */
+    jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
+    if (jX942Dh2DeriveParamsClass == NULL) { return ckParam; }
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "kdf", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.kdf = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jKdf = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pOtherInfo and ulOtherInfoLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pOtherInfo", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if (fieldID == NULL) { return ckParam; }
+    jOtherInfo = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get pPublicData and ulPublicDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData = (*env)->GetObjectField(env, jParam, fieldID);
 
     /* get ulPrivateDataLen */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "ulPrivateDataLen", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.ulPrivateDataLen = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateDataLen = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get hPrivateData */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "hPrivateData", "J");
-    assert(fieldID != 0);
-    jLong = (*env)->GetLongField(env, jParam, fieldID);
-    ckParam.hPrivateData = jLongToCKULong(jLong);
+    if (fieldID == NULL) { return ckParam; }
+    jPrivateData = (*env)->GetLongField(env, jParam, fieldID);
 
     /* get pPublicData2 and ulPublicDataLen2 */
     fieldID = (*env)->GetFieldID(env, jX942Dh2DeriveParamsClass, "pPublicData2", "[B");
-    assert(fieldID != 0);
-    jObject = (*env)->GetObjectField(env, jParam, fieldID);
-    jByteArrayToCKByteArray(env, jObject, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if (fieldID == NULL) { return ckParam; }
+    jPublicData2 = (*env)->GetObjectField(env, jParam, fieldID);
+
+    /* populate java values */
+    ckParam.kdf = jLongToCKULong(jKdf);
+    jByteArrayToCKByteArray(env, jOtherInfo, &(ckParam.pOtherInfo), &(ckParam.ulOtherInfoLen));
+    if ((*env)->ExceptionCheck(env)) { return ckParam; }
+    jByteArrayToCKByteArray(env, jPublicData, &(ckParam.pPublicData), &(ckParam.ulPublicDataLen));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        return ckParam;
+    }
+    ckParam.ulPrivateDataLen = jLongToCKULong(jPrivateDataLen);
+    ckParam.hPrivateData = jLongToCKULong(jPrivateData);
+    jByteArrayToCKByteArray(env, jPublicData2, &(ckParam.pPublicData2), &(ckParam.ulPublicDataLen2));
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckParam.pOtherInfo);
+        free(ckParam.pPublicData);
+        return ckParam;
+    }
 
     return ckParam ;
 }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_crypt.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -81,6 +81,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_EncryptInit)(ckSessionHandle, &ckMechanism,
                                         ckKeyHandle);
@@ -126,14 +127,29 @@
 
     if (jInLen > MAX_STACK_BUFFER_LEN) {
       inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+      if (inBufP == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       inBufP = IBUF;
     }
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+      if (inBufP != IBUF) { free(inBufP); }
+      return 0;
+    }
 
     ckEncryptedPartLen = jOutLen;
     if (jOutLen > MAX_STACK_BUFFER_LEN) {
       outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+      if (outBufP == NULL) {
+        if (inBufP != IBUF) {
+          free(inBufP);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       outBufP = OBUF;
     }
@@ -193,10 +209,18 @@
     } else {
       if (jInLen > MAX_STACK_BUFFER_LEN) {
         inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         inBufP = IBUF;
       }
       (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+      if ((*env)->ExceptionCheck(env)) {
+        if (directIn == 0 && inBufP != IBUF) { free(inBufP); }
+        return 0;
+      }
     }
 
     ckEncryptedPartLen = jOutLen;
@@ -205,6 +229,13 @@
     } else {
       if (jOutLen > MAX_STACK_BUFFER_LEN) {
         outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+        if (outBufP == NULL) {
+          if (directIn == 0 && inBufP != IBUF) {
+            free(inBufP);
+          }
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         outBufP = OBUF;
       }
@@ -317,6 +348,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_DecryptInit)(ckSessionHandle, &ckMechanism,
                                         ckKeyHandle);
@@ -362,14 +394,29 @@
 
     if (jInLen > MAX_STACK_BUFFER_LEN) {
       inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+      if (inBufP == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       inBufP = IBUF;
     }
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+      if (inBufP != IBUF) { free(inBufP); }
+      return 0;
+    }
 
     ckPartLen = jOutLen;
     if (jOutLen > MAX_STACK_BUFFER_LEN) {
       outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+      if (outBufP == NULL) {
+        if (inBufP != IBUF) {
+          free(inBufP);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return 0;
+      }
     } else {
       outBufP = OBUF;
     }
@@ -429,10 +476,18 @@
     } else {
       if (jInLen > MAX_STACK_BUFFER_LEN) {
         inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+        }
       } else {
         inBufP = IBUF;
       }
       (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+      if ((*env)->ExceptionCheck(env)) {
+        if (directIn == 0 && inBufP != IBUF) { free(inBufP); }
+        return 0;
+      }
     }
 
     ckDecryptedPartLen = jOutLen;
@@ -441,6 +496,13 @@
     } else {
       if (jOutLen > MAX_STACK_BUFFER_LEN) {
         outBufP = (CK_BYTE_PTR)malloc((size_t)jOutLen);
+        if (outBufP == NULL) {
+          if (directIn == 0 && inBufP != IBUF) {
+            free(inBufP);
+          }
+          JNU_ThrowOutOfMemoryError(env, 0);
+          return 0;
+      }
       } else {
         outBufP = OBUF;
       }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_digest.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -75,6 +75,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
 
@@ -82,7 +83,7 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -114,6 +115,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0; }
 
     rv = (*ckpFunctions->C_DigestInit)(ckSessionHandle, &ckMechanism);
 
@@ -121,29 +123,32 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0; }
 
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         bufP = BUF;
     } else {
         /* always use single part op, even for large data */
-        bufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)bufP);
-    rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-        if (bufP != BUF) {
-            free(bufP);
-        }
+    if ((*env)->ExceptionCheck(env)) {
+        if (bufP != BUF) { free(bufP); }
         return 0;
     }
 
-    (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
+    rv = (*ckpFunctions->C_Digest)(ckSessionHandle, bufP, jInLen, DIGESTBUF, &ckDigestLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)DIGESTBUF);
+    }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
+
     return ckDigestLength;
 }
 #endif
@@ -183,17 +188,23 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
         rv = (*ckpFunctions->C_DigestUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) {
-                free(bufP);
-            }
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+            if (bufP != BUF) { free(bufP); }
             return;
         }
         jInOfs += chunkLen;
@@ -229,7 +240,7 @@
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_DigestKey)(ckSessionHandle, ckKeyHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -257,10 +268,9 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_DigestFinal)(ckSessionHandle, BUF, &ckDigestLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0 ; }
-
-    (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)BUF);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        (*env)->SetByteArrayRegion(env, jDigest, jDigestOfs, ckDigestLength, (jbyte *)BUF);
+    }
     return ckDigestLength;
 }
 #endif
@@ -288,12 +298,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jSeed, &ckpSeed, &ckSeedLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_SeedRandom)(ckSessionHandle, ckpSeed, ckSeedLength);
 
     free(ckpSeed);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -322,6 +333,7 @@
 
     jRandomBufferLength = (*env)->GetArrayLength(env, jRandomData);
     jRandomBuffer = (*env)->GetByteArrayElements(env, jRandomData, NULL);
+    if (jRandomBuffer == NULL) { return; }
 
     rv = (*ckpFunctions->C_GenerateRandom)(ckSessionHandle,
                                          (CK_BYTE_PTR) jRandomBuffer,
@@ -330,6 +342,6 @@
     /* copy back generated bytes */
     (*env)->ReleaseByteArrayElements(env, jRandomData, jRandomBuffer, 0);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_dual.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -73,7 +73,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart = NULL_PTR, ckpEncryptedPart;
     CK_ULONG ckPartLength, ckEncryptedPartLength = 0;
-    jbyteArray jEncryptedPart;
+    jbyteArray jEncryptedPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -81,20 +81,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jPart, &ckpPart, &ckPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DigestEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, NULL_PTR, &ckEncryptedPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpPart);
+        return NULL;
+    }
 
     ckpEncryptedPart = (CK_BYTE_PTR) malloc(ckEncryptedPartLength * sizeof(CK_BYTE));
+    if (ckpEncryptedPart == NULL) {
+        free(ckpPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DigestEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, ckpEncryptedPart, &ckEncryptedPartLength);
-
-    jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    }
     free(ckpPart);
     free(ckpEncryptedPart);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jEncryptedPart ;
 }
 #endif
@@ -117,7 +125,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart, ckpEncryptedPart = NULL_PTR;
     CK_ULONG ckPartLength = 0, ckEncryptedPartLength;
-    jbyteArray jPart;
+    jbyteArray jPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -125,19 +133,27 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jEncryptedPart, &ckpEncryptedPart, &ckEncryptedPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DecryptDigestUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, NULL_PTR, &ckPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpEncryptedPart);
+        return NULL;
+    }
 
     ckpPart = (CK_BYTE_PTR) malloc(ckPartLength * sizeof(CK_BYTE));
+    if (ckpPart == NULL) {
+        free(ckpEncryptedPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DecryptDigestUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, ckpPart, &ckPartLength);
-
-    jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    }
+    free(ckpEncryptedPart);
     free(ckpPart);
-    free(ckpEncryptedPart);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     return jPart ;
 }
@@ -161,7 +177,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart = NULL_PTR, ckpEncryptedPart;
     CK_ULONG ckPartLength, ckEncryptedPartLength = 0;
-    jbyteArray jEncryptedPart;
+    jbyteArray jEncryptedPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -169,20 +185,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jPart, &ckpPart, &ckPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_SignEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, NULL_PTR, &ckEncryptedPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpPart);
+        return NULL;
+    }
 
     ckpEncryptedPart = (CK_BYTE_PTR) malloc(ckEncryptedPartLength * sizeof(CK_BYTE));
+    if (ckpEncryptedPart == NULL) {
+        free(ckpPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_SignEncryptUpdate)(ckSessionHandle, ckpPart, ckPartLength, ckpEncryptedPart, &ckEncryptedPartLength);
-
-    jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jEncryptedPart = ckByteArrayToJByteArray(env, ckpEncryptedPart, ckEncryptedPartLength);
+    }
     free(ckpPart);
     free(ckpEncryptedPart);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jEncryptedPart ;
 }
 #endif
@@ -205,7 +229,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpPart, ckpEncryptedPart = NULL_PTR;
     CK_ULONG ckPartLength = 0, ckEncryptedPartLength;
-    jbyteArray jPart;
+    jbyteArray jPart = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -213,19 +237,28 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jEncryptedPart, &ckpEncryptedPart, &ckEncryptedPartLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     rv = (*ckpFunctions->C_DecryptVerifyUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, NULL_PTR, &ckPartLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpEncryptedPart);
+        return NULL;
+    }
 
     ckpPart = (CK_BYTE_PTR) malloc(ckPartLength * sizeof(CK_BYTE));
+    if (ckpPart == NULL) {
+        free(ckpEncryptedPart);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_DecryptVerifyUpdate)(ckSessionHandle, ckpEncryptedPart, ckEncryptedPartLength, ckpPart, &ckPartLength);
 
-    jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
-    free(ckpPart);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jPart = ckByteArrayToJByteArray(env, ckpPart, ckPartLength);
+    }
     free(ckpEncryptedPart);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    free(ckpPart);
 
     return jPart ;
 }
@@ -252,7 +285,7 @@
 
     /* C_GetFunctionStatus should always return CKR_FUNCTION_NOT_PARALLEL */
     rv = (*ckpFunctions->C_GetFunctionStatus)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -277,6 +310,6 @@
 
     /* C_GetFunctionStatus should always return CKR_FUNCTION_NOT_PARALLEL */
     rv = (*ckpFunctions->C_CancelFunction)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_general.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -102,6 +102,7 @@
 
 jclass fetchClass(JNIEnv *env, const char *name) {
     jclass tmpClass = (*env)->FindClass(env, name);
+    if (tmpClass == NULL) { return NULL; }
     return (*env)->NewGlobalRef(env, tmpClass);
 }
 
@@ -110,14 +111,18 @@
 
     /* PKCS11 */
     pNativeDataID = (*env)->GetFieldID(env, thisClass, "pNativeData", "J");
+    if (pNativeDataID == NULL) { return; }
 
     /* CK_MECHANISM */
     tmpClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (tmpClass == NULL) { return; }
     mech_mechanismID = (*env)->GetFieldID(env, tmpClass, "mechanism", "J");
+    if (mech_mechanismID == NULL) { return; }
     mech_pParameterID = (*env)->GetFieldID(env, tmpClass, "pParameter",
                                            "Ljava/lang/Object;");
-
+    if (mech_pParameterID == NULL) { return; }
     jByteArrayClass = fetchClass(env, "[B");
+    if (jByteArrayClass == NULL) { return; }
     jLongClass = fetchClass(env, "java/lang/Long");
 }
 
@@ -252,10 +257,9 @@
     if (ckpFunctions == NULL) { return NULL; }
 
     rv = (*ckpFunctions->C_GetInfo)(&ckLibInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jInfoObject = ckInfoPtrToJInfo(env, &ckLibInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jInfoObject = ckInfoPtrToJInfo(env, &ckLibInfo);
+    }
     return jInfoObject ;
 }
 
@@ -279,28 +283,31 @@
 
     /* load CK_INFO class */
     jInfoClass = (*env)->FindClass(env, CLASS_INFO);
-    assert(jInfoClass != 0);
+    if (jInfoClass == NULL) { return NULL; };
 
     /* load CK_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jInfoClass, "<init>",
        "(Lsun/security/pkcs11/wrapper/CK_VERSION;[CJ[CLsun/security/pkcs11/wrapper/CK_VERSION;)V");
-
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jCryptokiVer = ckVersionPtrToJVersion(env, &(ckpInfo->cryptokiVersion));
+    if (jCryptokiVer == NULL) { return NULL; }
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL) { return NULL; }
     jFlags = ckULongToJLong(ckpInfo->flags);
     jLibraryDesc =
       ckUTF8CharArrayToJCharArray(env, &(ckpInfo->libraryDescription[0]), 32);
+    if (jLibraryDesc == NULL) { return NULL; }
     jLibraryVer = ckVersionPtrToJVersion(env, &(ckpInfo->libraryVersion));
+    if (jLibraryVer == NULL) { return NULL; }
 
     /* create new CK_INFO object */
     jInfoObject = (*env)->NewObject(env, jInfoClass, jCtrId, jCryptokiVer,
                                     jVendor, jFlags, jLibraryDesc, jLibraryVer);
-    assert(jInfoObject != 0);
+    if (jInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jInfoClass);
@@ -343,15 +350,18 @@
     if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     ckpSlotList = (CK_SLOT_ID_PTR) malloc(ckTokenNumber * sizeof(CK_SLOT_ID));
+    if (ckpSlotList == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetSlotList)(ckTokenPresent, ckpSlotList,
                                         &ckTokenNumber);
-
-    jSlotList = ckULongArrayToJLongArray(env, ckpSlotList, ckTokenNumber);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotList = ckULongArrayToJLongArray(env, ckpSlotList, ckTokenNumber);
+    }
     free(ckpSlotList);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jSlotList ;
 }
 #endif
@@ -380,10 +390,9 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_GetSlotInfo)(ckSlotID, &ckSlotInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jSlotInfoObject = ckSlotInfoPtrToJSlotInfo(env, &ckSlotInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotInfoObject = ckSlotInfoPtrToJSlotInfo(env, &ckSlotInfo);
+    }
     return jSlotInfoObject ;
 }
 
@@ -410,28 +419,32 @@
 
     /* load CK_SLOT_INFO class */
     jSlotInfoClass = (*env)->FindClass(env, CLASS_SLOT_INFO);
-    assert(jSlotInfoClass != 0);
+    if (jSlotInfoClass == NULL) { return NULL; };
 
     /* load CK_SLOT_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jSlotInfoClass, "<init>",
        "([C[CJLsun/security/pkcs11/wrapper/CK_VERSION;Lsun/security/pkcs11/wrapper/CK_VERSION;)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; }
 
     /* prep all fields */
     jSlotDesc =
       ckUTF8CharArrayToJCharArray(env, &(ckpSlotInfo->slotDescription[0]), 64);
+    if (jSlotDesc == NULL) { return NULL; }
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpSlotInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL) { return NULL; }
     jFlags = ckULongToJLong(ckpSlotInfo->flags);
     jHardwareVer = ckVersionPtrToJVersion(env, &(ckpSlotInfo->hardwareVersion));
+    if (jHardwareVer == NULL) { return NULL; }
     jFirmwareVer = ckVersionPtrToJVersion(env, &(ckpSlotInfo->firmwareVersion));
+    if (jFirmwareVer == NULL) { return NULL; }
 
     /* create new CK_SLOT_INFO object */
     jSlotInfoObject = (*env)->NewObject
       (env, jSlotInfoClass, jCtrId, jSlotDesc, jVendor, jFlags,
        jHardwareVer, jFirmwareVer);
-    assert(jSlotInfoObject != 0);
+    if (jSlotInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jSlotInfoClass);
@@ -460,7 +473,7 @@
 {
     CK_SLOT_ID ckSlotID;
     CK_TOKEN_INFO ckTokenInfo;
-    jobject jInfoTokenObject;
+    jobject jInfoTokenObject = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -469,10 +482,9 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_GetTokenInfo)(ckSlotID, &ckTokenInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jInfoTokenObject = ckTokenInfoPtrToJTokenInfo(env, &ckTokenInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jInfoTokenObject = ckTokenInfoPtrToJTokenInfo(env, &ckTokenInfo);
+    }
     return jInfoTokenObject ;
 }
 
@@ -512,21 +524,25 @@
 
     /* load CK_TOKEN_INFO class */
     jTokenInfoClass = (*env)->FindClass(env, CLASS_TOKEN_INFO);
-    assert(jTokenInfoClass != 0);
+    if (jTokenInfoClass == NULL)  { return NULL; };
 
     /* load CK_TOKEN_INFO constructor */
     jCtrId = (*env)->GetMethodID
       (env, jTokenInfoClass, "<init>",
        "([C[C[C[CJJJJJJJJJJJLsun/security/pkcs11/wrapper/CK_VERSION;Lsun/security/pkcs11/wrapper/CK_VERSION;[C)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL)  { return NULL; };
 
     /* prep all fields */
     jLabel = ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->label[0]), 32);
+    if (jLabel == NULL)  { return NULL; };
     jVendor =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->manufacturerID[0]), 32);
+    if (jVendor == NULL)  { return NULL; };
     jModel = ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->model[0]), 16);
+    if (jModel == NULL)  { return NULL; };
     jSerialNo =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->serialNumber[0]), 16);
+    if (jSerialNo == NULL)  { return NULL; };
     jFlags = ckULongToJLong(ckpTokenInfo->flags);
     jMaxSnCnt = ckULongSpecialToJLong(ckpTokenInfo->ulMaxSessionCount);
     jSnCnt = ckULongSpecialToJLong(ckpTokenInfo->ulSessionCount);
@@ -540,10 +556,13 @@
     jFreePrivMem = ckULongSpecialToJLong(ckpTokenInfo->ulFreePrivateMemory);
     jHardwareVer =
       ckVersionPtrToJVersion(env, &(ckpTokenInfo->hardwareVersion));
+    if (jHardwareVer == NULL) { return NULL; }
     jFirmwareVer =
       ckVersionPtrToJVersion(env, &(ckpTokenInfo->firmwareVersion));
+    if (jFirmwareVer == NULL) { return NULL; }
     jUtcTime =
       ckUTF8CharArrayToJCharArray(env, &(ckpTokenInfo->utcTime[0]), 16);
+    if (jUtcTime == NULL) { return NULL; }
 
     /* create new CK_TOKEN_INFO object */
     jTokenInfoObject =
@@ -553,7 +572,7 @@
                         jMaxPinLen, jMinPinLen,
                         jTotalPubMem, jFreePubMem, jTotalPrivMem, jFreePrivMem,
                         jHardwareVer, jFirmwareVer, jUtcTime);
-    assert(jTokenInfoObject != 0);
+    if (jTokenInfoObject == NULL) { return NULL; }
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jTokenInfoClass);
@@ -584,7 +603,7 @@
 {
     CK_FLAGS ckFlags;
     CK_SLOT_ID ckSlotID;
-    jlong jSlotID;
+    jlong jSlotID = 0L;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -593,9 +612,9 @@
     ckFlags = jLongToCKULong(jFlags);
 
     rv = (*ckpFunctions->C_WaitForSlotEvent)(ckFlags, &ckSlotID, NULL_PTR);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L; }
-
-    jSlotID = ckULongToJLong(ckSlotID);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSlotID = ckULongToJLong(ckSlotID);
+    }
 
     return jSlotID ;
 }
@@ -632,16 +651,19 @@
 
     ckpMechanismList = (CK_MECHANISM_TYPE_PTR)
       malloc(ckMechanismNumber * sizeof(CK_MECHANISM_TYPE));
+    if (ckpMechanismList == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetMechanismList)(ckSlotID, ckpMechanismList,
                                              &ckMechanismNumber);
-
-    jMechanismList = ckULongArrayToJLongArray(env, ckpMechanismList,
-                                              ckMechanismNumber);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jMechanismList = ckULongArrayToJLongArray(env, ckpMechanismList,
+                                                  ckMechanismNumber);
+    }
     free(ckpMechanismList);
 
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jMechanismList ;
 }
 #endif
@@ -663,7 +685,7 @@
     CK_SLOT_ID ckSlotID;
     CK_MECHANISM_TYPE ckMechanismType;
     CK_MECHANISM_INFO ckMechanismInfo;
-    jobject jMechanismInfo;
+    jobject jMechanismInfo = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -674,10 +696,9 @@
 
     rv = (*ckpFunctions->C_GetMechanismInfo)(ckSlotID, ckMechanismType,
                                              &ckMechanismInfo);
-    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jMechanismInfo = ckMechanismInfoPtrToJMechanismInfo(env, &ckMechanismInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jMechanismInfo = ckMechanismInfoPtrToJMechanismInfo(env, &ckMechanismInfo);
+    }
     return jMechanismInfo ;
 }
 
@@ -703,11 +724,11 @@
 
     /* load CK_MECHANISM_INFO class */
     jMechanismInfoClass = (*env)->FindClass(env, CLASS_MECHANISM_INFO);
-    assert(jMechanismInfoClass != 0);
+    if (jMechanismInfoClass == NULL) { return NULL; };
 
     /* load CK_MECHANISM_INFO constructor */
     jCtrId = (*env)->GetMethodID(env, jMechanismInfoClass, "<init>", "(JJJ)V");
-    assert(jCtrId != 0);
+    if (jCtrId == NULL) { return NULL; };
 
     /* prep all fields */
     jMinKeySize = ckULongToJLong(ckpMechanismInfo->ulMinKeySize);
@@ -717,7 +738,7 @@
     /* create new CK_MECHANISM_INFO object */
     jMechanismInfoObject = (*env)->NewObject(env, jMechanismInfoClass, jCtrId,
                                              jMinKeySize, jMaxKeySize, jFlags);
-    assert(jMechanismInfoObject != 0);
+    if (jMechanismInfoObject == NULL) { return NULL; };
 
     /* free local references */
     (*env)->DeleteLocalRef(env, jMechanismInfoClass);
@@ -753,8 +774,13 @@
 
     ckSlotID = jLongToCKULong(jSlotID);
     jCharArrayToCKCharArray(env, jPin, &ckpPin, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+    /* ckLabelLength <= 32 !!! */
     jCharArrayToCKUTF8CharArray(env, jLabel, &ckpLabel, &ckLabelLength);
-    /* ckLabelLength <= 32 !!! */
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpPin);
+        return;
+    }
 
     rv = (*ckpFunctions->C_InitToken)(ckSlotID, ckpPin, ckPinLength, ckpLabel);
     TRACE1("InitToken return code: %d", rv);
@@ -790,6 +816,7 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jCharArrayToCKCharArray(env, jPin, &ckpPin, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_InitPIN)(ckSessionHandle, ckpPin, ckPinLength);
 
@@ -828,7 +855,12 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jCharArrayToCKCharArray(env, jOldPin, &ckpOldPin, &ckOldPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
     jCharArrayToCKCharArray(env, jNewPin, &ckpNewPin, &ckNewPinLength);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpOldPin);
+        return;
+    }
 
     rv = (*ckpFunctions->C_SetPIN)(ckSessionHandle, ckpOldPin, ckOldPinLength,
                                    ckpNewPin, ckNewPinLength);
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_keymgmt.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -74,7 +74,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jlong jKeyHandle;
+    jlong jKeyHandle = 0L;
     CK_ULONG i;
     CK_RV rv;
 
@@ -83,21 +83,23 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
-    if ((*env)->ExceptionOccurred(env)) { return 0L ; }
+    if ((*env)->ExceptionCheck(env)) { return 0L ; }
+
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
 
     rv = (*ckpFunctions->C_GenerateKey)(ckSessionHandle, &ckMechanism, ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
-    jKeyHandle = ckULongToJLong(ckKeyHandle);
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandle = ckULongToJLong(ckKeyHandle);
 
-    /* cheack, if we must give a initialization vector back to Java */
-    switch (ckMechanism.mechanism) {
+        /* cheack, if we must give a initialization vector back to Java */
+        switch (ckMechanism.mechanism) {
         case CKM_PBE_MD2_DES_CBC:
         case CKM_PBE_MD5_DES_CBC:
         case CKM_PBE_MD5_CAST_CBC:
@@ -109,13 +111,13 @@
             /* we must copy back the initialization vector to the jMechanism object */
             copyBackPBEInitializationVector(env, &ckMechanism, jMechanism);
             break;
+        }
     }
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     return jKeyHandle ;
 }
@@ -158,40 +160,53 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
-    jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
-    jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
+
     ckpKeyHandles = (CK_OBJECT_HANDLE_PTR) malloc(2 * sizeof(CK_OBJECT_HANDLE));
+    if (ckpKeyHandles == NULL) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     ckpPublicKeyHandle = ckpKeyHandles;   /* first element of array is Public Key */
     ckpPrivateKeyHandle = (ckpKeyHandles + 1);  /* second element of array is Private Key */
 
+    jAttributeArrayToCKAttributeArray(env, jPublicKeyTemplate, &ckpPublicKeyAttributes, &ckPublicKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpKeyHandles);
+        return NULL;
+    }
+
+    jAttributeArrayToCKAttributeArray(env, jPrivateKeyTemplate, &ckpPrivateKeyAttributes, &ckPrivateKeyAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpKeyHandles);
+        freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
+        return NULL;
+    }
+
     rv = (*ckpFunctions->C_GenerateKeyPair)(ckSessionHandle, &ckMechanism,
                      ckpPublicKeyAttributes, ckPublicKeyAttributesLength,
                      ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength,
                      ckpPublicKeyHandle, ckpPrivateKeyHandle);
 
-    jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
-
-    for(i=0; i<ckPublicKeyAttributesLength; i++) {
-        if(ckpPublicKeyAttributes[i].pValue != NULL_PTR) {
-            free(ckpPublicKeyAttributes[i].pValue);
-        }
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandles = ckULongArrayToJLongArray(env, ckpKeyHandles, 2);
     }
-    free(ckpPublicKeyAttributes);
-
-    for(i=0; i<ckPrivateKeyAttributesLength; i++) {
-        if(ckpPrivateKeyAttributes[i].pValue != NULL_PTR) {
-            free(ckpPrivateKeyAttributes[i].pValue);
-        }
-    }
-    free(ckpPrivateKeyAttributes);
 
     if(ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
     free(ckpKeyHandles);
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL; }
+    freeCKAttributeArray(ckpPublicKeyAttributes, ckPublicKeyAttributesLength);
+    freeCKAttributeArray(ckpPrivateKeyAttributes, ckPrivateKeyAttributesLength);
 
     return jKeyHandles ;
 }
@@ -217,7 +232,7 @@
     CK_MECHANISM ckMechanism;
     CK_OBJECT_HANDLE ckWrappingKeyHandle;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jbyteArray jWrappedKey;
+    jbyteArray jWrappedKey = NULL;
     CK_RV rv;
     CK_BYTE BUF[MAX_STACK_BUFFER_LEN];
     CK_BYTE_PTR ckpWrappedKey = BUF;
@@ -228,24 +243,32 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
+
     ckWrappingKeyHandle = jLongToCKULong(jWrappingKeyHandle);
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     if (rv == CKR_BUFFER_TOO_SMALL) {
         ckpWrappedKey = (CK_BYTE_PTR) malloc(ckWrappedKeyLength);
+        if (ckpWrappedKey == NULL) {
+            if (ckMechanism.pParameter != NULL_PTR) {
+                free(ckMechanism.pParameter);
+            }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
+
         rv = (*ckpFunctions->C_WrapKey)(ckSessionHandle, &ckMechanism, ckWrappingKeyHandle, ckKeyHandle, ckpWrappedKey, &ckWrappedKeyLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jWrappedKey = ckByteArrayToJByteArray(env, ckpWrappedKey, ckWrappedKeyLength);
     }
 
-    if (ckpWrappedKey != BUF) {
-        free(ckpWrappedKey);
+    if (ckpWrappedKey != BUF) { free(ckpWrappedKey); }
+    if (ckMechanism.pParameter != NULL_PTR) {
+        free(ckMechanism.pParameter);
     }
-    if(ckMechanism.pParameter != NULL_PTR)
-        free(ckMechanism.pParameter);
-
     return jWrappedKey ;
 }
 #endif
@@ -277,7 +300,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_OBJECT_HANDLE ckKeyHandle;
-    jlong jKeyHandle;
+    jlong jKeyHandle = 0L;
     CK_ULONG i;
     CK_RV rv;
 
@@ -286,37 +309,48 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
+
     ckUnwrappingKeyHandle = jLongToCKULong(jUnwrappingKeyHandle);
     jByteArrayToCKByteArray(env, jWrappedKey, &ckpWrappedKey, &ckWrappedKeyLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
+
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        free(ckpWrappedKey);
+        return 0L;
+    }
+
 
     rv = (*ckpFunctions->C_UnwrapKey)(ckSessionHandle, &ckMechanism, ckUnwrappingKeyHandle,
                  ckpWrappedKey, ckWrappedKeyLength,
                  ckpAttributes, ckAttributesLength, &ckKeyHandle);
 
-    jKeyHandle = ckLongToJLong(ckKeyHandle);
-
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jKeyHandle = ckLongToJLong(ckKeyHandle);
 
 #if 0
-    /* cheack, if we must give a initialization vector back to Java */
-    if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
-        /* we must copy back the unwrapped key info to the jMechanism object */
-        copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
+        /* cheack, if we must give a initialization vector back to Java */
+        if (ckMechanism.mechanism == CKM_KEY_WRAP_SET_OAEP) {
+            /* we must copy back the unwrapped key info to the jMechanism object */
+            copyBackSetUnwrappedKey(env, &ckMechanism, jMechanism);
+        }
+#endif
     }
-#endif
 
-    free(ckpWrappedKey);
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+    free(ckpWrappedKey);
 
     return jKeyHandle ;
 }
@@ -360,8 +394,7 @@
  */
 void copyBackTLSPrfParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-    jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-    jclass jTLSPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+    jclass jMechanismClass, jTLSPrfParamsClass;
     CK_TLS_PRF_PARAMS *ckTLSPrfParams;
     jobject jTLSPrfParams;
     jfieldID fieldID;
@@ -374,8 +407,10 @@
     int i;
 
     /* get mechanism */
+    jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+    if (jMechanismClass == NULL) { return; }
     fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return; }
     jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
     ckMechanismType = jLongToCKULong(jMechanismType);
     if (ckMechanismType != ckMechanism->mechanism) {
@@ -388,12 +423,14 @@
     if (ckTLSPrfParams != NULL_PTR) {
         /* get the Java CK_TLS_PRF_PARAMS object (pParameter) */
         fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-        assert(fieldID != 0);
+        if (fieldID == NULL) { return; }
         jTLSPrfParams = (*env)->GetObjectField(env, jMechanism, fieldID);
 
         /* copy back the client IV */
+        jTLSPrfParamsClass = (*env)->FindClass(env, CLASS_TLS_PRF_PARAMS);
+        if (jTLSPrfParamsClass == NULL) { return; }
         fieldID = (*env)->GetFieldID(env, jTLSPrfParamsClass, "pOutput", "[B");
-        assert(fieldID != 0);
+        if (fieldID == NULL) { return; }
         jOutput = (*env)->GetObjectField(env, jTLSPrfParams, fieldID);
         output = ckTLSPrfParams->pOutput;
 
@@ -402,26 +439,21 @@
         if (jOutput != NULL) {
             jLength = (*env)->GetArrayLength(env, jOutput);
             jBytes = (*env)->GetByteArrayElements(env, jOutput, NULL);
+            if (jBytes == NULL) { return; }
+
             /* copy the bytes to the Java buffer */
             for (i=0; i < jLength; i++) {
                 jBytes[i] = ckByteToJByte(output[i]);
             }
             /* copy back the Java buffer to the object */
             (*env)->ReleaseByteArrayElements(env, jOutput, jBytes, 0);
-            // free malloc'd data
-            free(output);
         }
 
         // free malloc'd data
-        if (ckTLSPrfParams->pSeed != NULL) {
-            free(ckTLSPrfParams->pSeed);
-        }
-        if (ckTLSPrfParams->pLabel != NULL) {
-            free(ckTLSPrfParams->pLabel);
-        }
-        if (ckTLSPrfParams->pulOutputLen != NULL) {
-            free(ckTLSPrfParams->pulOutputLen);
-        }
+        free(ckTLSPrfParams->pSeed);
+        free(ckTLSPrfParams->pLabel);
+        free(ckTLSPrfParams->pulOutputLen);
+        free(ckTLSPrfParams->pOutput);
     }
 }
 
@@ -456,8 +488,16 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
+
     ckBaseKeyHandle = jLongToCKULong(jBaseKeyHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) {
+        if (ckMechanism.pParameter != NULL_PTR) {
+            free(ckMechanism.pParameter);
+        }
+        return 0L;
+    }
 
     switch (ckMechanism.mechanism) {
     case CKM_SSL3_KEY_AND_MAC_DERIVE:
@@ -476,14 +516,8 @@
                  ckpAttributes, ckAttributesLength, phKey);
 
     jKeyHandle = ckLongToJLong(ckKeyHandle);
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    if (ckpAttributes != NULL) {
-        free(ckpAttributes);
-    }
+
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     switch (ckMechanism.mechanism) {
     case CKM_SSL3_MASTER_KEY_DERIVE:
@@ -512,11 +546,10 @@
         break;
     }
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     return jKeyHandle ;
 }
@@ -529,9 +562,7 @@
  */
 void copyBackClientVersion(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-  jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-  jclass jSSL3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
-  jclass jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+  jclass jMechanismClass, jSSL3MasterKeyDeriveParamsClass, jVersionClass;
   CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ckSSL3MasterKeyDeriveParams;
   CK_VERSION *ckVersion;
   jfieldID fieldID;
@@ -541,8 +572,10 @@
   jobject jVersion;
 
   /* get mechanism */
+  jMechanismClass = (*env)->FindClass(env, CLASS_MECHANISM);
+  if (jMechanismClass == NULL) { return; }
   fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-  assert(fieldID != 0);
+  if (fieldID == NULL) { return; }
   jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
   ckMechanismType = jLongToCKULong(jMechanismType);
   if (ckMechanismType != ckMechanism->mechanism) {
@@ -558,27 +591,31 @@
     if (ckVersion != NULL_PTR) {
       /* get the Java CK_SSL3_MASTER_KEY_DERIVE_PARAMS (pParameter) */
       fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
+
       jSSL3MasterKeyDeriveParams = (*env)->GetObjectField(env, jMechanism, fieldID);
 
       /* get the Java CK_VERSION */
+      jSSL3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS);
+      if (jSSL3MasterKeyDeriveParamsClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3MasterKeyDeriveParamsClass, "pVersion", "L"CLASS_VERSION";");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jVersion = (*env)->GetObjectField(env, jSSL3MasterKeyDeriveParams, fieldID);
 
       /* now copy back the version from the native structure to the Java structure */
 
       /* copy back the major version */
+      jVersionClass = (*env)->FindClass(env, CLASS_VERSION);
+      if (jVersionClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jVersionClass, "major", "B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetByteField(env, jVersion, fieldID, ckByteToJByte(ckVersion->major));
 
       /* copy back the minor version */
       fieldID = (*env)->GetFieldID(env, jVersionClass, "minor", "B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetByteField(env, jVersion, fieldID, ckByteToJByte(ckVersion->minor));
     }
-
   }
 }
 
@@ -591,9 +628,7 @@
  */
 void copyBackSSLKeyMatParams(JNIEnv *env, CK_MECHANISM *ckMechanism, jobject jMechanism)
 {
-  jclass jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
-  jclass jSSL3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
-  jclass jSSL3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+  jclass jMechanismClass, jSSL3KeyMatParamsClass, jSSL3KeyMatOutClass;
   CK_SSL3_KEY_MAT_PARAMS *ckSSL3KeyMatParam;
   CK_SSL3_KEY_MAT_OUT *ckSSL3KeyMatOut;
   jfieldID fieldID;
@@ -608,8 +643,10 @@
   int i;
 
   /* get mechanism */
+  jMechanismClass= (*env)->FindClass(env, CLASS_MECHANISM);
+  if (jMechanismClass == NULL) { return; }
   fieldID = (*env)->GetFieldID(env, jMechanismClass, "mechanism", "J");
-  assert(fieldID != 0);
+  if (fieldID == NULL) { return; }
   jMechanismType = (*env)->GetLongField(env, jMechanism, fieldID);
   ckMechanismType = jLongToCKULong(jMechanismType);
   if (ckMechanismType != ckMechanism->mechanism) {
@@ -633,74 +670,78 @@
     if (ckSSL3KeyMatOut != NULL_PTR) {
       /* get the Java CK_SSL3_KEY_MAT_PARAMS (pParameter) */
       fieldID = (*env)->GetFieldID(env, jMechanismClass, "pParameter", "Ljava/lang/Object;");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jSSL3KeyMatParam = (*env)->GetObjectField(env, jMechanism, fieldID);
 
       /* get the Java CK_SSL3_KEY_MAT_OUT */
+      jSSL3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS);
+      if (jSSL3KeyMatParamsClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatParamsClass, "pReturnedKeyMaterial", "L"CLASS_SSL3_KEY_MAT_OUT";");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jSSL3KeyMatOut = (*env)->GetObjectField(env, jSSL3KeyMatParam, fieldID);
 
       /* now copy back all the key handles and the initialization vectors */
       /* copy back client MAC secret handle */
+      jSSL3KeyMatOutClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_OUT);
+      if (jSSL3KeyMatOutClass == NULL) { return; }
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hClientMacSecret", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hClientMacSecret));
 
       /* copy back server MAC secret handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hServerMacSecret", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hServerMacSecret));
 
       /* copy back client secret key handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hClientKey", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hClientKey));
 
       /* copy back server secret key handle */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "hServerKey", "J");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       (*env)->SetLongField(env, jSSL3KeyMatOut, fieldID, ckULongToJLong(ckSSL3KeyMatOut->hServerKey));
 
       /* copy back the client IV */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "pIVClient", "[B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jIV = (*env)->GetObjectField(env, jSSL3KeyMatOut, fieldID);
       iv = ckSSL3KeyMatOut->pIVClient;
 
       if (jIV != NULL) {
         jLength = (*env)->GetArrayLength(env, jIV);
         jBytes = (*env)->GetByteArrayElements(env, jIV, NULL);
+        if (jBytes == NULL) { return; }
         /* copy the bytes to the Java buffer */
         for (i=0; i < jLength; i++) {
           jBytes[i] = ckByteToJByte(iv[i]);
         }
         /* copy back the Java buffer to the object */
         (*env)->ReleaseByteArrayElements(env, jIV, jBytes, 0);
-        // free malloc'd data
-        free(iv);
       }
+      // free malloc'd data
+      free(ckSSL3KeyMatOut->pIVClient);
 
       /* copy back the server IV */
       fieldID = (*env)->GetFieldID(env, jSSL3KeyMatOutClass, "pIVServer", "[B");
-      assert(fieldID != 0);
+      if (fieldID == NULL) { return; }
       jIV = (*env)->GetObjectField(env, jSSL3KeyMatOut, fieldID);
       iv = ckSSL3KeyMatOut->pIVServer;
 
       if (jIV != NULL) {
         jLength = (*env)->GetArrayLength(env, jIV);
         jBytes = (*env)->GetByteArrayElements(env, jIV, NULL);
+        if (jBytes == NULL) { return; }
         /* copy the bytes to the Java buffer */
         for (i=0; i < jLength; i++) {
           jBytes[i] = ckByteToJByte(iv[i]);
         }
         /* copy back the Java buffer to the object */
         (*env)->ReleaseByteArrayElements(env, jIV, jBytes, 0);
-        // free malloc'd data
-        free(iv);
       }
-
       // free malloc'd data
+      free(ckSSL3KeyMatOut->pIVServer);
       free(ckSSL3KeyMatOut);
     }
   }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_mutex.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -76,7 +76,7 @@
 CK_C_INITIALIZE_ARGS_PTR makeCKInitArgsAdapter(JNIEnv *env, jobject jInitArgs)
 {
     CK_C_INITIALIZE_ARGS_PTR ckpInitArgs;
-    jclass jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    jclass jInitArgsClass;
     jfieldID fieldID;
     jlong jFlags;
     jobject jReserved;
@@ -91,10 +91,20 @@
 
     /* convert the Java InitArgs object to a pointer to a CK_C_INITIALIZE_ARGS structure */
     ckpInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
+    if (ckpInitArgs == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL_PTR;
+    }
 
     /* Set the mutex functions that will call the Java mutex functions, but
      * only set it, if the field is not null.
      */
+    jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) {
+        free(ckpInitArgs);
+        return NULL;
+    }
+
 #ifdef NO_CALLBACKS
     ckpInitArgs->CreateMutex = NULL_PTR;
     ckpInitArgs->DestroyMutex = NULL_PTR;
@@ -102,22 +112,22 @@
     ckpInitArgs->UnlockMutex = NULL_PTR;
 #else
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "CreateMutex", "Lsun/security/pkcs11/wrapper/CK_CREATEMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->CreateMutex = (jMutexHandler != NULL) ? &callJCreateMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "DestroyMutex", "Lsun/security/pkcs11/wrapper/CK_DESTROYMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->DestroyMutex = (jMutexHandler != NULL) ? &callJDestroyMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "LockMutex", "Lsun/security/pkcs11/wrapper/CK_LOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->LockMutex = (jMutexHandler != NULL) ? &callJLockMutex : NULL_PTR;
 
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jMutexHandler = (*env)->GetObjectField(env, jInitArgs, fieldID);
     ckpInitArgs->UnlockMutex = (jMutexHandler != NULL) ? &callJUnlockMutex : NULL_PTR;
 
@@ -129,19 +139,25 @@
         /* set the global object jInitArgs so that the right Java mutex functions will be called */
         jInitArgsObject = (*env)->NewGlobalRef(env, jInitArgs);
         ckpGlobalInitArgs = (CK_C_INITIALIZE_ARGS_PTR) malloc(sizeof(CK_C_INITIALIZE_ARGS));
+        if (ckpGlobalInitArgs == NULL) {
+            free(ckpInitArgs);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL_PTR;
+        }
+
         memcpy(ckpGlobalInitArgs, ckpInitArgs, sizeof(CK_C_INITIALIZE_ARGS));
     }
 #endif /* NO_CALLBACKS */
 
     /* convert and set the flags field */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "flags", "J");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jFlags = (*env)->GetLongField(env, jInitArgs, fieldID);
     ckpInitArgs->flags = jLongToCKULong(jFlags);
 
     /* pReserved should be NULL_PTR in this version */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "pReserved", "Ljava/lang/Object;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return NULL; }
     jReserved = (*env)->GetObjectField(env, jInitArgs, fieldID);
 
     /* we try to convert the reserved parameter also */
@@ -201,20 +217,21 @@
         wasAttached = 1;
     }
 
-
     jCreateMutexClass = (*env)->FindClass(env, CLASS_CREATEMUTEX);
+    if (jCreateMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* get the CreateMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "CreateMutex", "Lsun/security/pkcs11/wrapper/CK_CREATEMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jCreateMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jCreateMutex != 0);
 
     /* call the CK_CREATEMUTEX function of the CreateMutex object */
     /* and get the new Java mutex object */
     methodID = (*env)->GetMethodID(env, jCreateMutexClass, "CK_CREATEMUTEX", "()Ljava/lang/Object;");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     jMutex = (*env)->CallObjectMethod(env, jCreateMutex, methodID);
 
     /* set a global reference on the Java mutex */
@@ -227,10 +244,13 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
+
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -292,22 +312,23 @@
         wasAttached = 1;
     }
 
-
     jDestroyMutexClass = (*env)->FindClass(env, CLASS_DESTROYMUTEX);
+    if (jDestroyMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the DestroyMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "DestroyMutex", "Lsun/security/pkcs11/wrapper/CK_DESTROYMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jDestroyMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jDestroyMutex != 0);
 
     /* call the CK_DESTROYMUTEX method of the DestroyMutex object */
     methodID = (*env)->GetMethodID(env, jDestroyMutexClass, "CK_DESTROYMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jDestroyMutex, methodID, jMutex);
 
     /* delete the global reference on the Java mutex */
@@ -318,10 +339,12 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -383,33 +406,35 @@
         wasAttached = 1;
     }
 
-
     jLockMutexClass = (*env)->FindClass(env, CLASS_LOCKMUTEX);
+    if (jLockMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the LockMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "LockMutex", "Lsun/security/pkcs11/wrapper/CK_LOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jLockMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jLockMutex != 0);
 
     /* call the CK_LOCKMUTEX method of the LockMutex object */
     methodID = (*env)->GetMethodID(env, jLockMutexClass, "CK_LOCKMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jLockMutex, methodID, jMutex);
 
-
     /* check, if callback threw an exception */
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
@@ -471,33 +496,35 @@
         wasAttached = 1;
     }
 
-
     jUnlockMutexClass = (*env)->FindClass(env, CLASS_UNLOCKMUTEX);
+    if (jUnlockMutexClass == NULL) { return rv; }
     jInitArgsClass = (*env)->FindClass(env, CLASS_C_INITIALIZE_ARGS);
+    if (jInitArgsClass == NULL) { return rv; }
 
     /* convert the CK-type mutex to a Java mutex */
     jMutex = ckVoidPtrToJObject(pMutex);
 
     /* get the UnlockMutex object out of the jInitArgs object */
     fieldID = (*env)->GetFieldID(env, jInitArgsClass, "UnlockMutex", "Lsun/security/pkcs11/wrapper/CK_UNLOCKMUTEX;");
-    assert(fieldID != 0);
+    if (fieldID == NULL) { return rv; }
     jUnlockMutex = (*env)->GetObjectField(env, jInitArgsObject, fieldID);
     assert(jUnlockMutex != 0);
 
     /* call the CK_UNLOCKMUTEX method of the UnLockMutex object */
     methodID = (*env)->GetMethodID(env, jUnlockMutexClass, "CK_UNLOCKMUTEX", "(Ljava/lang/Object;)V");
-    assert(methodID != 0);
+    if (methodID == NULL) { return rv; }
     (*env)->CallVoidMethod(env, jUnlockMutex, methodID, jMutex);
 
-
     /* check, if callback threw an exception */
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
         methodID = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(methodID != 0);
+        if (methodID == NULL) { return rv; }
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, methodID);
         rv = jLongToCKULong(errorCode);
     }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_objmgmt.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -81,16 +81,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     rv = (*ckpFunctions->C_CreateObject)(ckSessionHandle, ckpAttributes, ckAttributesLength, &ckObjectHandle);
 
     jObjectHandle = ckULongToJLong(ckObjectHandle);
-    for(i=0; i<ckAttributesLength; i++)
-        if(ckpAttributes[i].pValue != NULL_PTR)
-            free(ckpAttributes[i].pValue);
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     return jObjectHandle ;
 }
@@ -126,14 +124,12 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return 0L; }
 
     rv = (*ckpFunctions->C_CopyObject)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength, &ckNewObjectHandle);
 
     jNewObjectHandle = ckULongToJLong(ckNewObjectHandle);
-    for(i=0; i<ckAttributesLength; i++)
-        if(ckpAttributes[i].pValue != NULL_PTR)
-            free(ckpAttributes[i].pValue);
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
@@ -164,7 +160,7 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
 
     rv = (*ckpFunctions->C_DestroyObject)(ckSessionHandle, ckObjectHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -194,7 +190,7 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
 
     rv = (*ckpFunctions->C_GetObjectSize)(ckSessionHandle, ckObjectHandle, &ckObjectSize);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
 
     jObjectSize = ckULongToJLong(ckObjectSize);
 
@@ -221,7 +217,7 @@
     CK_ATTRIBUTE_PTR ckpAttributes = NULL_PTR;
     CK_ULONG ckAttributesLength;
     CK_ULONG ckBufferLength;
-    CK_ULONG i;
+    CK_ULONG i, j;
     jobject jAttribute;
     CK_RV rv;
 
@@ -238,19 +234,20 @@
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     TRACE1("jAttributeArrayToCKAttributeArray now with jTemplate = %d", jTemplate);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     TRACE2("DEBUG: jAttributeArrayToCKAttributeArray finished with ckpAttribute = %d, Length = %d\n", ckpAttributes, ckAttributesLength);
 
     /* first set all pValue to NULL, to get the needed buffer length */
     for(i = 0; i < ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
+        if (ckpAttributes[i].pValue != NULL_PTR) {
             free(ckpAttributes[i].pValue);
+            ckpAttributes[i].pValue = NULL_PTR;
         }
     }
-    for (i = 0; i < ckAttributesLength; i++) {
-        ckpAttributes[i].pValue = NULL_PTR;
-    }
+
     rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
         free(ckpAttributes);
         return ;
     }
@@ -261,27 +258,34 @@
     for (i = 0; i < ckAttributesLength; i++) {
         ckBufferLength = sizeof(CK_BYTE) * ckpAttributes[i].ulValueLen;
         ckpAttributes[i].pValue = (void *) malloc(ckBufferLength);
+        if (ckpAttributes[i].pValue == NULL) {
+            freeCKAttributeArray(ckpAttributes, i);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
         ckpAttributes[i].ulValueLen = ckBufferLength;
     }
 
     /* now get the attributes with all values */
     rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
 
-    /* copy back the values to the Java attributes */
-    for (i = 0; i < ckAttributesLength; i++) {
-        jAttribute = ckAttributePtrToJAttribute(env, &(ckpAttributes[i]));
-        (*env)->SetObjectArrayElement(env, jTemplate, i, jAttribute);
-    }
-
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        /* copy back the values to the Java attributes */
+        for (i = 0; i < ckAttributesLength; i++) {
+            jAttribute = ckAttributePtrToJAttribute(env, &(ckpAttributes[i]));
+            if (jAttribute == NULL) {
+                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+                return;
+            }
+            (*env)->SetObjectArrayElement(env, jTemplate, i, jAttribute);
+            if ((*env)->ExceptionCheck(env)) {
+                freeCKAttributeArray(ckpAttributes, ckAttributesLength);
+                return;
+            }
         }
     }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
     TRACE0("FINISHED\n");
-
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return ; }
 }
 #endif
 
@@ -312,15 +316,11 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckObjectHandle = jLongToCKULong(jObjectHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_SetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
 
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
@@ -355,15 +355,11 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jAttributeArrayToCKAttributeArray(env, jTemplate, &ckpAttributes, &ckAttributesLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_FindObjectsInit)(ckSessionHandle, ckpAttributes, ckAttributesLength);
 
-    for(i=0; i<ckAttributesLength; i++) {
-        if(ckpAttributes[i].pValue != NULL_PTR) {
-            free(ckpAttributes[i].pValue);
-        }
-    }
-    free(ckpAttributes);
+    freeCKAttributeArray(ckpAttributes, ckAttributesLength);
     TRACE0("FINISHED\n");
 
     if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
@@ -397,14 +393,18 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckMaxObjectLength = jLongToCKULong(jMaxObjectCount);
     ckpObjectHandleArray = (CK_OBJECT_HANDLE_PTR) malloc(sizeof(CK_OBJECT_HANDLE) * ckMaxObjectLength);
+    if (ckpObjectHandleArray == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_FindObjects)(ckSessionHandle, ckpObjectHandleArray, ckMaxObjectLength, &ckActualObjectCount);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jObjectHandleArray = ckULongArrayToJLongArray(env, ckpObjectHandleArray, ckActualObjectCount);
+    }
 
-    jObjectHandleArray = ckULongArrayToJLongArray(env, ckpObjectHandleArray, ckActualObjectCount);
     free(ckpObjectHandleArray);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jObjectHandleArray ;
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sessmgmt.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -97,6 +97,10 @@
 #ifndef NO_CALLBACKS
     if (jNotify != NULL) {
         notifyEncapsulation = (NotifyEncapsulation *) malloc(sizeof(NotifyEncapsulation));
+        if (notifyEncapsulation == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0L;
+        }
         notifyEncapsulation->jApplicationData = (jApplication != NULL)
                 ? (*env)->NewGlobalRef(env, jApplication)
                 : NULL;
@@ -118,7 +122,18 @@
     TRACE0(" ... ");
 
     rv = (*ckpFunctions->C_OpenSession)(ckSlotID, ckFlags, ckpApplication, ckNotify, &ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return 0L ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+#ifndef NO_CALLBACKS
+        if (notifyEncapsulation != NULL) {
+            if (notifyEncapsulation->jApplicationData != NULL) {
+                (*env)->DeleteGlobalRef(env, jApplication);
+            }
+            (*env)->DeleteGlobalRef(env, jNotify);
+            free(notifyEncapsulation);
+        }
+#endif /* NO_CALLBACKS */
+        return 0L;
+    }
 
     TRACE0("got session");
     TRACE1(", SessionHandle=%u", ckSessionHandle);
@@ -163,7 +178,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_CloseSession)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 
 #ifndef NO_CALLBACKS
     notifyEncapsulation = removeNotifyEntry(env, ckSessionHandle);
@@ -208,7 +223,7 @@
     ckSlotID = jLongToCKULong(jSlotID);
 
     rv = (*ckpFunctions->C_CloseAllSessions)(ckSlotID);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 
 #ifndef NO_CALLBACKS
     /* Remove all notify callback helper objects. */
@@ -250,10 +265,9 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_GetSessionInfo)(ckSessionHandle, &ckSessionInfo);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
-    jSessionInfo = ckSessionInfoPtrToJSessionInfo(env, &ckSessionInfo);
-
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSessionInfo = ckSessionInfoPtrToJSessionInfo(env, &ckSessionInfo);
+    }
     return jSessionInfo ;
 }
 #endif
@@ -274,7 +288,7 @@
     CK_SESSION_HANDLE ckSessionHandle;
     CK_BYTE_PTR ckpState;
     CK_ULONG ckStateLength;
-    jbyteArray jState;
+    jbyteArray jState = NULL;
     CK_RV rv;
 
     CK_FUNCTION_LIST_PTR ckpFunctions = getFunctionList(env, obj);
@@ -283,17 +297,20 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_GetOperationState)(ckSessionHandle, NULL_PTR, &ckStateLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
 
     ckpState = (CK_BYTE_PTR) malloc(ckStateLength);
+    if (ckpState == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     rv = (*ckpFunctions->C_GetOperationState)(ckSessionHandle, ckpState, &ckStateLength);
-
-    jState = ckByteArrayToJByteArray(env, ckpState, ckStateLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jState = ckByteArrayToJByteArray(env, ckpState, ckStateLength);
+    }
     free(ckpState);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jState ;
 }
 #endif
@@ -325,6 +342,8 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jOperationState, &ckpState, &ckStateLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckEncryptionKeyHandle = jLongToCKULong(jEncryptionKeyHandle);
     ckAuthenticationKeyHandle = jLongToCKULong(jAuthenticationKeyHandle);
 
@@ -332,7 +351,7 @@
 
     free(ckpState);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -362,12 +381,13 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     ckUserType = jLongToCKULong(jUserType);
     jCharArrayToCKCharArray(env, jPin, &ckpPinArray, &ckPinLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     rv = (*ckpFunctions->C_Login)(ckSessionHandle, ckUserType, ckpPinArray, ckPinLength);
 
     free(ckpPinArray);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -391,7 +411,7 @@
     ckSessionHandle = jLongToCKULong(jSessionHandle);
 
     rv = (*ckpFunctions->C_Logout)(ckSessionHandle);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -410,10 +430,14 @@
     NotifyListNode *currentNode, *newNode;
 
     if (notifyEncapsulation == NULL) {
-        return ;
+        return;
     }
 
     newNode = (NotifyListNode *) malloc(sizeof(NotifyListNode));
+    if (newNode == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     newNode->hSession = hSession;
     newNode->notifyEncapsulation = notifyEncapsulation;
     newNode->next = NULL;
@@ -578,9 +602,10 @@
     jEvent = ckULongToJLong(event);
 
     ckNotifyClass = (*env)->FindClass(env, CLASS_NOTIFY);
-    assert(ckNotifyClass != 0);
+    if (ckNotifyClass == NULL) { return rv; }
     jmethod = (*env)->GetMethodID(env, ckNotifyClass, "CK_NOTIFY", "(JJLjava/lang/Object;)V");
-    assert(jmethod != 0);
+    if (jmethod == NULL) { return rv; }
+
     (*env)->CallVoidMethod(env, notifyEncapsulation->jNotifyObject, jmethod,
                          jSessionHandle, jEvent, notifyEncapsulation->jApplicationData);
 
@@ -588,10 +613,14 @@
     pkcs11Exception = (*env)->ExceptionOccurred(env);
 
     if (pkcs11Exception != NULL) {
+        /* TBD: clear the pending exception with ExceptionClear? */
         /* The was an exception thrown, now we get the error-code from it */
         pkcs11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
+        if (pkcs11ExceptionClass == NULL) { return rv; }
+
         jmethod = (*env)->GetMethodID(env, pkcs11ExceptionClass, "getErrorCode", "()J");
-        assert(jmethod != 0);
+        if (jmethod == NULL) { return rv; }
+
         errorCode = (*env)->CallLongMethod(env, pkcs11Exception, jmethod);
         rv = jLongToCKULong(errorCode);
     }
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_sign.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2005 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -77,15 +77,16 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_SignInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -117,14 +118,23 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
+    if ((*env)->ExceptionCheck(env)) { return NULL; }
 
     /* START standard code */
 
     /* first determine the length of the signature */
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, NULL_PTR, &ckSignatureLength);
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        free(ckpData);
+        return NULL;
+    }
 
     ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
+    if (ckpSignature == NULL) {
+        free(ckpData);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
 
     /* now get the signature */
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
@@ -134,22 +144,31 @@
     /* START workaround code for operation abort bug in pkcs#11 of Datakey and iButton */
 /*
     ckpSignature = (CK_BYTE_PTR) malloc(256 * sizeof(CK_BYTE));
+    if (ckpSignature == NULL) {
+        free(ckpData);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
 
     if (rv == CKR_BUFFER_TOO_SMALL) {
         free(ckpSignature);
         ckpSignature = (CK_BYTE_PTR) malloc(ckSignatureLength * sizeof(CK_BYTE));
+        if (ckpSignature == NULL) {
+            free(ckpData);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         rv = (*ckpFunctions->C_Sign)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, &ckSignatureLength);
     }
  */
     /* END workaround code */
-
-    jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
+    if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
+        jSignature = ckByteArrayToJByteArray(env, ckpSignature, ckSignatureLength);
+    }
     free(ckpData);
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return NULL ; }
-
     return jSignature ;
 }
 #endif
@@ -189,14 +208,22 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
         rv = (*ckpFunctions->C_SignUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
             if (bufP != BUF) {
                 free(bufP);
             }
@@ -206,9 +233,7 @@
         jInLen -= chunkLen;
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
 }
 #endif
 
@@ -244,15 +269,18 @@
     rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
     if (rv == CKR_BUFFER_TOO_SMALL) {
         bufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         rv = (*ckpFunctions->C_SignFinal)(ckSessionHandle, bufP, &ckSignatureLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         jSignature = ckByteArrayToJByteArray(env, bufP, ckSignatureLength);
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
+
     return jSignature;
 }
 #endif
@@ -280,11 +308,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_SignRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
@@ -323,26 +353,38 @@
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
     } else {
-        inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+        if (inBufP != INBUF) { free(inBufP); }
+        return 0;
+    }
     rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     /* re-alloc larger buffer if it fits into our Java buffer */
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckSignatureLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckSignatureLength);
+        if (outBufP == NULL) {
+            if (inBufP != INBUF) {
+                free(inBufP);
+            }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
         rv = (*ckpFunctions->C_SignRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckSignatureLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckSignatureLength, (jbyte *)outBufP);
     }
 
-    if (inBufP != INBUF) {
-        free(inBufP);
-    }
-    if (outBufP != OUTBUF) {
-        free(outBufP);
-    }
+    if (inBufP != INBUF) { free(inBufP); }
+    if (outBufP != OUTBUF) { free(outBufP); }
+
     return ckSignatureLength;
 }
 #endif
@@ -370,6 +412,8 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_VerifyInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
@@ -378,7 +422,7 @@
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -409,7 +453,13 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jData, &ckpData, &ckDataLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
+    if ((*env)->ExceptionCheck(env)) {
+        free(ckpData);
+        return;
+    }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_Verify)(ckSessionHandle, ckpData, ckDataLength, ckpSignature, ckSignatureLength);
@@ -417,7 +467,7 @@
     free(ckpData);
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -456,26 +506,31 @@
         bufP = BUF;
     } else {
         bufLen = min(MAX_HEAP_BUFFER_LEN, jInLen);
-        bufP = (CK_BYTE_PTR)malloc((size_t)bufLen);
+        bufP = (CK_BYTE_PTR) malloc((size_t)bufLen);
+        if (bufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
     }
 
     while (jInLen > 0) {
         jsize chunkLen = min(bufLen, jInLen);
         (*env)->GetByteArrayRegion(env, jIn, jInOfs, chunkLen, (jbyte *)bufP);
+        if ((*env)->ExceptionCheck(env)) {
+            if (bufP != BUF) { free(bufP); }
+            return;
+        }
+
         rv = (*ckpFunctions->C_VerifyUpdate)(ckSessionHandle, bufP, chunkLen);
-        if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
-            if (bufP != BUF) {
-                free(bufP);
-            }
+        if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) {
+            if (bufP != BUF) { free(bufP); }
             return;
         }
         jInOfs += chunkLen;
         jInLen -= chunkLen;
     }
 
-    if (bufP != BUF) {
-        free(bufP);
-    }
+    if (bufP != BUF) { free(bufP); }
 }
 #endif
 
@@ -502,13 +557,14 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jByteArrayToCKByteArray(env, jSignature, &ckpSignature, &ckSignatureLength);
+    if ((*env)->ExceptionCheck(env)) { return; }
 
     /* verify the signature */
     rv = (*ckpFunctions->C_VerifyFinal)(ckSessionHandle, ckpSignature, ckSignatureLength);
 
     free(ckpSignature);
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -535,15 +591,17 @@
 
     ckSessionHandle = jLongToCKULong(jSessionHandle);
     jMechanismToCKMechanism(env, jMechanism, &ckMechanism);
+    if ((*env)->ExceptionCheck(env)) { return; }
+
     ckKeyHandle = jLongToCKULong(jKeyHandle);
 
     rv = (*ckpFunctions->C_VerifyRecoverInit)(ckSessionHandle, &ckMechanism, ckKeyHandle);
 
-    if(ckMechanism.pParameter != NULL_PTR) {
+    if (ckMechanism.pParameter != NULL_PTR) {
         free(ckMechanism.pParameter);
     }
 
-    if(ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
+    if (ckAssertReturnValueOK(env, rv) != CK_ASSERT_OK) { return; }
 }
 #endif
 
@@ -578,26 +636,38 @@
     if (jInLen <= MAX_STACK_BUFFER_LEN) {
         inBufP = INBUF;
     } else {
-        inBufP = (CK_BYTE_PTR)malloc((size_t)jInLen);
+        inBufP = (CK_BYTE_PTR) malloc((size_t)jInLen);
+        if (inBufP == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
     }
 
     (*env)->GetByteArrayRegion(env, jIn, jInOfs, jInLen, (jbyte *)inBufP);
+    if ((*env)->ExceptionCheck(env)) {
+        if (inBufP != INBUF) { free(inBufP); }
+        return 0;
+    }
+
     rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
+
     /* re-alloc larger buffer if it fits into our Java buffer */
     if ((rv == CKR_BUFFER_TOO_SMALL) && (ckDataLength <= jIntToCKULong(jOutLen))) {
         outBufP = (CK_BYTE_PTR) malloc(ckDataLength);
+        if (outBufP == NULL) {
+            if (inBufP != INBUF) { free(inBufP); }
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return 0;
+        }
         rv = (*ckpFunctions->C_VerifyRecover)(ckSessionHandle, inBufP, jInLen, outBufP, &ckDataLength);
     }
     if (ckAssertReturnValueOK(env, rv) == CK_ASSERT_OK) {
         (*env)->SetByteArrayRegion(env, jOut, jOutOfs, ckDataLength, (jbyte *)outBufP);
     }
 
-    if (inBufP != INBUF) {
-        free(inBufP);
-    }
-    if (outBufP != OUTBUF) {
-        free(outBufP);
-    }
+    if (inBufP != INBUF) { free(inBufP); }
+    if (outBufP != OUTBUF) { free(outBufP); }
+
     return ckDataLength;
 }
 #endif
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/p11_util.c	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -73,11 +73,11 @@
     jmethodID jConstructor;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Object");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jObjectClass, "<init>", "()V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jLockObject = (*env)->NewObject(env, jObjectClass, jConstructor);
-    assert(jLockObject != 0);
+    if (jLockObject == NULL) { return NULL; }
     jLockObject = (*env)->NewGlobalRef(env, jLockObject);
 
     return jLockObject ;
@@ -200,84 +200,30 @@
         return 0L ;
     } else {
         jPKCS11ExceptionClass = (*env)->FindClass(env, CLASS_PKCS11EXCEPTION);
-        assert(jPKCS11ExceptionClass != 0);
-        jConstructor = (*env)->GetMethodID(env, jPKCS11ExceptionClass, "<init>", "(J)V");
-        assert(jConstructor != 0);
-        jErrorCode = ckULongToJLong(returnValue);
-        jPKCS11Exception = (jthrowable) (*env)->NewObject(env, jPKCS11ExceptionClass, jConstructor, jErrorCode);
-        (*env)->Throw(env, jPKCS11Exception);
+        if (jPKCS11ExceptionClass != NULL) {
+            jConstructor = (*env)->GetMethodID(env, jPKCS11ExceptionClass, "<init>", "(J)V");
+            if (jConstructor != NULL) {
+                jErrorCode = ckULongToJLong(returnValue);
+                jPKCS11Exception = (jthrowable) (*env)->NewObject(env, jPKCS11ExceptionClass, jConstructor, jErrorCode);
+                if (jPKCS11Exception != NULL) {
+                    (*env)->Throw(env, jPKCS11Exception);
+                }
+            }
+        }
+        (*env)->DeleteLocalRef(env, jPKCS11ExceptionClass);
         return jErrorCode ;
     }
 }
 
 /*
- * this function simply throws a FileNotFoundException
- *
- * @param env Used to call JNI funktions and to get the Exception class.
- * @param jmessage The message string of the Exception object.
- */
-void throwFileNotFoundException(JNIEnv *env, jstring jmessage)
-{
-    jclass jFileNotFoundExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jFileNotFoundException;
-
-    jFileNotFoundExceptionClass = (*env)->FindClass(env, CLASS_FILE_NOT_FOUND_EXCEPTION);
-    assert(jFileNotFoundExceptionClass != 0);
-
-    jConstructor = (*env)->GetMethodID(env, jFileNotFoundExceptionClass, "<init>", "(Ljava/lang/String;)V");
-    assert(jConstructor != 0);
-    jFileNotFoundException = (jthrowable) (*env)->NewObject(env, jFileNotFoundExceptionClass, jConstructor, jmessage);
-    (*env)->Throw(env, jFileNotFoundException);
-}
-
-/*
- * this function simply throws an IOException
+ * This function simply throws an IOException
  *
  * @param env Used to call JNI funktions and to get the Exception class.
  * @param message The message string of the Exception object.
  */
-void throwIOException(JNIEnv *env, const char * message)
-{
-    jclass jIOExceptionClass;
-
-    jIOExceptionClass = (*env)->FindClass(env, CLASS_IO_EXCEPTION);
-    assert(jIOExceptionClass != 0);
-
-    (*env)->ThrowNew(env, jIOExceptionClass, message);
-}
-
-/*
- * this function simply throws an IOException and takes a unicode
- * messge.
- *
- * @param env Used to call JNI funktions and to get the Exception class.
- * @param message The unicode message string of the Exception object.
- */
-void throwIOExceptionUnicodeMessage(JNIEnv *env, const short *message)
+void throwIOException(JNIEnv *env, const char *message)
 {
-    jclass jIOExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jIOException;
-    jstring jmessage;
-    jsize length;
-    short *currentCharacter;
-
-    jIOExceptionClass = (*env)->FindClass(env, CLASS_IO_EXCEPTION);
-    assert(jIOExceptionClass != 0);
-
-    length = 0;
-    if (message != NULL) {
-        currentCharacter = (short *) message;
-        while (*(currentCharacter++) != 0) length++;
-    }
-
-    jmessage = (*env)->NewString(env, (const jchar *)message, length);
-
-    jConstructor = (*env)->GetMethodID(env, jIOExceptionClass, "<init>", "(Ljava/lang/String;)V");
-    assert(jConstructor != 0);
-    jIOException = (jthrowable) (*env)->NewObject(env, jIOExceptionClass, jConstructor, jmessage);
-    (*env)->Throw(env, jIOException);
+    JNU_ThrowByName(env, CLASS_IO_EXCEPTION, message);
 }
 
 /*
@@ -288,26 +234,9 @@
  * @param env Used to call JNI funktions and to get the Exception class.
  * @param jmessage The message string of the Exception object.
  */
-void throwPKCS11RuntimeException(JNIEnv *env, jstring jmessage)
+void throwPKCS11RuntimeException(JNIEnv *env, const char *message)
 {
-    jclass jPKCS11RuntimeExceptionClass;
-    jmethodID jConstructor;
-    jthrowable jPKCS11RuntimeException;
-
-    jPKCS11RuntimeExceptionClass = (*env)->FindClass(env, CLASS_PKCS11RUNTIMEEXCEPTION);
-    assert(jPKCS11RuntimeExceptionClass != 0);
-
-    if (jmessage == NULL) {
-        jConstructor = (*env)->GetMethodID(env, jPKCS11RuntimeExceptionClass, "<init>", "()V");
-        assert(jConstructor != 0);
-        jPKCS11RuntimeException = (jthrowable) (*env)->NewObject(env, jPKCS11RuntimeExceptionClass, jConstructor);
-        (*env)->Throw(env, jPKCS11RuntimeException);
-    } else {
-        jConstructor = (*env)->GetMethodID(env, jPKCS11RuntimeExceptionClass, "<init>", "(Ljava/lang/String;)V");
-        assert(jConstructor != 0);
-        jPKCS11RuntimeException = (jthrowable) (*env)->NewObject(env, jPKCS11RuntimeExceptionClass, jConstructor, jmessage);
-        (*env)->Throw(env, jPKCS11RuntimeException);
-    }
+    JNU_ThrowByName(env, CLASS_PKCS11RUNTIMEEXCEPTION, message);
 }
 
 /*
@@ -318,9 +247,24 @@
  */
 void throwDisconnectedRuntimeException(JNIEnv *env)
 {
-    jstring jExceptionMessage = (*env)->NewStringUTF(env, "This object is not connected to a module.");
+    throwPKCS11RuntimeException(env, "This object is not connected to a module.");
+}
 
-    throwPKCS11RuntimeException(env, jExceptionMessage);
+/* This function frees the specified CK_ATTRIBUTE array.
+ *
+ * @param attrPtr pointer to the to-be-freed CK_ATTRIBUTE array.
+ * @param len the length of the array
+ */
+void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len)
+{
+    int i;
+
+    for (i=0; i<len; i++) {
+        if (attrPtr[i].pValue != NULL_PTR) {
+            free(attrPtr[i].pValue);
+        }
+    }
+    free(attrPtr);
 }
 
 /*
@@ -375,8 +319,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jboolean*) malloc((*ckpLength) * sizeof(jboolean));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetBooleanArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
+
     *ckpArray = (CK_BBOOL*) malloc ((*ckpLength) * sizeof(CK_BBOOL));
+    if (*ckpArray == NULL) {
+        free(jpTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jBooleanToCKBBool(jpTemp[i]);
     }
@@ -403,13 +361,26 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jbyte*) malloc((*ckpLength) * sizeof(jbyte));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetByteArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
 
     /* if CK_BYTE is the same size as jbyte, we save an additional copy */
     if (sizeof(CK_BYTE) == sizeof(jbyte)) {
         *ckpArray = (CK_BYTE_PTR) jpTemp;
     } else {
         *ckpArray = (CK_BYTE_PTR) malloc ((*ckpLength) * sizeof(CK_BYTE));
+        if (*ckpArray == NULL) {
+            free(jpTemp);
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return;
+        }
         for (i=0; i<(*ckpLength); i++) {
             (*ckpArray)[i] = jByteToCKByte(jpTemp[i]);
         }
@@ -437,8 +408,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jTemp = (jlong*) malloc((*ckpLength) * sizeof(jlong));
+    if (jTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetLongArrayRegion(env, jArray, 0, *ckpLength, jTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jTemp);
+        return;
+    }
+
     *ckpArray = (CK_ULONG_PTR) malloc (*ckpLength * sizeof(CK_ULONG));
+    if (*ckpArray == NULL) {
+        free(jTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jLongToCKULong(jTemp[i]);
     }
@@ -465,8 +450,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jpTemp = (jchar*) malloc((*ckpLength) * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetCharArrayRegion(env, jArray, 0, *ckpLength, jpTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jpTemp);
+        return;
+    }
+
     *ckpArray = (CK_CHAR_PTR) malloc (*ckpLength * sizeof(CK_CHAR));
+    if (*ckpArray == NULL) {
+        free(jpTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jCharToCKChar(jpTemp[i]);
     }
@@ -493,8 +492,22 @@
     }
     *ckpLength = (*env)->GetArrayLength(env, jArray);
     jTemp = (jchar*) malloc((*ckpLength) * sizeof(jchar));
+    if (jTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     (*env)->GetCharArrayRegion(env, jArray, 0, *ckpLength, jTemp);
+    if ((*env)->ExceptionCheck(env)) {
+        free(jTemp);
+        return;
+    }
+
     *ckpArray = (CK_UTF8CHAR_PTR) malloc (*ckpLength * sizeof(CK_UTF8CHAR));
+    if (*ckpArray == NULL) {
+        free(jTemp);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     for (i=0; i<(*ckpLength); i++) {
         (*ckpArray)[i] = jCharToCKUTF8Char(jTemp[i]);
     }
@@ -521,8 +534,15 @@
     }
 
     pCharArray = (*env)->GetStringUTFChars(env, jArray, &isCopy);
+    if (pCharArray == NULL) { return; }
+
     *ckpLength = strlen(pCharArray);
     *ckpArray = (CK_UTF8CHAR_PTR) malloc((*ckpLength + 1) * sizeof(CK_UTF8CHAR));
+    if (*ckpArray == NULL) {
+        (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     strcpy((char*)*ckpArray, pCharArray);
     (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
 }
@@ -552,55 +572,36 @@
     jLength = (*env)->GetArrayLength(env, jArray);
     *ckpLength = jLongToCKULong(jLength);
     *ckpArray = (CK_ATTRIBUTE_PTR) malloc(*ckpLength * sizeof(CK_ATTRIBUTE));
+    if (*ckpArray == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
+    }
     TRACE1(", converting %d attibutes", jLength);
     for (i=0; i<(*ckpLength); i++) {
         TRACE1(", getting %d. attibute", i);
         jAttribute = (*env)->GetObjectArrayElement(env, jArray, i);
+        if ((*env)->ExceptionCheck(env)) {
+            freeCKAttributeArray(*ckpArray, i);
+            return;
+        }
         TRACE1(", jAttribute = %d", jAttribute);
         TRACE1(", converting %d. attibute", i);
         (*ckpArray)[i] = jAttributeToCKAttribute(env, jAttribute);
+        if ((*env)->ExceptionCheck(env)) {
+            freeCKAttributeArray(*ckpArray, i);
+            return;
+        }
     }
     TRACE0("FINISHED\n");
 }
 
 /*
- * converts a jobjectArray to a CK_VOID_PTR array. The allocated memory has to be freed after
- * use!
- * NOTE: this function does not work and is not used yet
- *
- * @param env - used to call JNI funktions to get the array informtaion
- * @param jArray - the Java object array to convert
- * @param ckpArray - the reference, where the pointer to the new CK_VOID_PTR array will be stored
- * @param ckpLength - the reference, where the array length will be stored
- */
-/*
-void jObjectArrayToCKVoidPtrArray(JNIEnv *env, const jobjectArray jArray, CK_VOID_PTR_PTR *ckpArray, CK_ULONG_PTR ckpLength)
-{
-    jobject jTemp;
-    CK_ULONG i;
-
-    if(jArray == NULL) {
-        *ckpArray = NULL_PTR;
-        *ckpLength = 0L;
-        return;
-    }
-    *ckpLength = (*env)->GetArrayLength(env, jArray);
-    *ckpArray = (CK_VOID_PTR_PTR) malloc (*ckpLength * sizeof(CK_VOID_PTR));
-    for (i=0; i<(*ckpLength); i++) {
-        jTemp = (*env)->GetObjectArrayElement(env, jArray, i);
-        (*ckpArray)[i] = jObjectToCKVoidPtr(jTemp);
-    }
-    free(jTemp);
-}
-*/
-
-/*
  * converts a CK_BYTE array and its length to a jbyteArray.
  *
  * @param env - used to call JNI funktions to create the new Java array
  * @param ckpArray - the pointer to the CK_BYTE array to convert
  * @param ckpLength - the length of the array to convert
- * @return - the new Java byte array
+ * @return - the new Java byte array or NULL if error occurred
  */
 jbyteArray ckByteArrayToJByteArray(JNIEnv *env, const CK_BYTE_PTR ckpArray, CK_ULONG ckLength)
 {
@@ -613,17 +614,21 @@
         jpTemp = (jbyte*) ckpArray;
     } else {
         jpTemp = (jbyte*) malloc((ckLength) * sizeof(jbyte));
+        if (jpTemp == NULL) {
+            JNU_ThrowOutOfMemoryError(env, 0);
+            return NULL;
+        }
         for (i=0; i<ckLength; i++) {
             jpTemp[i] = ckByteToJByte(ckpArray[i]);
         }
     }
 
     jArray = (*env)->NewByteArray(env, ckULongToJSize(ckLength));
-    (*env)->SetByteArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetByteArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
 
-    if (sizeof(CK_BYTE) != sizeof(jbyte)) {
-        free(jpTemp);
-    }
+    if (sizeof(CK_BYTE) != sizeof(jbyte)) { free(jpTemp); }
 
     return jArray ;
 }
@@ -643,11 +648,17 @@
     jlongArray jArray;
 
     jpTemp = (jlong*) malloc((ckLength) * sizeof(jlong));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckLongToJLong(ckpArray[i]);
     }
     jArray = (*env)->NewLongArray(env, ckULongToJSize(ckLength));
-    (*env)->SetLongArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetLongArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -668,11 +679,17 @@
     jcharArray jArray;
 
     jpTemp = (jchar*) malloc(ckLength * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckCharToJChar(ckpArray[i]);
     }
     jArray = (*env)->NewCharArray(env, ckULongToJSize(ckLength));
-    (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -693,11 +710,17 @@
     jcharArray jArray;
 
     jpTemp = (jchar*) malloc(ckLength * sizeof(jchar));
+    if (jpTemp == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     for (i=0; i<ckLength; i++) {
         jpTemp[i] = ckUTF8CharToJChar(ckpArray[i]);
     }
     jArray = (*env)->NewCharArray(env, ckULongToJSize(ckLength));
-    (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    if (jArray != NULL) {
+        (*env)->SetCharArrayRegion(env, jArray, 0, ckULongToJSize(ckLength), jpTemp);
+    }
     free(jpTemp);
 
     return jArray ;
@@ -736,12 +759,11 @@
     jboolean jValue;
 
     jValueObjectClass = (*env)->FindClass(env, "java/lang/Boolean");
-    assert(jValueObjectClass != 0);
+    if (jValueObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jValueObjectClass, "<init>", "(Z)V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jValue = ckBBoolToJBoolean(*ckpValue);
     jValueObject = (*env)->NewObject(env, jValueObjectClass, jConstructor, jValue);
-    assert(jValueObject != 0);
 
     return jValueObject ;
 }
@@ -761,12 +783,11 @@
     jlong jValue;
 
     jValueObjectClass = (*env)->FindClass(env, "java/lang/Long");
-    assert(jValueObjectClass != 0);
+    if (jValueObjectClass == NULL) { return NULL; }
     jConstructor = (*env)->GetMethodID(env, jValueObjectClass, "<init>", "(J)V");
-    assert(jConstructor != 0);
+    if (jConstructor == NULL) { return NULL; }
     jValue = ckULongToJLong(*ckpValue);
     jValueObject = (*env)->NewObject(env, jValueObjectClass, jConstructor, jValue);
-    assert(jValueObject != 0);
 
     return jValueObject ;
 }
@@ -787,11 +808,15 @@
     CK_BBOOL *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Boolean");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "booleanValue", "()Z");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallBooleanMethod(env, jObject, jValueMethod);
     ckpValue = (CK_BBOOL *) malloc(sizeof(CK_BBOOL));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jBooleanToCKBBool(jValue);
 
     return ckpValue ;
@@ -813,13 +838,16 @@
     CK_BYTE_PTR ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Byte");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "byteValue", "()B");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallByteMethod(env, jObject, jValueMethod);
     ckpValue = (CK_BYTE_PTR) malloc(sizeof(CK_BYTE));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jByteToCKByte(jValue);
-
     return ckpValue ;
 }
 
@@ -839,13 +867,16 @@
     CK_ULONG *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Integer");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "intValue", "()I");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallIntMethod(env, jObject, jValueMethod);
     ckpValue = (CK_ULONG *) malloc(sizeof(CK_ULONG));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jLongToCKLong(jValue);
-
     return ckpValue ;
 }
 
@@ -865,11 +896,15 @@
     CK_ULONG *ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Long");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "longValue", "()J");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallLongMethod(env, jObject, jValueMethod);
     ckpValue = (CK_ULONG *) malloc(sizeof(CK_ULONG));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jLongToCKULong(jValue);
 
     return ckpValue ;
@@ -891,11 +926,15 @@
     CK_CHAR_PTR ckpValue;
 
     jObjectClass = (*env)->FindClass(env, "java/lang/Char");
-    assert(jObjectClass != 0);
+    if (jObjectClass == NULL) { return NULL; }
     jValueMethod = (*env)->GetMethodID(env, jObjectClass, "charValue", "()C");
-    assert(jValueMethod != 0);
+    if (jValueMethod == NULL) { return NULL; }
     jValue = (*env)->CallCharMethod(env, jObject, jValueMethod);
     ckpValue = (CK_CHAR_PTR) malloc(sizeof(CK_CHAR));
+    if (ckpValue == NULL) {
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return NULL;
+    }
     *ckpValue = jCharToCKChar(jValue);
 
     return ckpValue ;
@@ -913,124 +952,172 @@
  */
 void jObjectToPrimitiveCKObjectPtrPtr(JNIEnv *env, jobject jObject, CK_VOID_PTR *ckpObjectPtr, CK_ULONG *ckpLength)
 {
-    jclass jBooleanClass     = (*env)->FindClass(env, "java/lang/Boolean");
-    jclass jByteClass        = (*env)->FindClass(env, "java/lang/Byte");
-    jclass jCharacterClass   = (*env)->FindClass(env, "java/lang/Character");
-    jclass jClassClass = (*env)->FindClass(env, "java/lang/Class");
-    /* jclass jShortClass       = (*env)->FindClass(env, "java/lang/Short"); */
-    jclass jIntegerClass     = (*env)->FindClass(env, "java/lang/Integer");
-    jclass jLongClass        = (*env)->FindClass(env, "java/lang/Long");
-    /* jclass jFloatClass       = (*env)->FindClass(env, "java/lang/Float"); */
-    /* jclass jDoubleClass      = (*env)->FindClass(env, "java/lang/Double"); */
-    jclass jDateClass      = (*env)->FindClass(env, CLASS_DATE);
-    jclass jStringClass      = (*env)->FindClass(env, "java/lang/String");
-    jclass jStringBufferClass      = (*env)->FindClass(env, "java/lang/StringBuffer");
-    jclass jBooleanArrayClass = (*env)->FindClass(env, "[Z");
-    jclass jByteArrayClass    = (*env)->FindClass(env, "[B");
-    jclass jCharArrayClass    = (*env)->FindClass(env, "[C");
-    /* jclass jShortArrayClass   = (*env)->FindClass(env, "[S"); */
-    jclass jIntArrayClass     = (*env)->FindClass(env, "[I");
-    jclass jLongArrayClass    = (*env)->FindClass(env, "[J");
-    /* jclass jFloatArrayClass   = (*env)->FindClass(env, "[F"); */
-    /* jclass jDoubleArrayClass  = (*env)->FindClass(env, "[D"); */
-    jclass jObjectClass = (*env)->FindClass(env, "java/lang/Object");
-    /* jclass jObjectArrayClass = (*env)->FindClass(env, "[java/lang/Object"); */
-    /* ATTENTION: jObjectArrayClass is always NULL !! */
-    /* CK_ULONG ckArrayLength; */
-    /* CK_VOID_PTR *ckpElementObject; */
-    /* CK_ULONG ckElementLength; */
-    /* CK_ULONG i; */
+    jclass jLongClass, jBooleanClass, jByteArrayClass, jCharArrayClass;
+    jclass jByteClass, jDateClass, jCharacterClass, jIntegerClass;
+    jclass jBooleanArrayClass, jIntArrayClass, jLongArrayClass;
+    jclass jStringClass;
+    jclass jObjectClass, jClassClass;
     CK_VOID_PTR ckpVoid = *ckpObjectPtr;
     jmethodID jMethod;
     jobject jClassObject;
     jstring jClassNameString;
-    jstring jExceptionMessagePrefix;
-    jobject jExceptionMessageStringBuffer;
-    jstring jExceptionMessage;
+    char *classNameString, *exceptionMsgPrefix, *exceptionMsg;
 
     TRACE0("\nDEBUG: jObjectToPrimitiveCKObjectPtrPtr");
     if (jObject == NULL) {
         *ckpObjectPtr = NULL;
         *ckpLength = 0;
-    } else if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
+        return;
+    }
+
+    jLongClass = (*env)->FindClass(env, "java/lang/Long");
+    if (jLongClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jLongClass)) {
         *ckpObjectPtr = jLongObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
         TRACE1("<converted long value %X>", *((CK_ULONG *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
+        return;
+    }
+
+    jBooleanClass = (*env)->FindClass(env, "java/lang/Boolean");
+    if (jBooleanClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jBooleanClass)) {
         *ckpObjectPtr = jBooleanObjectToCKBBoolPtr(env, jObject);
         *ckpLength = sizeof(CK_BBOOL);
         TRACE0(" <converted boolean value ");
         TRACE0((*((CK_BBOOL *) *ckpObjectPtr) == TRUE) ? "TRUE>" : "FALSE>");
-    } else if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
+        return;
+    }
+
+    jByteArrayClass = (*env)->FindClass(env, "[B");
+    if (jByteArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jByteArrayClass)) {
         jByteArrayToCKByteArray(env, jObject, (CK_BYTE_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
+        return;
+    }
+
+    jCharArrayClass = (*env)->FindClass(env, "[C");
+    if (jCharArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jCharArrayClass)) {
         jCharArrayToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
+        return;
+    }
+
+    jByteClass = (*env)->FindClass(env, "java/lang/Byte");
+    if (jByteClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jByteClass)) {
         *ckpObjectPtr = jByteObjectToCKBytePtr(env, jObject);
         *ckpLength = sizeof(CK_BYTE);
         TRACE1("<converted byte value %X>", *((CK_BYTE *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
+        return;
+    }
+
+    jDateClass = (*env)->FindClass(env, CLASS_DATE);
+    if (jDateClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jDateClass)) {
         *ckpObjectPtr = jDateObjectPtrToCKDatePtr(env, jObject);
         *ckpLength = sizeof(CK_DATE);
-        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year,
-                                                    (*((CK_DATE *) *ckpObjectPtr)).month,
-                                                    (*((CK_DATE *) *ckpObjectPtr)).day);
-    } else if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
+        TRACE3("<converted date value %.4s-%.2s-%.2s>", (*((CK_DATE *) *ckpObjectPtr)).year, (*((CK_DATE *) *ckpObjectPtr)).month, (*((CK_DATE *) *ckpObjectPtr)).day);
+        return;
+    }
+
+    jCharacterClass = (*env)->FindClass(env, "java/lang/Character");
+    if (jCharacterClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jCharacterClass)) {
         *ckpObjectPtr = jCharObjectToCKCharPtr(env, jObject);
         *ckpLength = sizeof(CK_UTF8CHAR);
         TRACE1("<converted char value %c>", *((CK_CHAR *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
+        return;
+    }
+
+    jIntegerClass = (*env)->FindClass(env, "java/lang/Integer");
+    if (jIntegerClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jIntegerClass)) {
         *ckpObjectPtr = jIntegerObjectToCKULongPtr(env, jObject);
         *ckpLength = sizeof(CK_ULONG);
         TRACE1("<converted integer value %X>", *((CK_ULONG *) *ckpObjectPtr));
-    } else if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
+        return;
+    }
+
+    jBooleanArrayClass = (*env)->FindClass(env, "[Z");
+    if (jBooleanArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jBooleanArrayClass)) {
         jBooleanArrayToCKBBoolArray(env, jObject, (CK_BBOOL**)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
+        return;
+    }
+
+    jIntArrayClass = (*env)->FindClass(env, "[I");
+    if (jIntArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jIntArrayClass)) {
         jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
+        return;
+    }
+
+    jLongArrayClass = (*env)->FindClass(env, "[J");
+    if (jLongArrayClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jLongArrayClass)) {
         jLongArrayToCKULongArray(env, jObject, (CK_ULONG_PTR*)ckpObjectPtr, ckpLength);
-    } else if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
+        return;
+    }
+
+    jStringClass = (*env)->FindClass(env, "java/lang/String");
+    if (jStringClass == NULL) { return; }
+    if ((*env)->IsInstanceOf(env, jObject, jStringClass)) {
         jStringToCKUTF8CharArray(env, jObject, (CK_UTF8CHAR_PTR*)ckpObjectPtr, ckpLength);
+        return;
+    }
 
-        /* a Java object array is not used by CK_ATTRIBUTE by now... */
-/*  } else if ((*env)->IsInstanceOf(env, jObject, jObjectArrayClass)) {
-        ckArrayLength = (*env)->GetArrayLength(env, (jarray) jObject);
-        ckpObjectPtr = (CK_VOID_PTR_PTR) malloc(sizeof(CK_VOID_PTR) * ckArrayLength);
-        *ckpLength = 0;
-        for (i = 0; i < ckArrayLength; i++) {
-            jObjectToPrimitiveCKObjectPtrPtr(env, (*env)->GetObjectArrayElement(env, (jarray) jObject, i),
-                     ckpElementObject, &ckElementLength);
-            (*ckpObjectPtr)[i] = *ckpElementObject;
-            *ckpLength += ckElementLength;
-        }
-*/
-    } else {
-        /* type of jObject unknown, throw PKCS11RuntimeException */
-        jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
-        assert(jMethod != 0);
-        jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
-        assert(jClassObject != 0);
-        jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
-        assert(jMethod != 0);
-        jClassNameString = (jstring)
-                (*env)->CallObjectMethod(env, jClassObject, jMethod);
-        assert(jClassNameString != 0);
-        jExceptionMessagePrefix = (*env)->NewStringUTF(env, "Java object of this class cannot be converted to native PKCS#11 type: ");
-        jMethod = (*env)->GetMethodID(env, jStringBufferClass, "<init>", "(Ljava/lang/String;)V");
-        assert(jMethod != 0);
-        jExceptionMessageStringBuffer = (*env)->NewObject(env, jStringBufferClass, jMethod, jExceptionMessagePrefix);
-        assert(jClassNameString != 0);
-        jMethod = (*env)->GetMethodID(env, jStringBufferClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
-        assert(jMethod != 0);
-        jExceptionMessage = (jstring)
-                 (*env)->CallObjectMethod(env, jExceptionMessageStringBuffer, jMethod, jClassNameString);
-        assert(jExceptionMessage != 0);
-
-        throwPKCS11RuntimeException(env, jExceptionMessage);
-
-        *ckpObjectPtr = NULL;
-        *ckpLength = 0;
+    /* type of jObject unknown, throw PKCS11RuntimeException */
+    jObjectClass = (*env)->FindClass(env, "java/lang/Object");
+    if (jObjectClass == NULL) { return; }
+    jMethod = (*env)->GetMethodID(env, jObjectClass, "getClass", "()Ljava/lang/Class;");
+    if (jMethod == NULL) { return; }
+    jClassObject = (*env)->CallObjectMethod(env, jObject, jMethod);
+    assert(jClassObject != 0);
+    jClassClass = (*env)->FindClass(env, "java/lang/Class");
+    if (jClassClass == NULL) { return; }
+    jMethod = (*env)->GetMethodID(env, jClassClass, "getName", "()Ljava/lang/String;");
+    if (jMethod == NULL) { return; }
+    jClassNameString = (jstring)
+        (*env)->CallObjectMethod(env, jClassObject, jMethod);
+    assert(jClassNameString != 0);
+    classNameString = (char*)
+        (*env)->GetStringUTFChars(env, jClassNameString, NULL);
+    if (classNameString == NULL) { return; }
+    exceptionMsgPrefix = "Java object of this class cannot be converted to native PKCS#11 type: ";
+    exceptionMsg = (char *)
+        malloc((strlen(exceptionMsgPrefix) + strlen(classNameString) + 1));
+    if (exceptionMsg == NULL) {
+        (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
+        JNU_ThrowOutOfMemoryError(env, 0);
+        return;
     }
+    strcpy(exceptionMsg, exceptionMsgPrefix);
+    strcat(exceptionMsg, classNameString);
+    (*env)->ReleaseStringUTFChars(env, jClassNameString, classNameString);
+    throwPKCS11RuntimeException(env, exceptionMsg);
+    free(exceptionMsg);
+    *ckpObjectPtr = NULL;
+    *ckpLength = 0;
 
     TRACE0("FINISHED\n");
 }
+
+#ifdef P11_MEMORYDEBUG
+
+#undef malloc
+#undef free
+
+void *p11malloc(size_t c, char *file, int line) {
+    void *p = malloc(c);
+    printf("malloc\t%08x\t%d\t%s:%d\n", p, c, file, line); fflush(stdout);
+    return p;
+}
+
+void p11free(void *p, char *file, int line) {
+    printf("free\t%08x\t\t%s:%d\n", p, file, line); fflush(stdout);
+    free(p);
+}
+
+#endif
+
--- a/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h	Mon Mar 02 15:10:55 2009 -0800
+++ b/jdk/src/share/native/sun/security/pkcs11/wrapper/pkcs11wrapper.h	Tue Mar 03 19:50:59 2009 -0800
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright 2003-2006 Sun Microsystems, Inc.  All Rights Reserved.
+ * Portions Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -154,6 +154,7 @@
 
 #include "pkcs11.h"
 #include <jni.h>
+#include <jni_util.h>
 
 #define MAX_STACK_BUFFER_LEN (4 * 1024)
 #define MAX_HEAP_BUFFER_LEN (64 * 1024)
@@ -277,12 +278,14 @@
  */
 
 jlong ckAssertReturnValueOK(JNIEnv *env, CK_RV returnValue);
-void throwPKCS11RuntimeException(JNIEnv *env, jstring jmessage);
-void throwFileNotFoundException(JNIEnv *env, jstring jmessage);
 void throwIOException(JNIEnv *env, const char *message);
-void throwIOExceptionUnicodeMessage(JNIEnv *env, const short *message);
+void throwPKCS11RuntimeException(JNIEnv *env, const char *message);
 void throwDisconnectedRuntimeException(JNIEnv *env);
 
+/* function to free CK_ATTRIBUTE array
+ */
+void freeCKAttributeArray(CK_ATTRIBUTE_PTR attrPtr, int len);
+
 /* funktions to convert Java arrays to a CK-type array and the array length */
 
 void jBooleanArrayToCKBBoolArray(JNIEnv *env, const jbooleanArray jArray, CK_BBOOL **ckpArray, CK_ULONG_PTR ckLength);
@@ -438,3 +441,15 @@
 extern jobject jInitArgsObject;
 extern CK_C_INITIALIZE_ARGS_PTR ckpGlobalInitArgs;
 #endif /* NO_CALLBACKS */
+
+#ifdef P11_MEMORYDEBUG
+#include <stdlib.h>
+
+/* Simple malloc/free dumper */
+void *p11malloc(size_t c, char *file, int line);
+void p11free(void *p, char *file, int line);
+
+#define malloc(c)       (p11malloc((c), __FILE__, __LINE__))
+#define free(c)         (p11free((c), __FILE__, __LINE__))
+
+#endif