Clear pending exception before throwing a new one.

The JNI helper function that throws an exception calls FindClass, which
isn't allowed if an exception is currently pending.  Some of our code
called this when an operation failed without noting that the thing that
failed already threw an exception; this caused the VM to blow up in a
rather unhelpful way.

We now log the class name and optional message from the original
exception, clear it, and then allocate & throw the new one.

For bug 2141867.
diff --git a/libnativehelper/JNIHelp.c b/libnativehelper/JNIHelp.c
index fa6b532..0aecd12 100644
--- a/libnativehelper/JNIHelp.c
+++ b/libnativehelper/JNIHelp.c
@@ -1,6 +1,20 @@
 /*
- * Copyright 2006 The Android Open Source Project
+ * Copyright (C) 2006 The Android Open Source Project
  *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
  * JNI helper functions.
  */
 #define LOG_TAG "JNIHelp"
@@ -34,22 +48,86 @@
 }
 
 /*
+ * Get a human-readable summary of an exception object.  The buffer will
+ * be populated with the "binary" class name and, if present, the
+ * exception message.
+ */
+static void getExceptionSummary(JNIEnv* env, jthrowable excep, char* buf,
+    size_t bufLen)
+{
+    if (excep == NULL)
+        return;
+
+    /* get the name of the exception's class; none of these should fail */
+    jclass clazz = (*env)->GetObjectClass(env, excep); // exception's class
+    jclass jlc = (*env)->GetObjectClass(env, clazz);   // java.lang.Class
+    jmethodID getNameMethod =
+        (*env)->GetMethodID(env, jlc, "getName", "()Ljava/lang/String;");
+    jstring className = (*env)->CallObjectMethod(env, clazz, getNameMethod);
+
+    /* get printable string */
+    const char* nameStr = (*env)->GetStringUTFChars(env, className, NULL);
+    if (nameStr == NULL) {
+        snprintf(buf, bufLen, "%s", "out of memory generating summary");
+        (*env)->ExceptionClear(env);            // clear OOM
+        return;
+    }
+
+    /* if the exception has a message string, get that */
+    jmethodID getThrowableMessage =
+        (*env)->GetMethodID(env, clazz, "getMessage", "()Ljava/lang/String;");
+    jstring message = (*env)->CallObjectMethod(env, excep, getThrowableMessage);
+
+    if (message != NULL) {
+        const char* messageStr = (*env)->GetStringUTFChars(env, message, NULL);
+        snprintf(buf, bufLen, "%s: %s", nameStr, messageStr);
+        if (messageStr != NULL)
+            (*env)->ReleaseStringUTFChars(env, message, messageStr);
+        else
+            (*env)->ExceptionClear(env);        // clear OOM
+    } else {
+        strncpy(buf, nameStr, bufLen);
+        buf[bufLen-1] = '\0';
+    }
+
+    (*env)->ReleaseStringUTFChars(env, className, nameStr);
+}
+
+/*
  * Throw an exception with the specified class and an optional message.
+ *
+ * If an exception is currently pending, we log a warning message and
+ * clear it.
+ *
+ * Returns 0 if the specified exception was successfully thrown.  (Some
+ * sort of exception will always be pending when this returns.)
  */
 int jniThrowException(JNIEnv* env, const char* className, const char* msg)
 {
     jclass exceptionClass;
 
+    if ((*env)->ExceptionCheck(env)) {
+        /* TODO: consider creating the new exception with this as "cause" */
+        char buf[256];
+
+        jthrowable excep = (*env)->ExceptionOccurred(env);
+        (*env)->ExceptionClear(env);
+        getExceptionSummary(env, excep, buf, sizeof(buf));
+        LOGW("Discarding pending exception (%s) to throw %s\n",
+            buf, className);
+    }
+
     exceptionClass = (*env)->FindClass(env, className);
     if (exceptionClass == NULL) {
         LOGE("Unable to find exception class %s\n", className);
-        assert(0);      /* fatal during dev; should always be fatal? */
+        /* ClassNotFoundException now pending */
         return -1;
     }
 
     if ((*env)->ThrowNew(env, exceptionClass, msg) != JNI_OK) {
         LOGE("Failed throwing '%s' '%s'\n", className, msg);
-        assert(!"failed to throw");
+        /* an exception, most likely OOM, will now be pending */
+        return -1;
     }
     return 0;
 }