Overview
July 26, 2019 ยท View on GitHub
JNI (Java Native Interface) is the mechanism that enables Java code to call native functions, and native code to call Java functions.
- Native code calls into Java using apis from
<jni.h>, which basically mirror Java's reflection APIs. - Java code calls native functions by declaring body-less functions with the
nativekeyword, and then calling them as normal Java functions.
jni_generator generates boiler-plate code with the goal of making our code:
- easier to write, and
- typesafe.
jni_generator uses regular expressions to parse .Java files, so don't do
anything too fancy. E.g.:
- Classes must be either explicitly imported, or are assumed to be in
the same package. To use
java.langclasses, add an explicit import. - Inner classes need to be referenced through the outer class. E.g.:
void call(Outer.Inner inner)
The presense of any JNI within a class will result in ProGuard obfuscation for the class to be disabled.
Exposing Native Methods
Without Crazy Linker:
- Java->Native calls are exported from the shared library and lazily resolved
by the runtime (via
dlsym()).
With Crazy Linker:
- Java->Native calls are explicitly registered with JNI on the native side.
Explicit registration is necessary because crazy linker provides its own
dlsym(), but JNI is hardcoded to use the system'sdlsym().- The logic to explicitly register stubs is generated by
jni_registration_generator.py.- This script finds all native methods by scanning all source
.javafiles of an APK. Inefficient, but very convenient.
- This script finds all native methods by scanning all source
- Since
dlsym()is not used in this case, we use a linker script to avoid the cost of exporting symbols from the shared library (refer to//build/config/android:hide_all_but_jni_onload).
- The logic to explicitly register stubs is generated by
jni_registration_generator.pyexposes two registrations methods:RegisterNonMainDexNatives- Registers native functions needed by multiple process types (e.g. Rendereres, GPU process).RegisterMainDexNatives- Registers native functions needed only by the browser process.
Exposing Java Methods
Java methods just need to be annotated with @CalledByNative. The generated
functions can be put into a namespace using @JNINamespace("your_namespace").
Usage
Because the generator does not generate any source files, generated headers must
not be #included by multiple sources. If there are Java functions that need to
be called by multiple sources, one source should be chosen to expose the
functions to the others via additional wrapper functions.
Calling Java -> Native
There are two ways to call native methods:
Method 1 - Using the 'native' keyword (soon to be deprecated)
- Works for both static and non-static methods.
- Methods marked as
nativewill have stubs generated for them that forward calls to C++ function (that you must write). - If the first parameter is a C++ object (e.g.
long mNativePointer), then the bindings will automatically generate the appropriate cast and call into C++ code (JNI itself is only C).
Method 2 - Using an interface annotated with @NativeMethods
- Declare methods using a nested interface annotated with
@NativeMethods. - The JNI annotation processor generates a class named
${OriginalClassName}Jniwith aget()method that returns an implementation of the annotated interface. The C++ function that it routes to is the same as if it would be in the legacy method. - See example below for usage.
To add JNI to a class:
- Enable the JNI processor by adding to your
android_librarytarget:annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] deps = [ "//base:jni_java" ] - Create a nested-interface annotated with
@NativeMethodsthat contains the declaration of the corresponding static methods you wish to have implemented. - Call native functions using
${OriginalClassName}Jni.get().${method}
Example:
// The following classes would have the same generated native bindings (with the
// exception of differing class names).
// Legacy/deprecated static methods
class Legacy {
static native void nativeFoo();
static native double nativeBar(int a, int b);
// Either the |ClassName| part of the |nativeClassName| parameter name must
// match the native class name exactly, or the method annotation
// @NativeClassQualifiedName("ClassName") must be used.
//
// If the native class is nested, use
// @NativeClassQualifiedName("FooClassName::BarClassName") and call the
// parameter |nativePointer|.
native void nativeNonStatic(long nativeClassName);
void callNatives() {
nativeFoo()
nativeBar(1,2);
nativeNonStatic(mNativePointer);
}
}
// Equivalent using new style:
class NewStyle {
// Cannot be private. Must be package or public.
@NativeMethods
/* package */ interface Natives {
void foo();
double bar(int a, int b);
// Either the |ClassName| part of the |nativeClassName| parameter name must
// match the native class name exactly, or the method annotation
// @NativeClassQualifiedName("ClassName") must be used.
//
// If the native class is nested, use
// @NativeClassQualifiedName("FooClassName::BarClassName") and call the
// parameter |nativePointer|.
void nonStatic(long nativeClassName, NewStyle self);
}
void callNatives() {
// NewStyleJni is generated by the JNI annotation processor.
// Storing NewStyleJni.get() in a field defeats some of the desired R8
// optimizations, but local variables are fine.
Natives jni = NewStyleJni.get();
jni.foo();
jni.bar(1,2);
jni.nonStatic(this, mNativePointer);
}
}
Testing Mockable Natives
- Add the
JniMockerrule to your test. - Call
JniMocker#mockin asetUp()method for each interface you want to stub out.
Note: Mocking native methods doesn't work in tests that are part of APKs that
use an apk_under_test.
This crbug tracks removing the apk_under_test variable.
JniMocker will reset the stubs during tearDown().
/**
* Tests for {@link AnimationFrameTimeHistogram}
*/
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class AnimationFrameTimeHistogramTest {
@Rule
public JniMocker mocker = new JniMocker();
@Mock
AnimationFrameTimeHistogram.Natives mNativeMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mocker.mock(AnimationFrameTimeHistogramJni.TEST_HOOKS, mNativeMock);
}
@Test
public void testNatives() {
AnimationFrameTimeHistogram hist = new AnimationFrameTimeHistogram("histName");
hist.startRecording();
hist.endRecording();
verify(mNativeMock).saveHistogram(eq("histName"), any(long[].class), anyInt());
}
}
If a native method is called without setting a mock in a unit test, an
UnsupportedOperationException will be thrown.
Calling Native -> Java
- Methods annotated with
@CalledByNativewill have stubs generated for them.- Inner class methods must provide the inner class name explicitly
(ex.
@CalledByNative("InnerClassName"))
- Inner class methods must provide the inner class name explicitly
(ex.
- Just call the generated stubs defined in generated
.hfiles.
Java Objects and Garbage Collection
All pointers to Java objects must be registered with JNI in order to prevent garbage collection from invalidating them.
For Strings & Arrays - it's common practice to use the //base/android/jni_*
helpers to convert them to std::vectors and std::strings as soon as
possible.
For other objects - use smart pointers to store them:
ScopedJavaLocalRef<>- When lifetime is the current function's scope.ScopedJavaGlobalRef<>- When lifetime is longer than the current function's scope.JavaObjectWeakGlobalRef<>- Weak reference (do not prevent garbage collection).JavaParamRef<>- Use to accept any of the above as a parameter to a function without creating a redundant registration.
Additional Guidelines / Advice
Minimize the surface API between the two sides. Rather than calling multiple functions across boundaries, call only one (and then on the other side, call as many little functions as required).
If a Java object "owns" a native one, store the pointer via
"long mNativeClassName". Ensure to eventually call a native method to delete
the object. For example, have a close() that deletes the native object.
The best way to pass "compound" types across in either direction is to create an inner class with PODs and a factory function. If possible, make mark all the fields as "final".
Build Rules
generate_jni- Generates a header file with stubs for given.javafilesgenerate_jar_jni- Generates a header file with stubs for a given.jarfilegenerate_jni_registration- Generates a header file with functions to register native-side JNI methods (required only when using crazy linker).
Refer to //build/config/android/rules.gni for more about the GN templates.
Changing jni_generator
- Python unit tests live in
jni_generator_tests.py - A working demo app exists as
//base/android/jni_generator:sample_jni_apk