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):
#include <stdio.h>
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:
$ 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
:
#include <stdio.h>
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
:
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:
$ 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.
There are a couple more tricks you can do with LD_PRELOAD and I'll write about them next time. Stay tuned! (Update: A Simple LD_PRELOAD Tutorial, Part Two.)