How do I call Java code from C in a plugin and avoid random fails [closed]

20 hours ago 3
ARTICLE AD BOX

Then my plugin, written in C, is loaded it makes an initial call to JNI_CreateJavaVM(). It seems to fail completely at random. Running it one time might fail but the next time it might succeed. It looks very much like something inside JNI_CreateJavaVM() relies on uninitialized data. Since every little change I make to the code can alter the odds. And if it fails it is likely to segfault later, as if the memory gets corrupted. If it succeeds, everything works fins after that.

Running it through valgrind seems to increase (but not guarantee) the chances of success. It also generates tons of warnings (invalid writes below the stack pointer among others).

I have only tried it in Linux but with different versions of Java, mostly openjdk-25. The linking is done with meson (dependency('jni') and the path to libjvm.so is set with rpath).

The plugin is loaded with dlopen(plugin, RTLD_NOW|RTLD_GLOBAL). It doesn't really matter what it's a plugin for. I've tries to make a tiny program that just loads my plugin as well. (Consider it a concept for writing plugins in Java for applications written in C.)

Of course I've made sure that JavaVMInitArgs doesn't contain any random bytes. And that jvm and env are NULL before the call to JNI_CreateJavaVM().

I've also tried to make the call in a thread with a larger stack. I've tried to increase the stack with setrlimit(). And I've tried several different options to JavaVMInitArgs. Any such change can result in temporarily working code. But then any unrelated change can make it stop work again.

Any suggestions? Or isn't JNI supposed to work under these conditions. In that case, why?

Read Entire Article