Remix.run Logo
pron a day ago

Tangential:

The --enable-native-access option mentioned in the article is part of a large effort we call "Integrity by Default"[1]. The idea is that a library module can violate invariants established by another module (e.g. access to private fields and methods, mutation of final fields etc.) requires approval by the application, so that a library will not be able to have a global effect on the application without its knowledge, and the correctness of each module could be verfied in isolation.

Now, --enable-native-access is also required to use JNI, but JNI can violate the integrity of Java invariants in a much more extensive way than FFM can. For example, JNI gives native code access to private fields of classes in arbitrary modules, while FFM does not. The only invariant FFM can break is freedom from undefined behaviour in the C sense. This is dangerous, but not nearly as dangerous as what JNI can do.

For the time being, we decided to enable both FFM and JNI with the same flag, but, given how more dangerous JNI is, in the future we may introduce a more fine-grained flag that would allow the use of FFM but not of JNI.

[1]: https://openjdk.org/jeps/8305968

tadfisher a day ago | parent [-]

Where does the "final means final" effort fit in? Can the JVM prevent modification of final fields via JNI, or is --enable-native-access also going to require (or imply) the flag which enables setAccessible() and friends?

pron a day ago | parent [-]

Ah, that's a great question, and the answer is in the JEP (https://openjdk.org/jeps/500#Mutating-final-fields-from-nati...).

When running with -Xcheck:jni, you'll get a warning when trying to mutate a final field with JNI.

Now, enabling this check by default without harming JNI performance proved to be too much of an effort. However, mutating final fields with JNI even today can already lead to undefined behaviour, including horrible miscompilation, where different Java methods can read different values of the field, for final fields that the JVM already trusts to be immutable, such as static finals, record components, or a few other cases (indeed, there are non-final fields that the JVM trusts to be assigned only once, and mutating those with JNI is also undefined behaviour). As the compiler starts trusting more final fields after this change, mutating almost all final fields will lead to undefined behaviour. Then again, using JNI can lead to undefined behaviour in many ways.

So to make sure your JNI code isn't mutating finals, test with -Xcheck:jni (as of JDK 26).

gorset a day ago | parent [-]

This brings back memories debugging an azul zing bug where an effectively final optimization ended up doing the wrong thing with zstd-jni. It was painful enough that I couldn’t convince the team to enable the optimization again for years after it was fixed.