2

I'm trying to load an Android native library with Java reflection, but at runtime the library is not found. Normally i load a native library with:

System.loadLibrary("mylib");

and everything works as expected. Now i try to call the loadLibrary method with reflection, like this:

Class<?> system = Class.forName("java.lang.System");
Method loadLibrary = system.getDeclaredMethod("loadLibrary", String.class);
loadLibrary.invoke(null, "mylib");

but at runtime i get:

Caused by: java.lang.UnsatisfiedLinkError: Library mylib not found; tried [/system/lib64/libmylib.so, /vendor/lib64/libmylib.so]
    at java.lang.Runtime.loadLibrary0(Runtime.java:1001)
    at java.lang.System.loadLibrary(System.java:1530)
    at java.lang.reflect.Method.invoke(Native Method)

It seems like with reflection loadLibrary look for the library in the wrong path. These /system/lib64:/vendor/lib64 are the paths of java.library.path property, but it does not look inside the apk. Of course the library is present in the final apk, and it's in the right place, for the right ABI.

NOTE

I can't use

System.load("absolute-path-to-lib/mylib.so");

because from where i'm calling this i don't have the path available, i don't have any Context or Application available yet to retrive the path.

Do you have any idea how to force loadLibrary to search in the current apk ? Thank you!

  • From where are you trying to do this? AFAIK it is the ClassLoader associated with the calling class that is responsible for finding the library. – Michael Feb 23 '22 at 18:29
  • I tried in the static initializer of a random Class but also in a simple Android instrumentedTest. In both cases i get the same output, no matter where i call this i always get the `UnsatisfiedLinkError`. – Martino Tiziani Feb 25 '22 at 14:08
  • 1
    What actual problem are you trying to solve? Why can’t you just stay with `System.loadLibrary("mylib");` which you said to work as expected? – Holger Feb 28 '22 at 15:48
  • 1
    I want to hide as much as possible the loading of the native library. It's easy to find `System.loadLibrary` in the bytecode, but with reflection, the class and method became string which i can then encrypt with DexGuard or similar. – Martino Tiziani Mar 01 '22 at 13:36

0 Answers0