JNI Tips annotated

copied from JNI Tips .

see also Getting Started with the NDK.


Java Native Interface Specification (Java 7)

JavaVM and JNIEnv

Both of these are essentially pointers to pointers to function tables. (In the C++ version, they’re classes with a pointer to a function table and a member function for each JNI function that indirects through the table.)

  1. In theory you can have multiple JavaVMs per process, but Android only allows one.
  2. The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as the first argument
  3. The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. If a piece of code has no other way to get its JNIEnv, you should share the JavaVM, and use GetEnv to discover the thread’s JNIEnv. (Assuming it has one; see AttachCurrentThread below.)
  4. The C declarations of JNIEnv and JavaVM are different from the C++ declarations. It’s a bad idea to include JNIEnv arguments in header files included by both languages.

Threads

  1. All threads are Linux threads, scheduled by the kernel.
  2. They’re usually started from managed code (using Thread.start), but they can also be created elsewhere and then attached to the JavaVM. (e.g. pthread_create, AttachCurrentThread, AttachCurrentThreadAsDaemon). Until a thread is attached, it has no JNIEnv, and cannot make JNI calls.
  3. Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the “main” ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread is a no-op.
  4. If garbage collection is in progress, or the debugger has issued a suspend request, Android will pause the thread the next time it makes a JNI call.
  5. Threads attached through JNI must call DetachCurrentThread before they exit. pthread_key_create and pthread_setspecific come in handy.

jclass, jmethodID, and jfieldID

If you want to access an object’s field from native code, you would do the following:

  • Get the class object reference for the class with FindClass
  • Get the field ID for the field with GetFieldID
  • Get the contents of the field with something appropriate, such as GetIntField

Similarly, to call a method, you’d first get a class object reference and then a method ID. The IDs are often just pointers to internal runtime data structures. Looking them up may require several string comparisons, but once you have them the actual call to get the field or invoke the method is very quick.

If performance is important, it’s useful to look the values up once and cache the results in your native code. Because there is a limit of one JavaVM per process, it’s reasonable to store this data in a static local structure.

The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes are only unloaded if all classes associated with a ClassLoader can be garbage collected, which is rare but will not be impossible in Android.

If you would like to cache the IDs when a class is loaded, and automatically re-cache them if the class is ever unloaded and reloaded, the correct way to initialize the IDs is to add a piece of code that looks like this to the appropriate class

 /*
  * We use a class initializer to allow the native code to cache some
  * field offsets. This native function looks up and caches interesting
  * class/field/method IDs. Throws on failure.
  */
 private static native void nativeInit();

 static {
     nativeInit();
}

Local and Global References

Every argument passed to a native method, and almost every object returned by a JNI function is a “local reference”. This means that it’s valid for the duration of the current native method in the current thread. Even if the object itself continues to live on after the native method returns, the reference is not valid.

This applies to all sub-classes of jobject, including jclass, jstring, and jarray. (The runtime will warn you about most reference mis-uses when extended JNI checks are enabled.)

The only way to get non-local references is via the functions NewGlobalRef and NewWeakGlobalRef.

If you want to hold on to a reference for a longer period, you must use a “global” reference. The NewGlobalRef function takes the local reference as an argument and returns a global one. The global reference is guaranteed to be valid until you call DeleteGlobalRef.

This pattern is commonly used when caching a jclass returned from FindClass, e.g.:

jclass localClass = env->FindClass("MyClass");
jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));

All JNI methods accept both local and global references as arguments. It’s possible for references to the same object to have different values. For example, the return values from consecutive calls to NewGlobalRef on the same object may be different. To see if two references refer to the same object, you must use the IsSameObject function. Never compare references with == in native code.

One consequence of this is that you must not assume object references are constant or unique in native code. The 32-bit value representing an object may be different from one invocation of a method to the next, and it’s possible that two different objects could have the same 32-bit value on consecutive calls. Do not use jobject values as keys.

Programmers are required to “not excessively allocate” local references. In practical terms this means that if you’re creating large numbers of local references, perhaps while running through an array of objects, you should free them manually with DeleteLocalRef instead of letting JNI do it for you. The implementation is only required to reserve slots for 16 local references, so if you need more than that you should either delete as you go or use EnsureLocalCapacity/PushLocalFrame to reserve more.

Note that jfieldIDs and jmethodIDs are opaque types, not object references, and should not be passed to NewGlobalRef. The raw data pointers returned by functions like GetStringUTFChars and GetByteArrayElements are also not objects. (They may be passed between threads, and are valid until the matching Release call.)

One unusual case deserves separate mention. If you attach a native thread with AttachCurrentThread, the code you are running will never automatically free local references until the thread detaches. Any local references you create will have to be deleted manually. In general, any native code that creates local references in a loop probably needs to do some manual deletion.

UTF-8 and UTF-16 Strings

The Java programming language uses UTF-16. For convenience, JNI provides methods that work with Modified UTF-8 as well. The modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. The nice thing about this is that you can count on having C-style zero-terminated strings, suitable for use with standard libc string functions. The down side is that you cannot pass arbitrary UTF-8 data to JNI and expect it to work correctly.

If possible, it’s usually faster to operate with UTF-16 strings. Android currently does not require a copy in GetStringChars, whereas GetStringUTFChars requires an allocation and a conversion to UTF-8. Note that UTF-16 strings are not zero-terminated, and \u0000 is allowed, so you need to hang on to the string length as well as the jchar pointer.

Don’t forget to Release the strings you Get. The string functions return jchar* or jbyte*, which are C-style pointers to primitive data rather than local references. They are guaranteed valid until Release is called, which means they are not released when the native method returns.

Data passed to NewStringUTF must be in Modified UTF-8 format. A common mistake is reading character data from a file or network stream and handing it to NewStringUTF without filtering it. Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII characters or convert them to proper Modified UTF-8 form. If you don’t, the UTF-16 conversion will likely not be what you expect. The extended JNI checks will scan strings and warn you about invalid data, but they won’t catch everything.

Primitive Arrays

While arrays of objects must be accessed one entry at a time, arrays of primitives can be read and written directly as if they were declared in C.

To make the interface as efficient as possible without constraining the VM implementation, the Get<PrimitiveType>ArrayElements family of calls allows the runtime to either return a pointer to the actual elements, or allocate some memory and make a copy. Either way, the raw pointer returned is guaranteed to be valid until the corresponding Release call is issued (which implies that, if the data wasn’t copied, the array object will be pinned down and can’t be relocated as part of compacting the heap). You must Release every array you Get. Also, if the Get call fails, you must ensure that your code doesn’t try to Release a NULL pointer later.

The Release call takes a mode argument that can have one of three values. The actions performed by the runtime depend upon whether it returned a pointer to the actual data or a copy of it.

isCopy, JNI_COMMIT, JNI_ABORT

Region Calls

There is an alternative to calls like Get<Type>ArrayElements and GetStringChars that may be very helpful when all you want to do is copy data in or out

env->GetByteArrayRegion(array, 0, len, buffer);
Set<Type>ArrayRegion
GetStringRegion
GetStringUTFRegion

Exceptions

You must not call most JNI functions while an exception is pending. Your code is expected to notice the exception (via the function’s return value, ExceptionCheck, or ExceptionOccurred) and return, or clear the exception and handle it.

The only JNI functions that you are allowed to call while an exception is pending are:

  • DeleteGlobalRef
  • DeleteLocalRef
  • DeleteWeakGlobalRef
  • ExceptionCheck
  • ExceptionClear
  • ExceptionDescribe
  • ExceptionOccurred
  • MonitorExit
  • PopLocalFrame
  • PushLocalFrame
  • Release<PrimitiveType>ArrayElements
  • ReleasePrimitiveArrayCritical
  • ReleaseStringChars
  • ReleaseStringCritical
  • ReleaseStringUTFChars

Many JNI calls can throw an exception, but often provide a simpler way of checking for failure. For example, if NewString returns a non-NULL value, you don’t need to check for an exception. However, if you call a method (using a function like CallObjectMethod), you must always check for an exception, because the return value is not going to be valid if an exception was thrown.

Note that exceptions thrown by interpreted code do not unwind native stack frames, and Android does not yet support C++ exceptions. The JNI Throw and ThrowNew instructions just set an exception pointer in the current thread. Upon returning to managed from native code, the exception will be noted and handled appropriately.

Native code can “catch” an exception by calling ExceptionCheck or ExceptionOccurred, and clear it with ExceptionClear. As usual, discarding exceptions without handling them can lead to problems.

There are no built-in functions for manipulating the Throwable object itself, so if you want to (say) get the exception string you will need to find the Throwable class, look up the method ID for getMessage "()Ljava/lang/String;", invoke it, and if the result is non-NULL use GetStringUTFChars to get something you can hand to printf(3) or equivalent.

Extended Checking

JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.

There are several ways to enable CheckJNI.

  1. If you’re using the emulator, CheckJNI is on by default.
  2. If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:

    adb shell stop
    adb shell setprop dalvik.vm.checkjni true
    adb shell start

  3. for regular devices: adb shell setprop debug.checkjni 1, this won’t affect already-running apps, butany app launched from that point on will have CheckJNI enabled.

  4. You can also set the android:debuggable attribute in your application’s manifest to turn on CheckJNI just for your app. Note that the Android build tools will do this automatically for certain build types. (WHAT ?)

Native Libraries

You can load native code from shared libraries with the standard System.loadLibrary call. The preferred way to get at your native code is:

  • Call System.loadLibrary from a static class initializer. The argument is the “undecorated“ library name, so to load “libfubar.so” you would pass in “fubar”.
  • Provide a native function: jint JNI_OnLoad(JavaVM* vm, void* reserved)
  • In JNI_OnLoad, register all of your native methods. You should declare the methods “static” so the names don’t take up space in the symbol table on the device.

The JNI_OnLoad function should look something like this if written in C++:

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    JNIEnv* env;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    // Get jclass with env->FindClass.
    // Register methods with env->RegisterNatives.

    return JNI_VERSION_1_6;
}

You can also call System.load with the full path name of the shared library.

This is the recommended approach, but not the only approach. Explicit registration is not required, nor is it necessary that you provide a JNI_OnLoad function. You can instead use “discovery” of native methods that are named in a specific way (see the JNI spec for details), though this is less desirable because if a method signature is wrong you won’t know about it until the first time the method is actually used.

One other note about JNI_OnLoad: any FindClass calls you make from there will happen in the context of the class loader that was used to load the shared library. Normally FindClass uses the loader associated with the method at the top of the interpreted stack, or if there isn’t one (because the thread was just attached) it uses the “system” class loader. This makes JNI_OnLoad a convenient place to look up and cache class object references.

64-bit Considerations

For the most part this isn’t something that you will need to worry about when interacting with native code, but it becomes significant if you plan to store pointers to native structures in integer fields in an object. To support architectures that use 64-bit pointers, you need to stash your native pointers in a long field rather than an int.

Unsupported Features/Backwards Compatibility

All JNI 1.6 features are supported, with the following exception:

  1. DefineClass is not implemented.

Before Android 4.0, Android 2.2, Android 2.0 respectively, there are some restrictions, see original text for detail.