Question

Is it possible to pass arguments to my library, which is loaded with LD_PRELOAD:

LD_PRELOAD=lib.so ./program

How can I pass arguments to this library?

Was it helpful?

Solution

Normally I'd do this by using environment variables. For example with something like:

#include <iostream>
#include <stdlib.h>

void init() __attribute__ ((constructor));
void init() {
  std::cout << "Init: " << getenv("MYLIB") << std::endl;
}

lets you do:

MYLIB=hi LD_PRELOAD=./test.so /bin/echo
Init: hi

this doesn't have to be used in a constructor (which is a GCC extension), but that's often a handy place to use them.

What I've done in the past has been to use this, combined with a shell script wrapper that looks like it's a "normal" application. The shell script takes its arguments and pushes them into the environment variables your library expects before calling exec to load the program you want to interpose. It "feels" right to users that way without being too fragile or intrusive.

You could also do this by reading /proc/self/cmdline to read the command line of the current process directly if you'd rather. Personally I'd keep clear of interfering with the process you're working with as much as possible though.

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