Is it possible to programatically preload a shared library?

Viewed 141

Im building a project that needs to modify the behavior of some bionic methods (e.g getaddrinfo, __android_print). I've been able to create the hooked library both using a standalone compiler or including it directly in the Apk using Cmake. I've been able to preload the shared library using setprop wrap.com.foo.bar and LD_PRELOAD, and it is working and I get the result I want. However, I want to preload the hooked library programatically so I dont need to go through the specific steps of LD_PRELOAD (a.k.a disable SELinux, root device, setprop), every time after rebooting a device.

I tried using

// MainActivity
companion object {
   System.load("/data/data/com.foo.bar/lib/libhookedmethod.so")
}

But I don't see the method being replaced.

As a reference, the hooked method is rather simple. Here's an extreme simplification:


int __android_print(varargs a) {
   int realmethod(...);
   realmethod = dlsym("__android_print");
   doStuff();
   int res = realmethod(a) ;
   return res;
}

Again, compiling and using LD_PRELOAD works, but I want to achieve it without using LD_PRELOAD... Anything helps! Thanks in advance

1 Answers

The LD_PRELOAD works by asking the dynamic loader to load referenced library before any other. The loader resolves references to a given symbol by searching loaded libraries in their load order.

Once a symbol is resolved to a particular library, it will not be rebound to some other library for the duration of this process.

Above explanation should make it obvious why loading libhookedmethod.so after the program is already running has no effect.

About the only way you can achieve what you want is to setenv() (if not already set) and re-exec() the current process. Something like this:

int main(int argc, char *argv[])
{
  char *e = getenv("LD_PRELOAD");
  if (e == NULL || /* any other checks that show LD_PRELOAD to not be as we want it */) {
    setenv("LD_PRELOAD", ..., 1);
    execvp(argv[0], argv);
  }
  // LD_PRELOAD is to our liking. Run the actual program.
  ...
}
Related