Call System.loadLibrary twice for the same shared library

I have a situation where two jar libraries use the same shared library. In each library, the "main interface" class loads the .so file using System.loadLibrary . My question is: if the user decides to use these two jar libraries in one project, will the second call to System.loadLibrary for the same .so file raise any exception? Or is it “somehow handled” by the system to prevent the shared libraries from loading twice? Or maybe there is a “well-known pattern” for handling such situations?

Jni shells are intended for use on Android. I am the author of both shell libraries, so by replying you can fully control the sources of java.

+7
java c ++ android jni
source share
2 answers

According to apidocs, this should not be a problem: "If this method is called more than once with the same library name, the second and subsequent calls are ignored."

+13
source share

I found one very narrow use case when this would be a problem.

If you are using an Android Android application, with android:sharedUserId="android.uid.system" in the manifest, either pre-installed on the device or signed with a platform certificate , and you are trying to call System.loadLibrary twice to load the same a library (either by running the same application twice, or by creating two separate system applications loading the same library), Android will reboot.

Calling the JNI method from this library, if it has not already been loaded, will not throw an exception when launched inside the android.uid.system process, as in a regular Android application - it will restart Android.

To avoid this, and find out if the library has already been loaded, you can read the file /proc/self/maps and find your library name there. ClassLoader and reflection will not help here - they will show JNI methods as accessible, even if the library is not already loaded.

Please note that you cannot execute if (Runtime.getRuntime().exec("/system/bin/grep <library-name> /proc/self/maps").waitFor() == 0) - the system process is prohibited run any external commands using SELinux, you will need to read the file from Java code.

Another feature is that the library must be pre-installed on the device in the /system/lib directory - if you linked the library to your application and installed the application on the device, the library will be in /data/app/..../lib , and when you try to download it from the /data section, well, you guessed it - Android will reboot.

+5
source share

All Articles