A Simple LD_PRELOAD Tutorial
本文转载自:
LD_PRELOAD 的详细描述可以从man ld.so中查询。
Did you know you could override the C standard library functions, such as printf and fopen with your own functions in any program? In this short article I’ll teach you how to do it via the LD_PRELOAD environment variable.
Let’s start with a simple C program (prog.c):
1 |
|
The code above simply makes a call to the standard fopen function and then checks its return value. Now, let’s compile and execute it:
1 | ls |
As you can see, the call to fopen was successful.
Now, let’s write our own version of fopen that always fails and call this file myfopen.c:
1 |
|
Let’s compile it as a shared library called myfopen.so:
1 | gcc -Wall -fPIC -shared -o myfopen.so myfopen.c |
Now, if we set the LD_PRELOAD environment variable to myfopen.so shared library before running the program that we created earlier, we get this output:
1 | LD_PRELOAD=./myfopen.so ./prog |
As you can see, fopen got replaced with our own version that is always failing.
This is really handy if you need to debug or replace certain parts of programs or libraries that you didn’t write.