Can I get the memory address on the data from the static JNI field?
For example, I have 2 situations:
First:
jclass clazz = ...; jfieldID staticFiled = ...; // static field on java object uintptr_t *staticFiledPtr = ((uint64_t) staticFiled); // get field ptr jboolean *boolPtr = *magic code with static field*; *boolPtr = true;
Second:
jclass clazz = ...; jfieldID staticFiled = ...; // static field on java object uintptr_t *staticFiledPtr = ((uint64_t) staticFiled); // get field ptr jobject *objectPtr = *magic code with static field*; jobject object = *objectPtr;
The examples are very simple. I just want to get the memory address on the static field data, without using GetStaticObjectField and etc. It is possible?
Advertisement
Answer
Fields in the JVM have no addresses. There are only references to objects (which are not pointers), and then those references are accessed at a certain offset to read or write a field.
This operation might involve un-compressing and adding the reference’ value to the heap base address to obtain a temporary memory address. It will also potentially be guarded by GC barriers. i.e. it is not a simple pointer dereference. Of course, outside of this operation the GC is free to move the object around. Since every access is guarded by a GC barrier, even the reference value itself might be stale, since the GC could defer updating the value until just before the access, inside the GC barrier.
So, in short, getting the address of a field is not really possible, and reading/writing through that address even less so. At best you can hope to get some ephemeral value which points somewhere into the Java heap.