Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8313874

JNI NewWeakGlobalRef throws exception for null arg

XMLWordPrintable

    • 16
    • b08

        According to the JNI spec for NewWeakGlobalRef:

        > Returns NULL if obj refers to null, or if obj was a weak global reference, or if the VM runs out of memory. If the VM runs out of memory, an OutOfMemoryError will be thrown.

        The current behaviour is that `NewWeakGlobalRef(nullptr)` throws an OutOfMemoryError, which it should not.

        ```
         #include <stdio.h>
         #include <jni.h>
         #include "TestNull.h"

         JNIEXPORT void JNICALL Java_TestNull_testNull(JNIEnv *env, jclass a) {
             env->NewWeakGlobalRef(nullptr);
             env->ExceptionDescribe();
         }
        ```

        ```
        class TestNull {
            static { System.loadLibrary("testNull"); }
            public static void main(String[] args) {
                testNull();
            }
            public static native void testNull();
        }
        ```

        ```
        java -Djava.library.path=. TestNull
        Exception in thread "main" java.lang.OutOfMemoryError: C heap space
        at TestNull.testNull(Native Method)
        at TestNull.main(TestNull.java:4)
        ```

        It seems that [this code](https://github.com/openjdk/jdk/blob/dc01604756c22889412f9f25b534488180327317/src/hotspot/share/prims/jni.cpp#L2879-L2881) forgets to handle the case where the original argument was null.

        Thanks to Boris Rasin for reporting this issue in https://github.com/corretto/corretto-17/issues/145.

              ogillespie Oli Gillespie
              ogillespie Oli Gillespie
              Votes:
              0 Vote for this issue
              Watchers:
              6 Start watching this issue

                Created:
                Updated:
                Resolved: