Simone Aonzo
Simone Aonzo

Reputation: 921

Android JNI under the hood

I cannot find any references to a detailed explanation about how JNI works on Android in detail, so:

  1. Since every Android application runs in its own process, with its own instance of the Dalvik/ART virtual machine, I think that the native code will be executed in the same process, am I right?

  2. I read that when the VM invokes a function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method. But how is this made at assembly level (under the hood)?

  3. I read that you can instantiate objects, call methods, and so on, like Reflection, using the functions provided by the JNIEnv. Therefore, my question is: have I a "direct" memory access to the VM or I have always to use the JNIEnv's functions?

Upvotes: 0

Views: 495

Answers (1)

Alex Cohn
Alex Cohn

Reputation: 57173

The Android JVM is under Apache license, so the best detailed and precise description can be found in the form of source code. Note that there are two different JVMs: dalvik and art. Under the hood they are very different, to the extent that a user of JNI may consider special adaptations.

  1. the native code will be executed in the same process

    Exactly. Note that an Android app can run in more than one process, and also it can spawn child processes (normal Unix behavior). But JNI is not IPC.

  2. how is this made at assembly level?

    More or less, this is described in a related question: What does a JVM have to do when calling a native method?

  3. have I a "direct" memory access to the VM?

    Yes, you have. There is no security barrier between your C code and the JVM. You can reverse engineer the data structures, and do whatever you like. The exact implementations of the JVM not only depend on the Android version, but may be modified without notice by the vendor, as long as the public API of the JVM (including JNI) is compatible. The chances that you will do something useful with direct memory access to JVM are minimal, but the risk that it will crash is very high.

    Note that this is not a security issue: your C code is running in a separate process (with your Java code), and is subject to the same permissions restrictions as the Java code. It has no access to the private memory of other apps or procsses. Whatever you change in your instance of JVM will not effect VM that runs other apps.

Upvotes: 1

Related Questions