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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(void) {
printf("Calling the fopen() function...\n");
FILE *fd = fopen("test.txt","r");
if (!fd) {
printf("fopen() returned NULL\n");
return 1;
}
printf("fopen() succeeded\n");
return 0;
}
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
2
3
4
5
6
7
8
9
10
11 ls
prog.c test.txt
gcc prog.c -o prog
ls
prog prog.c test.txt
./prog
Calling the fopen() function...
fopen() succeeded
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
2
3
4
5
6
FILE *fopen(const char *path, const char *mode) {
printf("Always failing fopen\n");
return NULL;
}
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
2
3
4 LD_PRELOAD=./myfopen.so ./prog
Calling the fopen() function...
Always failing fopen
fopen() returned NULL
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.