Question

I know that LD_PRELOAD can be used to intercept calls to functions in shared libraries (if the app is not statically linked). However, I do not know how it can be used to add additional features or background threads to applications.

For example, I think Berkeley labs checkpoint/restart uses this method to add a background thread to an application that may be checkpointed later on.

So, now the question is how can a thread be injected into a compiled app using LD_PRELOAD without knowing before hand what functions of shared libraries are being called from this app?

Was it helpful?

Solution

It's a simple enough matter - you can implement the _init function - that would be void _init(void) {}, and you can use pthread_create in it (assuming you linked your library with -lpthread). You should compile your library with the other -l dependencies you need. GCC will allow you to replace the hardcoded _init() with another entry point, specified with an __attribute (constructor), as well. At any rate, your entry point will get called by LD.

When your library is injected, it gets injected before all others, but its own dependencies do get resolved as well, so whatever calls you make are generally ok (one notable exception being if you intercept functions you later call, for which you'll need to use the dlfcn APIs to do so safely).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top