changeset 9907:2b546fae4cd9

8031003: [Parfait] warnings from jdk/src/share/native/sun/security/jgss/wrapper: JNI exception pending Summary: Fixed various JNI exception pending warnings Reviewed-by: weijun
author valeriep
date Tue, 19 Aug 2014 22:12:15 +0000
parents 5c9e6e6c2673
children 09c23be3b54d
files src/share/classes/sun/security/jgss/wrapper/GSSLibStub.java src/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java src/share/native/sun/security/jgss/wrapper/GSSLibStub.c src/share/native/sun/security/jgss/wrapper/NativeUtil.c src/share/native/sun/security/jgss/wrapper/NativeUtil.h
diffstat 5 files changed, 601 insertions(+), 379 deletions(-) [+]
line wrap: on
line diff
--- a/src/share/classes/sun/security/jgss/wrapper/GSSLibStub.java	Tue Aug 19 17:35:09 2014 +0100
+++ b/src/share/classes/sun/security/jgss/wrapper/GSSLibStub.java	Tue Aug 19 22:12:15 2014 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,10 +48,11 @@
     /**
      * Initialization routine to dynamically load function pointers.
      *
-     * @param library name to dlopen
+     * @param lib library name to dlopen
+     * @param debug set to true for reporting native debugging info
      * @return true if succeeded, false otherwise.
      */
-    static native boolean init(String lib);
+    static native boolean init(String lib, boolean debug);
     private static native long getMechPtr(byte[] oidDerEncoding);
 
     // Miscellaneous routines
--- a/src/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java	Tue Aug 19 17:35:09 2014 +0100
+++ b/src/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java	Tue Aug 19 22:12:15 2014 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -100,7 +100,7 @@
                             gssLibs = new String[]{ defaultLib };
                         }
                         for (String libName: gssLibs) {
-                            if (GSSLibStub.init(libName)) {
+                            if (GSSLibStub.init(libName, DEBUG)) {
                                 debug("Loaded GSS library: " + libName);
                                 Oid[] mechs = GSSLibStub.indicateMechs();
                                 HashMap<String, String> map =
--- a/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Tue Aug 19 17:35:09 2014 +0100
+++ b/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Tue Aug 19 22:12:15 2014 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,19 +29,6 @@
 #include "jlong.h"
 #include <jni.h>
 
-/* Throws a Java Exception by name */
-
-void throwByName(JNIEnv *env, const char *name, const char *msg) {
-    jclass cls = (*env)->FindClass(env, name);
-
-    if (cls != 0) /* Otherwise an exception has already been thrown */
-        (*env)->ThrowNew(env, cls, msg);
-}
-
-void throwOutOfMemoryError(JNIEnv *env, const char *message) {
-    throwByName(env, "java/lang/OutOfMemoryError", message);
-}
-
 /* Constants for indicating what type of info is needed for inquiries */
 const int TYPE_CRED_NAME = 10;
 const int TYPE_CRED_TIME = 11;
@@ -50,23 +37,32 @@
 /*
  * Class:     sun_security_jgss_wrapper_GSSLibStub
  * Method:    init
- * Signature: (Ljava/lang/String;)Z
+ * Signature: (Ljava/lang/String;Z)Z
  */
 JNIEXPORT jboolean JNICALL
 Java_sun_security_jgss_wrapper_GSSLibStub_init(JNIEnv *env,
                                                jclass jcls,
-                                               jstring jlibName) {
+                                               jstring jlibName,
+                                               jboolean jDebug) {
     const char *libName;
     char *error = NULL;
 
+    if (!jDebug) {
+      JGSS_DEBUG = 0;
+    } else {
+      JGSS_DEBUG = 1;
+    }
+
     if (jlibName == NULL) {
-        debug(env, "[GSSLibStub_init] GSS lib name is NULL");
+        TRACE0("[GSSLibStub_init] GSS lib name is NULL");
         return JNI_FALSE;
     }
 
     libName = (*env)->GetStringUTFChars(env, jlibName, NULL);
-    sprintf(debugBuf, "[GSSLibStub_init] libName=%s", libName);
-    debug(env, debugBuf);
+    if (libName == NULL) {
+        return JNI_FALSE;
+    }
+    TRACE1("[GSSLibStub_init] libName=%s", libName);
 
     /* initialize global function table */
     error = loadNative(libName);
@@ -75,7 +71,7 @@
     if (error == NULL) {
         return JNI_TRUE;
     } else {
-        debug(env, error);
+        TRACE0(error);
         return JNI_FALSE;
     }
 }
@@ -93,126 +89,137 @@
   unsigned int i, len;
   jbyte* bytes;
   jthrowable gssEx;
-  jboolean found;
+  int found;
 
   if (jbytes != NULL) {
-    found = JNI_FALSE;
+    found = 0;
     len = (unsigned int)((*env)->GetArrayLength(env, jbytes) - 2);
     bytes = (*env)->GetByteArrayElements(env, jbytes, NULL);
-    if (bytes != NULL) {
-      for (i = 0; i < ftab->mechs->count; i++) {
-        cOid = &(ftab->mechs->elements[i]);
-        if (len == cOid->length &&
-            (memcmp(cOid->elements, (bytes + 2), len) == 0)) {
-          // Found a match
-          found = JNI_TRUE;
-          break;
-        }
+    if (bytes == NULL) {
+      return ptr_to_jlong(NULL);
+    }
+    for (i = 0; i < ftab->mechs->count; i++) {
+      cOid = &(ftab->mechs->elements[i]);
+      if (len == cOid->length &&
+          (memcmp(cOid->elements, (bytes + 2), len) == 0)) {
+        // Found a match
+        found = 1;
+        break;
       }
-      (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
     }
-    if (found != JNI_TRUE) {
+    (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
+
+    if (found != 1) {
       checkStatus(env, NULL, GSS_S_BAD_MECH, 0, "[GSSLibStub_getMechPtr]");
       return ptr_to_jlong(NULL);
-    } else return ptr_to_jlong(cOid);
-  } else return ptr_to_jlong(GSS_C_NO_OID);
+    } else {
+      return ptr_to_jlong(cOid);
+    }
+  } else {
+    return ptr_to_jlong(GSS_C_NO_OID);
+  }
 }
 
+/*
+ * Utility routine which releases the specified gss_channel_bindings_t
+ * structure.
+ */
+void deleteGSSCB(gss_channel_bindings_t cb) {
+  jobject jinetAddr;
+  jbyteArray value;
+
+  if (cb == GSS_C_NO_CHANNEL_BINDINGS) return;
+
+  /* release initiator address */
+  if (cb->initiator_addrtype != GSS_C_AF_NULLADDR) {
+    resetGSSBuffer(&(cb->initiator_address));
+  }
+  /* release acceptor address */
+  if (cb->acceptor_addrtype != GSS_C_AF_NULLADDR) {
+    resetGSSBuffer(&(cb->acceptor_address));
+  }
+  /* release application data */
+  if (cb->application_data.length != 0) {
+    resetGSSBuffer(&(cb->application_data));
+  }
+  free(cb);
+}
 
 /*
  * Utility routine which creates a gss_channel_bindings_t structure
  * using the specified org.ietf.jgss.ChannelBinding object.
+ * NOTE: must call deleteGSSCB() to free up the resources.
  */
-gss_channel_bindings_t getGSSCB(JNIEnv *env, jobject jcb) {
+gss_channel_bindings_t newGSSCB(JNIEnv *env, jobject jcb) {
   gss_channel_bindings_t cb;
   jobject jinetAddr;
   jbyteArray value;
+  int i;
 
   if (jcb == NULL) {
     return GSS_C_NO_CHANNEL_BINDINGS;
   }
 
   cb = malloc(sizeof(struct gss_channel_bindings_struct));
-
   if (cb == NULL) {
     throwOutOfMemoryError(env,NULL);
     return NULL;
   }
 
+  // initialize addrtype in CB first
+  cb->initiator_addrtype = GSS_C_AF_NULLADDR;
+  cb->acceptor_addrtype = GSS_C_AF_NULLADDR;
+
   /* set up initiator address */
-  jinetAddr =
-    (*env)->CallObjectMethod(env, jcb,
-                             MID_ChannelBinding_getInitiatorAddr);
+  jinetAddr = (*env)->CallObjectMethod(env, jcb,
+      MID_ChannelBinding_getInitiatorAddr);
+  if ((*env)->ExceptionCheck(env)) {
+    goto cleanup;
+  }
   if (jinetAddr != NULL) {
-    cb->initiator_addrtype = GSS_C_AF_INET;
     value = (*env)->CallObjectMethod(env, jinetAddr,
                                      MID_InetAddress_getAddr);
+    if ((*env)->ExceptionCheck(env)) {
+      goto cleanup;
+    }
+    cb->initiator_addrtype = GSS_C_AF_INET;
     initGSSBuffer(env, value, &(cb->initiator_address));
-  } else {
-    cb->initiator_addrtype = GSS_C_AF_NULLADDR;
-    cb->initiator_address.length = 0;
-    cb->initiator_address.value = NULL;
+    if ((*env)->ExceptionCheck(env)) {
+      goto cleanup;
+    }
   }
   /* set up acceptor address */
-  jinetAddr =
-    (*env)->CallObjectMethod(env, jcb,
-                             MID_ChannelBinding_getAcceptorAddr);
+  jinetAddr = (*env)->CallObjectMethod(env, jcb,
+      MID_ChannelBinding_getAcceptorAddr);
+  if ((*env)->ExceptionCheck(env)) {
+    goto cleanup;
+  }
   if (jinetAddr != NULL) {
-    cb->acceptor_addrtype = GSS_C_AF_INET;
     value = (*env)->CallObjectMethod(env, jinetAddr,
                                      MID_InetAddress_getAddr);
+    if ((*env)->ExceptionCheck(env)) {
+      goto cleanup;
+    }
+    cb->acceptor_addrtype = GSS_C_AF_INET;
     initGSSBuffer(env, value, &(cb->acceptor_address));
-  } else {
-    cb->acceptor_addrtype = GSS_C_AF_NULLADDR;
-    cb->acceptor_address.length = 0;
-    cb->acceptor_address.value = NULL;
+    if ((*env)->ExceptionCheck(env)) {
+      goto cleanup;
+    }
   }
   /* set up application data */
   value = (*env)->CallObjectMethod(env, jcb,
                                    MID_ChannelBinding_getAppData);
-  if (value != NULL) {
-    initGSSBuffer(env, value, &(cb->application_data));
-  } else {
-    cb->application_data.length = 0;
-    cb->application_data.value = NULL;
+  if ((*env)->ExceptionCheck(env)) {
+    goto cleanup;
+  }
+  initGSSBuffer(env, value, &(cb->application_data));
+  if ((*env)->ExceptionCheck(env)) {
+    goto cleanup;
   }
   return cb;
-}
-
-/*
- * Utility routine which releases the specified gss_channel_bindings_t
- * structure.
- */
-void releaseGSSCB(JNIEnv *env, jobject jcb, gss_channel_bindings_t cb) {
-  jobject jinetAddr;
-  jbyteArray value;
-
-  if (cb == GSS_C_NO_CHANNEL_BINDINGS) return;
-  /* release initiator address */
-  if (cb->initiator_addrtype != GSS_C_AF_NULLADDR) {
-    jinetAddr =
-      (*env)->CallObjectMethod(env, jcb,
-                               MID_ChannelBinding_getInitiatorAddr);
-    value = (*env)->CallObjectMethod(env, jinetAddr,
-                                     MID_InetAddress_getAddr);
-    resetGSSBuffer(env, value, &(cb->initiator_address));
-  }
-  /* release acceptor address */
-  if (cb->acceptor_addrtype != GSS_C_AF_NULLADDR) {
-    jinetAddr =
-      (*env)->CallObjectMethod(env, jcb,
-                               MID_ChannelBinding_getAcceptorAddr);
-    value = (*env)->CallObjectMethod(env, jinetAddr,
-                                     MID_InetAddress_getAddr);
-    resetGSSBuffer(env, value, &(cb->acceptor_address));
-  }
-  /* release application data */
-  if (cb->application_data.length != 0) {
-    value = (*env)->CallObjectMethod(env, jcb,
-                                     MID_ChannelBinding_getAppData);
-    resetGSSBuffer(env, value, &(cb->application_data));
-  }
-  free(cb);
+cleanup:
+  deleteGSSCB(cb);
+  return NULL;
 }
 
 /*
@@ -230,6 +237,9 @@
     isUnseq = ((suppInfo & GSS_S_UNSEQ_TOKEN) != 0);
     hasGap = ((suppInfo & GSS_S_GAP_TOKEN) != 0);
     minorMsg = getMinorMessage(env, jstub, minor);
+    if ((*env)->ExceptionCheck(env)) {
+      return;
+    }
     (*env)->CallVoidMethod(env, jprop, MID_MessageProp_setSupplementaryStates,
                            isDuplicate, isOld, isUnseq, hasGap, minor,
                            minorMsg);
@@ -265,21 +275,26 @@
   jobjectArray result;
 
   if (ftab->inquireNamesForMech != NULL) {
+    mech = (gss_OID)jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
+    nameTypes = GSS_C_NO_OID_SET;
 
-  mech = (gss_OID)jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
-  nameTypes = GSS_C_NO_OID_SET;
+    /* gss_inquire_names_for_mech(...) => N/A */
+    major = (*ftab->inquireNamesForMech)(&minor, mech, &nameTypes);
 
-  /* gss_inquire_names_for_mech(...) => N/A */
-  major = (*ftab->inquireNamesForMech)(&minor, mech, &nameTypes);
+    /* release intermediate buffers before checking status */
+    result = getJavaOIDArray(env, nameTypes);
+    deleteGSSOIDSet(nameTypes);
+    if ((*env)->ExceptionCheck(env)) {
+      return NULL;
+    }
 
-  result = getJavaOIDArray(env, nameTypes);
-
-  /* release intermediate buffers */
-  deleteGSSOIDSet(nameTypes);
-
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_inquireNamesForMech]");
-  return result;
-  } else return NULL;
+    checkStatus(env, jobj, major, minor, "[GSSLibStub_inquireNamesForMech]");
+    if ((*env)->ExceptionCheck(env)) {
+      return NULL;
+    }
+    return result;
+  }
+  return NULL;
 }
 
 /*
@@ -297,8 +312,7 @@
 
   nameHdl = (gss_name_t) jlong_to_ptr(pName);
 
-  sprintf(debugBuf, "[GSSLibStub_releaseName] %ld", (long) pName);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_releaseName] %ld", (long) pName);
 
   if (nameHdl != GSS_C_NO_NAME) {
     /* gss_release_name(...) => GSS_S_BAD_NAME */
@@ -324,13 +338,16 @@
   gss_name_t nameHdl;
   nameHdl = GSS_C_NO_NAME;
 
-  debug(env, "[GSSLibStub_importName]");
+  TRACE0("[GSSLibStub_importName]");
 
   initGSSBuffer(env, jnameVal, &nameVal);
+  if ((*env)->ExceptionCheck(env)) {
+      return jlong_zero;
+  }
+
   nameType = newGSSOID(env, jnameType);
   if ((*env)->ExceptionCheck(env)) {
-    deleteGSSOID(nameType);
-    resetGSSBuffer(env, jnameVal, &nameVal);
+    resetGSSBuffer(&nameVal);
     return jlong_zero;
   }
 
@@ -338,14 +355,16 @@
      GSS_S_BAD_MECH */
   major = (*ftab->importName)(&minor, &nameVal, nameType, &nameHdl);
 
-  sprintf(debugBuf, "[GSSLibStub_importName] %ld", (long) nameHdl);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_importName] %ld", (long) nameHdl);
 
   /* release intermediate buffers */
   deleteGSSOID(nameType);
-  resetGSSBuffer(env, jnameVal, &nameVal);
+  resetGSSBuffer(&nameVal);
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_importName]");
+  if ((*env)->ExceptionCheck(env)) {
+    return jlong_zero;
+  }
   return ptr_to_jlong(nameHdl);
 }
 
@@ -369,9 +388,7 @@
   nameHdl1 = (gss_name_t) jlong_to_ptr(pName1);
   nameHdl2 = (gss_name_t) jlong_to_ptr(pName2);
 
-  sprintf(debugBuf, "[GSSLibStub_compareName] %ld %ld", (long) pName1,
-    (long) pName2);
-  debug(env, debugBuf);
+  TRACE2("[GSSLibStub_compareName] %ld %ld", (long)pName1, (long)pName2);
 
   if ((nameHdl1 != GSS_C_NO_NAME) && (nameHdl2 != GSS_C_NO_NAME)) {
 
@@ -398,8 +415,8 @@
   gss_OID mech;
 
   nameHdl = (gss_name_t) jlong_to_ptr(pName);
-  sprintf(debugBuf, "[GSSLibStub_canonicalizeName] %ld", (long) pName);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_canonicalizeName] %ld", (long) pName);
 
   if (nameHdl != GSS_C_NO_NAME) {
     mech = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
@@ -409,16 +426,15 @@
        GSS_S_BAD_NAME, GSS_S_BAD_MECH */
     major = (*ftab->canonicalizeName)(&minor, nameHdl, mech, &mnNameHdl);
 
-    sprintf(debugBuf, "[GSSLibStub_canonicalizeName] MN=%ld",
-        (long)mnNameHdl);
-    debug(env, debugBuf);
-
-    /* release intermediate buffers */
+    TRACE1("[GSSLibStub_canonicalizeName] MN=%ld", (long)mnNameHdl);
 
     checkStatus(env, jobj, major, minor, "[GSSLibStub_canonicalizeName]");
-  } else mnNameHdl = GSS_C_NO_NAME;
-
-  return ptr_to_jlong(mnNameHdl);
+    if ((*env)->ExceptionCheck(env)) {
+      return (jlong) GSS_C_NO_NAME;
+    }
+    return ptr_to_jlong(mnNameHdl);
+  }
+  return (jlong) GSS_C_NO_NAME;
 }
 
 /*
@@ -436,8 +452,8 @@
   jbyteArray jresult;
 
   nameHdl = (gss_name_t) jlong_to_ptr(pName);
-  sprintf(debugBuf, "[GSSLibStub_exportName] %ld", (long) pName);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_exportName] %ld", (long) pName);
 
   /* gss_export_name(...) => GSS_S_NAME_NOT_MN, GSS_S_BAD_NAMETYPE,
      GSS_S_BAD_NAME */
@@ -445,28 +461,38 @@
 
   /* canonicalize the internal name to MN and retry */
   if (major == GSS_S_NAME_NOT_MN) {
-    debug(env, "[GSSLibStub_exportName] canonicalize and re-try");
+    /* release intermediate buffers before retrying */
+    (*ftab->releaseBuffer)(&minor, &outBuf);
+
+    TRACE0("[GSSLibStub_exportName] canonicalize and re-try");
 
     mNameHdl = (gss_name_t)jlong_to_ptr(
         Java_sun_security_jgss_wrapper_GSSLibStub_canonicalizeName
                                         (env, jobj, pName));
-    /* return immediately if an exception has occurred */
     if ((*env)->ExceptionCheck(env)) {
-      return NULL;
+        return NULL;
     }
+
     major = (*ftab->exportName)(&minor, mNameHdl, &outBuf);
     Java_sun_security_jgss_wrapper_GSSLibStub_releaseName
                                         (env, jobj, ptr_to_jlong(mNameHdl));
-    /* return immediately if an exception has occurred */
     if ((*env)->ExceptionCheck(env)) {
+      /* release intermediate buffers */
+      (*ftab->releaseBuffer)(&minor, &outBuf);
       return NULL;
     }
   }
 
-  /* release intermediate buffers */
+  /* release intermediate buffers before checking status */
   jresult = getJavaBuffer(env, &outBuf);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_exportName]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   return jresult;
 }
 
@@ -488,8 +514,8 @@
   jobjectArray jresult;
 
   nameHdl = (gss_name_t) jlong_to_ptr(pName);
-  sprintf(debugBuf, "[GSSLibStub_displayName] %ld", (long) pName);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_displayName] %ld", (long) pName);
 
   if (nameHdl == GSS_C_NO_NAME) {
     checkStatus(env, jobj, GSS_S_BAD_NAME, 0, "[GSSLibStub_displayName]");
@@ -499,21 +525,37 @@
   /* gss_display_name(...) => GSS_S_BAD_NAME */
   major = (*ftab->displayName)(&minor, nameHdl, &outNameBuf, &outNameType);
 
-  /* release intermediate buffers */
+  /* release intermediate buffers before checking status */
   jname = getJavaString(env, &outNameBuf);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
+  checkStatus(env, jobj, major, minor, "[GSSLibStub_displayName]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
   jtype = getJavaOID(env, outNameType);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   jresult = (*env)->NewObjectArray(env, 2, CLS_Object, NULL);
-
   /* return immediately if an exception has occurred */
   if ((*env)->ExceptionCheck(env)) {
     return NULL;
   }
 
   (*env)->SetObjectArrayElement(env, jresult, 0, jname);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   (*env)->SetObjectArrayElement(env, jresult, 1, jtype);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_displayName]");
   return jresult;
 }
 
@@ -537,20 +579,14 @@
   gss_cred_id_t credHdl;
   credHdl = GSS_C_NO_CREDENTIAL;
 
-  debug(env, "[GSSLibStub_acquireCred]");
-
+  TRACE0("[GSSLibStub_acquireCred]");
 
   mech = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
-  mechs = newGSSOIDSet(env, mech);
-  if ((*env)->ExceptionCheck(env)) {
-    return jlong_zero;
-  }
+  mechs = newGSSOIDSet(mech);
   credUsage = (gss_cred_usage_t) usage;
   nameHdl = (gss_name_t) jlong_to_ptr(pName);
 
-  sprintf(debugBuf, "[GSSLibStub_acquireCred] pName=%ld, usage=%d",
-    (long) pName, usage);
-  debug(env, debugBuf);
+  TRACE2("[GSSLibStub_acquireCred] pName=%ld, usage=%d", (long)pName, usage);
 
   /* gss_acquire_cred(...) => GSS_S_BAD_MECH, GSS_S_BAD_NAMETYPE,
      GSS_S_BAD_NAME, GSS_S_CREDENTIALS_EXPIRED, GSS_S_NO_CRED */
@@ -560,10 +596,12 @@
   /* release intermediate buffers */
   deleteGSSOIDSet(mechs);
 
-  sprintf(debugBuf, "[GSSLibStub_acquireCred] pCred=%ld", (long) credHdl);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_acquireCred] pCred=%ld", (long) credHdl);
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_acquireCred]");
+  if ((*env)->ExceptionCheck(env)) {
+    return jlong_zero;
+  }
   return ptr_to_jlong(credHdl);
 }
 
@@ -582,15 +620,16 @@
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
 
-  sprintf(debugBuf, "[GSSLibStub_releaseCred] %ld", (long int)pCred);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_releaseCred] %ld", (long int)pCred);
 
   if (credHdl != GSS_C_NO_CREDENTIAL) {
-
     /* gss_release_cred(...) => GSS_S_NO_CRED(!) */
     major = (*ftab->releaseCred)(&minor, &credHdl);
 
     checkStatus(env, jobj, major, minor, "[GSSLibStub_releaseCred]");
+    if ((*env)->ExceptionCheck(env)) {
+      return jlong_zero;
+    }
   }
   return ptr_to_jlong(credHdl);
 }
@@ -606,8 +645,7 @@
 
   credHdl = pCred;
 
-  sprintf(debugBuf, "[gss_inquire_cred] %ld", (long) pCred);
-  debug(env, debugBuf);
+  TRACE1("[gss_inquire_cred] %ld", (long) pCred);
 
   /* gss_inquire_cred(...) => GSS_S_DEFECTIVE_CREDENTIAL(!),
      GSS_S_CREDENTIALS_EXPIRED(!), GSS_S_NO_CRED(!) */
@@ -619,8 +657,6 @@
     major = (*ftab->inquireCred)(&minor, credHdl, NULL, NULL, result, NULL);
   }
 
-  /* release intermediate buffers */
-
   routineErr = GSS_ROUTINE_ERROR(major);
   if (routineErr == GSS_S_CREDENTIALS_EXPIRED) {
     /* ignore GSS_S_CREDENTIALS_EXPIRED for query  */
@@ -649,20 +685,16 @@
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
 
-  sprintf(debugBuf, "[GSSLibStub_getCredName] %ld", (long int)pCred);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_getCredName] %ld", (long int)pCred);
 
   nameHdl = GSS_C_NO_NAME;
   inquireCred(env, jobj, credHdl, TYPE_CRED_NAME, &nameHdl);
-
   /* return immediately if an exception has occurred */
   if ((*env)->ExceptionCheck(env)) {
     return jlong_zero;
   }
 
-  sprintf(debugBuf, "[GSSLibStub_getCredName] pName=%ld", (long) nameHdl);
-  debug(env, debugBuf);
-
+  TRACE1("[GSSLibStub_getCredName] pName=%ld", (long) nameHdl);
   return ptr_to_jlong(nameHdl);
 }
 
@@ -681,12 +713,10 @@
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
 
-  sprintf(debugBuf, "[GSSLibStub_getCredTime] %ld", (long int)pCred);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_getCredTime] %ld", (long int)pCred);
 
   lifetime = 0;
   inquireCred(env, jobj, credHdl, TYPE_CRED_TIME, &lifetime);
-
   /* return immediately if an exception has occurred */
   if ((*env)->ExceptionCheck(env)) {
     return 0;
@@ -709,11 +739,9 @@
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
 
-  sprintf(debugBuf, "[GSSLibStub_getCredUsage] %ld", (long int)pCred);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_getCredUsage] %ld", (long int)pCred);
 
   inquireCred(env, jobj, credHdl, TYPE_CRED_USAGE, &usage);
-
   /* return immediately if an exception has occurred */
   if ((*env)->ExceptionCheck(env)) {
     return -1;
@@ -735,21 +763,22 @@
   gss_ctx_id_t contextHdl;
   gss_OID mech, mech2;
 
-  debug(env, "[GSSLibStub_importContext]");
+  TRACE0("[GSSLibStub_importContext]");
 
   contextHdl = GSS_C_NO_CONTEXT;
   initGSSBuffer(env, jctxtToken, &ctxtToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
   /* gss_import_sec_context(...) => GSS_S_NO_CONTEXT, GSS_S_DEFECTIVE_TOKEN,
      GSS_S_UNAVAILABLE, GSS_S_UNAUTHORIZED */
   major = (*ftab->importSecContext)(&minor, &ctxtToken, &contextHdl);
 
-  sprintf(debugBuf, "[GSSLibStub_importContext] pContext=%ld",
-                                        (long) contextHdl);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_importContext] pContext=%ld", (long) contextHdl);
 
   /* release intermediate buffers */
-  resetGSSBuffer(env, jctxtToken, &ctxtToken);
+  resetGSSBuffer(&ctxtToken);
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_importContext]");
   /* return immediately if an exception has occurred */
@@ -768,9 +797,10 @@
     return NULL;
   }
 
-  mech2 = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
+  mech2 = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj,
+      FID_GSSLibStub_pMech));
 
-  if (sameMech(env, mech, mech2) == JNI_TRUE) {
+  if (sameMech(mech, mech2) == JNI_TRUE) {
     /* mech match - return the context object */
     return (*env)->NewObject(env, CLS_NativeGSSContext,
                                  MID_NativeGSSContext_ctor,
@@ -779,10 +809,11 @@
     /* mech mismatch - clean up then return null */
     major = (*ftab->deleteSecContext)(&minor, &contextHdl, GSS_C_NO_BUFFER);
     checkStatus(env, jobj, major, minor,
-      "[GSSLibStub_importContext] cleanup");
+        "[GSSLibStub_importContext] cleanup");
     return NULL;
   }
 }
+
 /*
  * Class:     sun_security_jgss_wrapper_GSSLibStub
  * Method:    initContext
@@ -812,7 +843,8 @@
   gss_OID aMech;
   jobject jMech;
 */
-  debug(env, "[GSSLibStub_initContext]");
+
+  TRACE0("[GSSLibStub_initContext]");
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(
@@ -823,18 +855,19 @@
                                           FID_NativeGSSContext_flags);
   time = getGSSTime((*env)->GetIntField(env, jcontextSpi,
                                         FID_NativeGSSContext_lifetime));
-  cb = getGSSCB(env, jcb);
+  cb = newGSSCB(env, jcb);
   if ((*env)->ExceptionCheck(env)) {
-    free(cb);
     return NULL;
   }
 
   initGSSBuffer(env, jinToken, &inToken);
+  if ((*env)->ExceptionCheck(env)) {
+    deleteGSSCB(cb);
+    return NULL;
+  }
 
-  sprintf(debugBuf,
-          "[GSSLibStub_initContext] before: pCred=%ld, pContext=%ld",
+  TRACE2( "[GSSLibStub_initContext] before: pCred=%ld, pContext=%ld",
           (long)credHdl, (long)contextHdl);
-  debug(env, debugBuf);
 
   /* gss_init_sec_context(...) => GSS_S_CONTINUE_NEEDED(!),
      GSS_S_DEFECTIVE_TOKEN, GSS_S_NO_CRED, GSS_S_DEFECTIVE_CREDENTIAL(!),
@@ -842,29 +875,24 @@
      GSS_S_OLD_TOKEN, GSS_S_DUPLICATE_TOKEN, GSS_S_NO_CONTEXT(!),
      GSS_S_BAD_NAMETYPE, GSS_S_BAD_NAME(!), GSS_S_BAD_MECH */
   major = (*ftab->initSecContext)(&minor, credHdl,
-                               &contextHdl, targetName, mech,
-                               flags, time, cb, &inToken, NULL /*aMech*/,
-                               &outToken, &aFlags, &aTime);
+                                 &contextHdl, targetName, mech,
+                                 flags, time, cb, &inToken, NULL /*aMech*/,
+                                 &outToken, &aFlags, &aTime);
 
-  sprintf(debugBuf, "[GSSLibStub_initContext] after: pContext=%ld",
-          (long)contextHdl);
-  debug(env, debugBuf);
-  sprintf(debugBuf, "[GSSLibStub_initContext] outToken len=%ld",
-          (long)outToken.length);
-  debug(env, debugBuf);
+  TRACE2("[GSSLibStub_initContext] after: pContext=%ld, outToken len=%ld",
+            (long)contextHdl, (long)outToken.length);
 
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
     (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
                         ptr_to_jlong(contextHdl));
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
-    sprintf(debugBuf, "[GSSLibStub_initContext] set flags=0x%x", aFlags);
-    debug(env, debugBuf);
+    TRACE1("[GSSLibStub_initContext] set flags=0x%x", aFlags);
 
     if (major == GSS_S_COMPLETE) {
       (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_lifetime,
                           getJavaTime(aTime));
-      debug(env, "[GSSLibStub_initContext] context established");
+      TRACE0("[GSSLibStub_initContext] context established");
 
       (*env)->SetBooleanField(env, jcontextSpi,
                               FID_NativeGSSContext_isEstablished,
@@ -876,16 +904,23 @@
                              FID_NativeGSSContext_actualMech, jMech);
 */
     } else if (major & GSS_S_CONTINUE_NEEDED) {
-      debug(env, "[GSSLibStub_initContext] context not established");
+      TRACE0("[GSSLibStub_initContext] context not established");
       major -= GSS_S_CONTINUE_NEEDED;
     }
   }
-  /* release intermediate buffers */
-  releaseGSSCB(env, jcb, cb);
-  resetGSSBuffer(env, jinToken, &inToken);
+
+  /* release intermediate buffers before checking status */
+  deleteGSSCB(cb);
+  resetGSSBuffer(&inToken);
   jresult = getJavaBuffer(env, &outToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_initContext]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   return jresult;
 }
 
@@ -922,27 +957,27 @@
   gss_name_t targetName;
   jobject jtargetName;
 
-  debug(env, "[GSSLibStub_acceptContext]");
+  TRACE0("[GSSLibStub_acceptContext]");
 
   contextHdl = (gss_ctx_id_t)jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
   initGSSBuffer(env, jinToken, &inToken);
-  cb = getGSSCB(env, jcb);
   if ((*env)->ExceptionCheck(env)) {
-    free(cb);
-    resetGSSBuffer(env, jinToken, &inToken);
     return NULL;
   }
-  srcName = GSS_C_NO_NAME;
+  cb = newGSSCB(env, jcb);
+  if ((*env)->ExceptionCheck(env)) {
+    resetGSSBuffer(&inToken);
+    return NULL;
+  }
+  srcName = targetName = GSS_C_NO_NAME;
   delCred = GSS_C_NO_CREDENTIAL;
   setTarget = (credHdl == GSS_C_NO_CREDENTIAL);
   aFlags = 0;
 
-  sprintf(debugBuf,
-          "[GSSLibStub_acceptContext] before: pCred=%ld, pContext=%ld",
+  TRACE2( "[GSSLibStub_acceptContext] before: pCred=%ld, pContext=%ld",
           (long) credHdl, (long) contextHdl);
-  debug(env, debugBuf);
 
   /* gss_accept_sec_context(...) => GSS_S_CONTINUE_NEEDED(!),
      GSS_S_DEFECTIVE_TOKEN, GSS_S_DEFECTIVE_CREDENTIAL(!),
@@ -953,91 +988,107 @@
     (*ftab->acceptSecContext)(&minor, &contextHdl, credHdl,
                            &inToken, cb, &srcName, &aMech, &outToken,
                            &aFlags, &aTime, &delCred);
+  /* release intermediate buffers before checking status */
 
-  sprintf(debugBuf,
-        "[GSSLibStub_acceptContext] after: pCred=%ld, pContext=%ld, pDelegCred=%ld",
+  deleteGSSCB(cb);
+  resetGSSBuffer(&inToken);
+
+  TRACE3("[GSSLibStub_acceptContext] after: pCred=%ld, pContext=%ld, pDelegCred=%ld",
         (long)credHdl, (long)contextHdl, (long) delCred);
-  debug(env, debugBuf);
 
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
     (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
                         ptr_to_jlong(contextHdl));
-    sprintf(debugBuf, "[GSSLibStub_acceptContext] set pContext=%ld",
+    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld",
             (long)contextHdl);
-    debug(env, debugBuf);
+
     // WORKAROUND for a Heimdal bug
     if (delCred == GSS_C_NO_CREDENTIAL) {
         aFlags &= 0xfffffffe;
     }
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
-    sprintf(debugBuf, "[GSSLibStub_acceptContext] set flags=0x%x",
-            aFlags);
-    debug(env, debugBuf);
+
+    TRACE1("[GSSLibStub_acceptContext] set flags=0x%x", aFlags);
+
     if (setTarget) {
       major2 = (*ftab->inquireContext)(&minor2, contextHdl, NULL,
                               &targetName, NULL, NULL, NULL,
                               NULL, NULL);
+      checkStatus(env, jobj, major2, minor2,
+                    "[GSSLibStub_acceptContext] inquire");
+      if ((*env)->ExceptionCheck(env)) {
+         goto error;
+      }
+
       jtargetName = (*env)->NewObject(env, CLS_GSSNameElement,
                                 MID_GSSNameElement_ctor,
                                 ptr_to_jlong(targetName), jobj);
+      if ((*env)->ExceptionCheck(env)) {
+        goto error;
+      }
 
-      /* return immediately if an exception has occurred */
-      if ((*env)->ExceptionCheck(env)) {
-        resetGSSBuffer(env, jinToken, &inToken);
-        return NULL;
-      }
-      sprintf(debugBuf, "[GSSLibStub_acceptContext] set targetName=%ld",
+      TRACE1("[GSSLibStub_acceptContext] set targetName=%ld",
               (long)targetName);
-      debug(env, debugBuf);
+
       (*env)->SetObjectField(env, jcontextSpi, FID_NativeGSSContext_targetName,
                              jtargetName);
+      if ((*env)->ExceptionCheck(env)) {
+        goto error;
+      }
     }
     if (srcName != GSS_C_NO_NAME) {
       jsrcName = (*env)->NewObject(env, CLS_GSSNameElement,
                                    MID_GSSNameElement_ctor,
                                    ptr_to_jlong(srcName), jobj);
-      /* return immediately if an exception has occurred */
       if ((*env)->ExceptionCheck(env)) {
-        resetGSSBuffer(env, jinToken, &inToken);
-        return NULL;
+        goto error;
       }
-      sprintf(debugBuf, "[GSSLibStub_acceptContext] set srcName=%ld",
-              (long)srcName);
-      debug(env, debugBuf);
+
+      TRACE1("[GSSLibStub_acceptContext] set srcName=%ld", (long)srcName);
+
       (*env)->SetObjectField(env, jcontextSpi, FID_NativeGSSContext_srcName,
                              jsrcName);
+      if ((*env)->ExceptionCheck(env)) {
+        goto error;
+      }
     }
     if (major == GSS_S_COMPLETE) {
-      debug(env, "[GSSLibStub_acceptContext] context established");
+      TRACE0("[GSSLibStub_acceptContext] context established");
 
       (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_lifetime,
                           getJavaTime(aTime));
-
       (*env)->SetBooleanField(env, jcontextSpi,
                               FID_NativeGSSContext_isEstablished,
                               JNI_TRUE);
       jMech = getJavaOID(env, aMech);
+      if ((*env)->ExceptionCheck(env)) {
+        goto error;
+      }
       (*env)->SetObjectField(env, jcontextSpi,
                              FID_NativeGSSContext_actualMech, jMech);
+      if ((*env)->ExceptionCheck(env)) {
+        goto error;
+      }
       if (delCred != GSS_C_NO_CREDENTIAL) {
         jdelCred = (*env)->NewObject(env, CLS_GSSCredElement,
                                      MID_GSSCredElement_ctor,
                                      ptr_to_jlong(delCred), jsrcName, jMech);
-        /* return immediately if an exception has occurred */
         if ((*env)->ExceptionCheck(env)) {
-          resetGSSBuffer(env, jinToken, &inToken);
-          return NULL;
+          goto error;
         }
         (*env)->SetObjectField(env, jcontextSpi,
                                FID_NativeGSSContext_delegatedCred,
                                jdelCred);
-        sprintf(debugBuf, "[GSSLibStub_acceptContext] set delegatedCred=%ld",
+        TRACE1("[GSSLibStub_acceptContext] set delegatedCred=%ld",
                 (long) delCred);
-        debug(env, debugBuf);
+
+        if ((*env)->ExceptionCheck(env)) {
+          goto error;
+        }
       }
     } else if (major & GSS_S_CONTINUE_NEEDED) {
-      debug(env, "[GSSLibStub_acceptContext] context not established");
+      TRACE0("[GSSLibStub_acceptContext] context not established");
 
       if (aFlags & GSS_C_PROT_READY_FLAG) {
         (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_lifetime,
@@ -1046,13 +1097,20 @@
       major -= GSS_S_CONTINUE_NEEDED;
     }
   }
-  /* release intermediate buffers */
-  releaseGSSCB(env, jcb, cb);
-  resetGSSBuffer(env, jinToken, &inToken);
-  jresult = getJavaBuffer(env, &outToken);
+  return getJavaBuffer(env, &outToken);
 
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_acceptContext]");
-  return jresult;
+error:
+  (*ftab->releaseBuffer)(&minor, &outToken);
+  if (srcName != GSS_C_NO_NAME) {
+    (*ftab->releaseName)(&minor, &srcName);
+  }
+  if (targetName != GSS_C_NO_NAME) {
+    (*ftab->releaseName)(&minor, &targetName);
+  }
+  if (delCred != GSS_C_NO_CREDENTIAL) {
+    (*ftab->releaseCred) (&minor, &delCred);
+  }
+  return NULL;
 }
 
 /*
@@ -1076,8 +1134,7 @@
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
 
-  sprintf(debugBuf, "[GSSLibStub_inquireContext] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_inquireContext] %ld", (long)contextHdl);
 
   srcName = targetName = GSS_C_NO_NAME;
   time = 0;
@@ -1088,12 +1145,13 @@
                               &targetName, &time, NULL, &flags,
                               &isInitiator, &isEstablished);
   /* update member values if needed */
-  sprintf(debugBuf, "[GSSLibStub_inquireContext] srcName %ld", (long)srcName);
-  debug(env, debugBuf);
-  sprintf(debugBuf, "[GSSLibStub_inquireContext] targetName %ld",
-                                                (long)targetName);
-  debug(env, debugBuf);
+  TRACE2("[GSSLibStub_inquireContext] srcName %ld, targetName %ld",
+      (long)srcName, (long)targetName);
 
+  checkStatus(env, jobj, major, minor, "[GSSLibStub_inquireContext]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   result[0] = ptr_to_jlong(srcName);
   result[1] = ptr_to_jlong(targetName);
   result[2] = (jlong) isInitiator;
@@ -1102,11 +1160,13 @@
   result[5] = (jlong) getJavaTime(time);
 
   jresult = (*env)->NewLongArray(env, 6);
+  if (jresult == NULL) {
+    return NULL;
+  }
   (*env)->SetLongArrayRegion(env, jresult, 0, 6, result);
-
-  /* release intermediate buffers */
-
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_inquireContext]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   return jresult;
 }
 
@@ -1126,8 +1186,7 @@
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
 
-  sprintf(debugBuf, "[GSSLibStub_getContextMech] %ld", (long int)pContext);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_getContextMech] %ld", (long int)pContext);
 
   major = (*ftab->inquireContext)(&minor, contextHdl, NULL, NULL,
                                 NULL, &mech, NULL,  NULL, NULL);
@@ -1156,9 +1215,8 @@
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
 
-  sprintf(debugBuf, "[GSSLibStub_getContextName] %ld, isSrc=%d",
+  TRACE2("[GSSLibStub_getContextName] %ld, isSrc=%d",
           (long)contextHdl, isSrc);
-  debug(env, debugBuf);
 
   nameHdl = GSS_C_NO_NAME;
   if (isSrc == JNI_TRUE) {
@@ -1175,8 +1233,7 @@
     return jlong_zero;
   }
 
-  sprintf(debugBuf, "[GSSLibStub_getContextName] pName=%ld", (long) nameHdl);
-  debug(env, debugBuf);
+  TRACE1("[GSSLibStub_getContextName] pName=%ld", (long) nameHdl);
 
   return ptr_to_jlong(nameHdl);
 }
@@ -1195,8 +1252,8 @@
   OM_uint32 time;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_getContextTime] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_getContextTime] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) return 0;
 
@@ -1207,6 +1264,9 @@
     major = GSS_CALLING_ERROR(major) | GSS_SUPPLEMENTARY_INFO(major);
   }
   checkStatus(env, jobj, major, minor, "[GSSLibStub_getContextTime]");
+  if ((*env)->ExceptionCheck(env)) {
+    return 0;
+  }
   return getJavaTime(time);
 }
 
@@ -1224,8 +1284,8 @@
   gss_ctx_id_t contextHdl;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_deleteContext] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_deleteContext] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) return ptr_to_jlong(GSS_C_NO_CONTEXT);
 
@@ -1233,6 +1293,9 @@
   major = (*ftab->deleteSecContext)(&minor, &contextHdl, GSS_C_NO_BUFFER);
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_deleteContext]");
+  if ((*env)->ExceptionCheck(env)) {
+    return jlong_zero;
+  }
   return (jlong) ptr_to_jlong(contextHdl);
 }
 
@@ -1255,20 +1318,27 @@
   gss_qop_t qop;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_wrapSizeLimit] %ld", (long)contextHdl);
-  debug(env, debugBuf);
 
-  // Check context handle??
+  TRACE1("[GSSLibStub_wrapSizeLimit] %ld", (long)contextHdl);
+
+  if (contextHdl == GSS_C_NO_CONTEXT) {
+    // Twik per javadoc
+    checkStatus(env, jobj, GSS_S_NO_CONTEXT, 0,
+        "[GSSLibStub_wrapSizeLimit]");
+    return 0;
+  }
 
   qop = (gss_qop_t) jqop;
   outSize = (OM_uint32) joutSize;
-  maxInSize = 0;
   /* gss_wrap_size_limit(...) => GSS_S_NO_CONTEXT(!), GSS_S_CONTEXT_EXPIRED,
      GSS_S_BAD_QOP */
   major = (*ftab->wrapSizeLimit)(&minor, contextHdl, reqFlag,
                               qop, outSize, &maxInSize);
 
   checkStatus(env, jobj, major, minor, "[GSSLibStub_wrapSizeLimit]");
+  if ((*env)->ExceptionCheck(env)) {
+    return 0;
+  }
   return (jint) maxInSize;
 }
 
@@ -1288,8 +1358,8 @@
   jbyteArray jresult;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_exportContext] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_exportContext] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) {
     // Twik per javadoc
@@ -1303,7 +1373,14 @@
 
   /* release intermediate buffers */
   jresult = getJavaBuffer(env, &interProcToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   checkStatus(env, jobj, major, minor, "[GSSLibStub_exportContext]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   return jresult;
 }
 
@@ -1325,8 +1402,8 @@
   jbyteArray jresult;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_getMic] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_getMic] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) {
     // Twik per javadoc
@@ -1336,6 +1413,9 @@
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
   qop = (gss_qop_t) jqop;
   initGSSBuffer(env, jmsg, &msg);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
   /* gss_get_mic(...) => GSS_S_CONTEXT_EXPIRED, GSS_S_NO_CONTEXT(!),
      GSS_S_BAD_QOP */
@@ -1343,10 +1423,16 @@
     (*ftab->getMic)(&minor, contextHdl, qop, &msg, &msgToken);
 
   /* release intermediate buffers */
-  resetGSSBuffer(env, jmsg, &msg);
+  resetGSSBuffer(&msg);
   jresult = getJavaBuffer(env, &msgToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+  checkStatus(env, jobj, major, minor, "[GSSLibStub_getMic]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_getMic]");
   return jresult;
 }
 
@@ -1370,8 +1456,8 @@
   gss_qop_t qop;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_verifyMic] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_verifyMic] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) {
     // Twik per javadoc
@@ -1379,9 +1465,19 @@
         "[GSSLibStub_verifyMic]");
     return;
   }
+
+  qop = (gss_qop_t) (*env)->CallIntMethod(env, jprop, MID_MessageProp_getQOP);
+  if ((*env)->ExceptionCheck(env)) { return; }
+
   initGSSBuffer(env, jmsg, &msg);
+  if ((*env)->ExceptionCheck(env)) { return; }
+
   initGSSBuffer(env, jmsgToken, &msgToken);
-  qop = (gss_qop_t) (*env)->CallIntMethod(env, jprop, MID_MessageProp_getQOP);
+  if ((*env)->ExceptionCheck(env)) {
+    resetGSSBuffer(&msg);
+    return;
+  }
+
   /* gss_verify_mic(...) => GSS_S_DEFECTIVE_TOKEN, GSS_S_BAD_MIC,
      GSS_S_CONTEXT_EXPIRED, GSS_S_DUPLICATE_TOKEN(!), GSS_S_OLD_TOKEN(!),
      GSS_S_UNSEQ_TOKEN(!), GSS_S_GAP_TOKEN(!), GSS_S_NO_CONTEXT(!) */
@@ -1389,13 +1485,24 @@
     (*ftab->verifyMic)(&minor, contextHdl, &msg, &msgToken, &qop);
 
   /* release intermediate buffers */
-  resetGSSBuffer(env, jmsg, &msg);
-  resetGSSBuffer(env, jmsgToken, &msgToken);
+  resetGSSBuffer(&msg);
+  resetGSSBuffer(&msgToken);
+
+  checkStatus(env, jobj, GSS_ERROR(major), minor, "[GSSLibStub_verifyMic]");
+  if ((*env)->ExceptionCheck(env)) {
+    return;
+  }
 
   (*env)->CallVoidMethod(env, jprop, MID_MessageProp_setQOP, qop);
+  if ((*env)->ExceptionCheck(env)) {
+    return;
+  }
+
   setSupplementaryInfo(env, jobj, jprop, GSS_SUPPLEMENTARY_INFO(major),
                        minor);
-  checkStatus(env, jobj, GSS_ERROR(major), minor, "[GSSLibStub_verifyMic]");
+  if ((*env)->ExceptionCheck(env)) {
+    return;
+  }
 }
 
 /*
@@ -1420,8 +1527,8 @@
   jbyteArray jresult;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_wrap] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_wrap] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) {
     // Twik per javadoc
@@ -1431,22 +1538,43 @@
 
   confFlag =
     (*env)->CallBooleanMethod(env, jprop, MID_MessageProp_getPrivacy);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   qop = (gss_qop_t)
     (*env)->CallIntMethod(env, jprop, MID_MessageProp_getQOP);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   initGSSBuffer(env, jmsg, &msg);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   /* gss_wrap(...) => GSS_S_CONTEXT_EXPIRED, GSS_S_NO_CONTEXT(!),
      GSS_S_BAD_QOP */
   major = (*ftab->wrap)(&minor, contextHdl, confFlag, qop, &msg, &confState,
                    &msgToken);
 
+  /* release intermediate buffers */
+  resetGSSBuffer(&msg);
+  jresult = getJavaBuffer(env, &msgToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
+  checkStatus(env, jobj, major, minor, "[GSSLibStub_wrap]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   (*env)->CallVoidMethod(env, jprop, MID_MessageProp_setPrivacy,
                          (confState? JNI_TRUE:JNI_FALSE));
-
-  /* release intermediate buffers */
-  resetGSSBuffer(env, jmsg, &msg);
-  jresult = getJavaBuffer(env, &msgToken);
-
-  checkStatus(env, jobj, major, minor, "[GSSLibStub_wrap]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   return jresult;
 }
 
@@ -1471,15 +1599,20 @@
   jbyteArray jresult;
 
   contextHdl = (gss_ctx_id_t) jlong_to_ptr(pContext);
-  sprintf(debugBuf, "[GSSLibStub_unwrap] %ld", (long)contextHdl);
-  debug(env, debugBuf);
+
+  TRACE1("[GSSLibStub_unwrap] %ld", (long)contextHdl);
 
   if (contextHdl == GSS_C_NO_CONTEXT) {
     // Twik per javadoc
     checkStatus(env, jobj, GSS_S_CONTEXT_EXPIRED, 0, "[GSSLibStub_unwrap]");
     return NULL;
   }
+
   initGSSBuffer(env, jmsgToken, &msgToken);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   confState = 0;
   qop = GSS_C_QOP_DEFAULT;
   /* gss_unwrap(...) => GSS_S_DEFECTIVE_TOKEN, GSS_S_BAD_MIC,
@@ -1487,17 +1620,34 @@
      GSS_S_UNSEQ_TOKEN(!), GSS_S_GAP_TOKEN(!), GSS_S_NO_CONTEXT(!) */
   major =
     (*ftab->unwrap)(&minor, contextHdl, &msgToken, &msg, &confState, &qop);
+
+  /* release intermediate buffers */
+  resetGSSBuffer(&msgToken);
+  jresult = getJavaBuffer(env, &msg);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
+  checkStatus(env, jobj, GSS_ERROR(major), minor, "[GSSLibStub_unwrap]");
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
+
   /* update the message prop with relevant info */
   (*env)->CallVoidMethod(env, jprop, MID_MessageProp_setPrivacy,
                          (confState != 0));
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   (*env)->CallVoidMethod(env, jprop, MID_MessageProp_setQOP, qop);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   setSupplementaryInfo(env, jobj, jprop, GSS_SUPPLEMENTARY_INFO(major),
-                       minor);
+                         minor);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
 
-  /* release intermediate buffers */
-  resetGSSBuffer(env, jmsgToken, &msgToken);
-  jresult = getJavaBuffer(env, &msg);
-
-  checkStatus(env, jobj, GSS_ERROR(major), minor, "[GSSLibStub_unwrap]");
   return jresult;
 }
--- a/src/share/native/sun/security/jgss/wrapper/NativeUtil.c	Tue Aug 19 17:35:09 2014 +0100
+++ b/src/share/native/sun/security/jgss/wrapper/NativeUtil.c	Tue Aug 19 22:12:15 2014 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,8 +28,6 @@
 #include "jlong.h"
 #include <jni.h>
 
-extern void throwOutOfMemoryError(JNIEnv *env, const char *message);
-
 const int JAVA_DUPLICATE_TOKEN_CODE = 19; /* DUPLICATE_TOKEN */
 const int JAVA_OLD_TOKEN_CODE = 20; /* OLD_TOKEN */
 const int JAVA_UNSEQ_TOKEN_CODE = 21; /* UNSEQ_TOKEN */
@@ -82,7 +80,6 @@
 jmethodID MID_GSSNameElement_ctor;
 jmethodID MID_GSSCredElement_ctor;
 jmethodID MID_NativeGSSContext_ctor;
-jmethodID MID_SunNativeProvider_debug;
 jfieldID FID_GSSLibStub_pMech;
 jfieldID FID_NativeGSSContext_pContext;
 jfieldID FID_NativeGSSContext_srcName;
@@ -93,7 +90,8 @@
 jfieldID FID_NativeGSSContext_flags;
 jfieldID FID_NativeGSSContext_lifetime;
 jfieldID FID_NativeGSSContext_actualMech;
-char debugBuf[256];
+
+int JGSS_DEBUG;
 
 JNIEXPORT jint JNICALL
 JNI_OnLoad(JavaVM *jvm, void *reserved) {
@@ -291,13 +289,6 @@
     printf("Couldn't find NativeGSSContext(long, GSSLibStub) constructor\n");
     return JNI_ERR;
   }
-  MID_SunNativeProvider_debug =
-    (*env)->GetStaticMethodID(env, CLS_SunNativeProvider, "debug",
-                              "(Ljava/lang/String;)V");
-  if (MID_SunNativeProvider_debug == NULL) {
-    printf("Couldn't find SunNativeProvider.debug(String) method\n");
-    return JNI_ERR;
-  }
   /* Compute and cache the field ID */
   cls = (*env)->FindClass(env, "sun/security/jgss/wrapper/GSSLibStub");
   if (cls == NULL) {
@@ -448,14 +439,28 @@
   }
   return GSS_S_COMPLETE;
 }
+
+
+/* Throws a Java Exception by name */
+void throwByName(JNIEnv *env, const char *name, const char *msg) {
+    jclass cls = (*env)->FindClass(env, name);
+
+    if (cls != NULL) {
+        (*env)->ThrowNew(env, cls, msg);
+    }
+}
+
+void throwOutOfMemoryError(JNIEnv *env, const char *message) {
+    throwByName(env, "java/lang/OutOfMemoryError", message);
+}
+
 /*
  * Utility routine for creating a java.lang.String object
- * using the specified gss_buffer_t structure. After the,
- * String object is created, the specified gss_buffer_t
- * structure is released.
+ * using the specified gss_buffer_t structure. The specified
+ * gss_buffer_t structure is always released.
  */
 jstring getJavaString(JNIEnv *env, gss_buffer_t bytes) {
-  jstring result;
+  jstring result = NULL;
   OM_uint32 minor;
   int len;
   jbyteArray jbytes;
@@ -465,9 +470,18 @@
        NOTE: do NOT include the trailing NULL */
     len = bytes->length;
     jbytes = (*env)->NewByteArray(env, len);
+    if (jbytes == NULL) {
+      goto finish;
+    }
+
     (*env)->SetByteArrayRegion(env, jbytes, 0, len, (jbyte *) bytes->value);
+    if ((*env)->ExceptionCheck(env)) {
+      goto finish;
+    }
+
     result = (*env)->NewObject(env, CLS_String, MID_String_ctor,
                                jbytes);
+  finish:
     (*env)->DeleteLocalRef(env, jbytes);
     (*ftab->releaseBuffer)(&minor, bytes);
     return result;
@@ -490,14 +504,15 @@
   } else {
     mech = GSS_C_NO_OID;
   }
+
   /* gss_display_status(...) => GSS_S_BAD_MECH, GSS_S_BAD_STATUS */
+  // TBD: check messageContext value and repeat the call if necessary
   major = (*ftab->displayStatus)(&minor, statusValue, GSS_C_MECH_CODE, mech,
-                             &messageContext, &statusString);
-  /* release intermediate buffers */
-  msg = getJavaString(env, &statusString);
-  (*ftab->releaseBuffer)(&minor, &statusString);
-  return msg;
+                                 &messageContext, &statusString);
+
+  return getJavaString(env, &statusString);
 }
+
 /*
  * Utility routine checking the specified major and minor
  * status codes. GSSExceptions will be thrown if they are
@@ -517,11 +532,9 @@
   routineErr = GSS_ROUTINE_ERROR(major);
   supplementaryInfo = GSS_SUPPLEMENTARY_INFO(major);
 
-  sprintf(debugBuf, "%s Status major/minor = %x/%d", methodName, major, minor);
-  debug(env, debugBuf);
-  sprintf(debugBuf, "%s Status c/r/s = %d/%d/%d ", methodName, callingErr>>24,
-          routineErr>>16, supplementaryInfo);
-  debug(env, debugBuf);
+  TRACE3("%s Status major/minor = %x/%d", methodName, major, minor);
+  TRACE3("c/r/s = %d/%d/%d ", callingErr>>24, routineErr>>16,
+          supplementaryInfo);
 
   jmajor = getJavaErrorCode(routineErr | supplementaryInfo);
   jminor = minor;
@@ -529,11 +542,17 @@
     jmsg = NULL;
     if (minor != 0) {
       jmsg = getMinorMessage(env, jstub, minor);
+      if ((*env)->ExceptionCheck(env)) {
+        return;
+      }
     }
+
     gssEx = (*env)->NewObject(env, CLS_GSSException,
                               MID_GSSException_ctor3,
                               jmajor, jminor, jmsg);
-    (*env)->Throw(env, gssEx);
+    if (gssEx != NULL) {
+      (*env)->Throw(env, gssEx);
+    }
   } else {
     /* Error in calling the GSS api */
     if (callingErr == GSS_S_CALL_INACCESSIBLE_READ) {
@@ -545,56 +564,88 @@
     }
     jmajor = 13; /* use GSSException.FAILURE for now */
     jmsg = (*env)->NewStringUTF(env, msg);
+    if (jmsg == NULL) {
+      return;
+    }
     gssEx = (*env)->NewObject(env, CLS_GSSException,
                               MID_GSSException_ctor3,
                               jmajor, jminor, jmsg);
-    (*env)->Throw(env, gssEx);
+    if (gssEx != NULL) {
+      (*env)->Throw(env, gssEx);
+    }
   }
 }
+
 /*
  * Utility routine for initializing gss_buffer_t structure
  * with the byte[] in the specified jbyteArray object.
- * NOTE: need to call resetGSSBuffer(...) to free up
- * the resources.
+ * NOTE: must call resetGSSBuffer() to free up the resources
+ * inside the gss_buffer_t structure.
  */
 void initGSSBuffer(JNIEnv *env, jbyteArray jbytes,
-                   gss_buffer_t cbytes) {
+                     gss_buffer_t cbytes) {
+
+  int len;
+  void* value;
+
   if (jbytes != NULL) {
-    cbytes->length = (*env)->GetArrayLength(env, jbytes);
-    cbytes->value = (*env)->GetByteArrayElements(env, jbytes, NULL);
+    len = (*env)->GetArrayLength(env, jbytes);
+    value = malloc(len);
+    if (value == NULL) {
+      throwOutOfMemoryError(env, NULL);
+      return;
+    } else {
+      (*env)->GetByteArrayRegion(env, jbytes, 0, len, value);
+      if ((*env)->ExceptionCheck(env)) {
+        free(value);
+        return;
+      } else {
+        cbytes->length = len;
+        cbytes->value = value;
+      }
+    }
   } else {
     cbytes->length = 0;
     cbytes->value = NULL;
   }
 }
+
 /*
- * Utility routine for unpinning/releasing the byte[]
- * associated with the specified jbyteArray object.
+ * Utility routine for freeing the bytes malloc'ed
+ * in initGSSBuffer() method.
  * NOTE: used in conjunction with initGSSBuffer(...).
  */
-void resetGSSBuffer(JNIEnv *env, jbyteArray jbytes,
-                    gss_buffer_t cbytes) {
-  if ((cbytes != NULL) && (cbytes != GSS_C_NO_BUFFER) &&
-      (cbytes->length != 0)) {
-    (*env)->ReleaseByteArrayElements(env, jbytes, cbytes->value,
-                                     JNI_ABORT);
+void resetGSSBuffer(gss_buffer_t cbytes) {
+  if ((cbytes != NULL) && (cbytes != GSS_C_NO_BUFFER)) {
+    free(cbytes->value);
+    cbytes->length = 0;
+    cbytes->value = NULL;
   }
 }
+
 /*
  * Utility routine for creating a jbyteArray object using
  * the byte[] value in specified gss_buffer_t structure.
- * NOTE: the specified gss_buffer_t structure will be
- * released in this routine.
+ * NOTE: the specified gss_buffer_t structure is always
+ * released.
  */
 jbyteArray getJavaBuffer(JNIEnv *env, gss_buffer_t cbytes) {
-  jbyteArray result;
+  jbyteArray result = NULL;
   OM_uint32 minor; // don't care, just so it compiles
 
-  if ((cbytes != NULL) && (cbytes != GSS_C_NO_BUFFER) &&
-      (cbytes->length != 0)) {
-    result = (*env)->NewByteArray(env, cbytes->length);
-    (*env)->SetByteArrayRegion(env, result, 0, cbytes->length,
-                               cbytes->value);
+  if (cbytes != NULL) {
+    if ((cbytes != GSS_C_NO_BUFFER) && (cbytes->length != 0)) {
+      result = (*env)->NewByteArray(env, cbytes->length);
+      if (result == NULL) {
+        goto finish;
+      }
+      (*env)->SetByteArrayRegion(env, result, 0, cbytes->length,
+                                 cbytes->value);
+      if ((*env)->ExceptionCheck(env)) {
+        result = NULL;
+      }
+    }
+  finish:
     (*ftab->releaseBuffer)(&minor, cbytes);
     return result;
   }
@@ -604,8 +655,7 @@
 /*
  * Utility routine for creating a non-mech gss_OID using
  * the specified org.ietf.jgss.Oid object.
- * NOTE: need to call deleteGSSOID(...) afterwards to
- * release the created gss_OID structure.
+ * NOTE: must call deleteGSSOID(...) to free up the gss_OID.
  */
 gss_OID newGSSOID(JNIEnv *env, jobject jOid) {
   jbyteArray jbytes;
@@ -614,8 +664,7 @@
   if (jOid != NULL) {
     jbytes = (*env)->CallObjectMethod(env, jOid, MID_Oid_getDER);
     if ((*env)->ExceptionCheck(env)) {
-      gssEx = (*env)->ExceptionOccurred(env);
-      (*env)->Throw(env, gssEx);
+      return GSS_C_NO_OID;
     }
     cOid = malloc(sizeof(struct gss_OID_desc_struct));
     if (cOid == NULL) {
@@ -626,17 +675,24 @@
     cOid->elements = malloc(cOid->length);
     if (cOid->elements == NULL) {
       throwOutOfMemoryError(env,NULL);
-      free(cOid);
-      return GSS_C_NO_OID;
+      goto cleanup;
     }
     (*env)->GetByteArrayRegion(env, jbytes, 2, cOid->length,
                                cOid->elements);
-    (*env)->DeleteLocalRef(env, jbytes);
+    if ((*env)->ExceptionCheck(env)) {
+      goto cleanup;
+    }
     return cOid;
   } else {
     return GSS_C_NO_OID;
   }
+  cleanup:
+    (*env)->DeleteLocalRef(env, jbytes);
+    free(cOid->elements);
+    free(cOid);
+    return GSS_C_NO_OID;
 }
+
 /*
  * Utility routine for releasing the specified gss_OID
  * structure.
@@ -648,6 +704,7 @@
     free(oid);
   }
 }
+
 /*
  * Utility routine for creating a org.ietf.jgss.Oid
  * object using the specified gss_OID structure.
@@ -656,7 +713,7 @@
   int cLen;
   char oidHdr[2];
   jbyteArray jbytes;
-  jobject result;
+  jobject result = NULL;
 
   if ((cOid == NULL) || (cOid == GSS_C_NO_OID)) {
     return NULL;
@@ -665,12 +722,20 @@
   oidHdr[0] = 6;
   oidHdr[1] = cLen;
   jbytes = (*env)->NewByteArray(env, cLen+2);
+  if (jbytes == NULL) {
+    return NULL;
+  }
   (*env)->SetByteArrayRegion(env, jbytes, 0, 2, (jbyte *) oidHdr);
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   (*env)->SetByteArrayRegion(env, jbytes, 2, cLen, (jbyte *) cOid->elements);
-
+  if ((*env)->ExceptionCheck(env)) {
+    return NULL;
+  }
   result = (*env)->NewObject(env, CLS_Oid, MID_Oid_ctor1, jbytes);
   if ((*env)->ExceptionCheck(env)) {
-    (*env)->Throw(env, (*env)->ExceptionOccurred(env));
+    return NULL;
   }
   (*env)->DeleteLocalRef(env, jbytes);
   return result;
@@ -681,7 +746,7 @@
  * NOTE: need to call deleteGSSOIDSet(...) afterwards
  * to release the created gss_OID_set structure.
  */
-gss_OID_set newGSSOIDSet(JNIEnv *env, gss_OID oid) {
+gss_OID_set newGSSOIDSet(gss_OID oid) {
   gss_OID_set oidSet;
   OM_uint32 minor; // don't care; just so it compiles
 
@@ -722,26 +787,26 @@
   if (cOidSet != NULL && cOidSet != GSS_C_NO_OID_SET) {
     numOfOids = cOidSet->count;
     jOidSet = (*env)->NewObjectArray(env, numOfOids, CLS_Oid, NULL);
-    if (jOidSet != NULL) {
-      for (i = 0; i < numOfOids; i++) {
-        jOid = getJavaOID(env, &(cOidSet->elements[i]));
-        (*env)->SetObjectArrayElement(env, jOidSet, i, jOid);
-        (*env)->DeleteLocalRef(env, jOid);
+    if ((*env)->ExceptionCheck(env)) {
+      return NULL;
+    }
+    for (i = 0; i < numOfOids; i++) {
+      jOid = getJavaOID(env, &(cOidSet->elements[i]));
+      if ((*env)->ExceptionCheck(env)) {
+        return NULL;
       }
+      (*env)->SetObjectArrayElement(env, jOidSet, i, jOid);
+      if ((*env)->ExceptionCheck(env)) {
+        return NULL;
+      }
+      (*env)->DeleteLocalRef(env, jOid);
     }
     return jOidSet;
   }
   return NULL;
 }
 
-void debug(JNIEnv *env, char *msg) {
-  jstring jmsg = (*env)->NewStringUTF(env, msg);
-  (*env)->CallStaticVoidMethod(env, CLS_SunNativeProvider,
-                               MID_SunNativeProvider_debug, jmsg);
-  (*env)->DeleteLocalRef(env, jmsg);
-}
-
-int sameMech(JNIEnv *env, gss_OID mech, gss_OID mech2) {
+int sameMech(gss_OID mech, gss_OID mech2) {
   int result = JNI_FALSE; // default to not equal
 
   if (mech->length == mech2->length) {
--- a/src/share/native/sun/security/jgss/wrapper/NativeUtil.h	Tue Aug 19 17:35:09 2014 +0100
+++ b/src/share/native/sun/security/jgss/wrapper/NativeUtil.h	Tue Aug 19 22:12:15 2014 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,12 +37,13 @@
   extern OM_uint32 getGSSTime(jint);
   extern void checkStatus(JNIEnv *, jobject, OM_uint32, OM_uint32, char*);
   extern jint checkTime(OM_uint32);
+  extern void throwOutOfMemoryError(JNIEnv *, const char*);
   extern void initGSSBuffer(JNIEnv *, jbyteArray, gss_buffer_t);
-  extern void resetGSSBuffer(JNIEnv *, jbyteArray, gss_buffer_t);
+  extern void resetGSSBuffer(gss_buffer_t);
 
   extern gss_OID newGSSOID(JNIEnv *, jobject);
   extern void deleteGSSOID(gss_OID);
-  extern gss_OID_set newGSSOIDSet(JNIEnv *, gss_OID);
+  extern gss_OID_set newGSSOIDSet(gss_OID);
   extern void deleteGSSOIDSet(gss_OID_set);
 
   extern jbyteArray getJavaBuffer(JNIEnv *, gss_buffer_t);
@@ -51,13 +52,12 @@
   extern jobjectArray getJavaOIDArray(JNIEnv *, gss_OID_set);
 
   extern jstring getMinorMessage(JNIEnv *, jobject, OM_uint32);
-  extern void debug(JNIEnv *, char *);
-  extern int sameMech(JNIEnv *, gss_OID, gss_OID);
+  extern int sameMech(gss_OID, gss_OID);
 
   JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *, void *);
   JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *, void *);
 
-  extern char debugBuf[];
+  extern int JGSS_DEBUG;
 
   extern jclass CLS_Object;
   extern jclass CLS_GSSNameElement;
@@ -85,6 +85,12 @@
   extern jfieldID FID_NativeGSSContext_flags;
   extern jfieldID FID_NativeGSSContext_lifetime;
   extern jfieldID FID_NativeGSSContext_actualMech;
+  #define TRACE0(s) { if (JGSS_DEBUG) { puts(s); fflush(stdout); }}
+  #define TRACE1(s, p1) { if (JGSS_DEBUG) { printf(s, p1); fflush(stdout); }}
+  #define TRACE2(s, p1, p2) { if (JGSS_DEBUG) { printf(s, p1, p2); fflush(stdout); }}
+  #define TRACE3(s, p1, p2, p3) { if (JGSS_DEBUG) { printf(s, p1, p2, p3); fflush(stdout); }}
+
+
 #ifdef __cplusplus
 }
 #endif