Dynamic linker will load the all the shared library one bye one in any order. LD_PRELOAD is a environment variable containing libraries that the dynamic linker will load before loading any other libraries.
By using this we can override the function available in the later libraries. Even we can over ride the functions available in C programs libc libraries. Here i demonstrate the usage of LD_PRELOAD with simple example.
Simple C program named as ldmain.c
#include <stdio.h>
int main()
{
printf("PID = %d\n", getpid());
return 0;
}
Above program will print the process id of the current process using libc function getpid.
Now you see how we can override the libc's getpid with our own. Write our own version of the getpid function. Here i named the file as ldpid.c
Set the LD_PRELOAD envirnonment as new shared library we created before.
Run the program and see our own version of getpid called instead of libc's function.
sujinsr@fedo:~/workspace/c $ ./main
My own version of getpid() for testing it will return always 99999
PID = 99999
If you want to remove shared library configured to LD_PRELOAD just unset the environment variable like below.
sujinsr@fedo:~/workspace/c $ unset LD_PRELOAD
sujinsr@fedo:~/workspace/c $ ./main
PID = 1638
Cheers !!!!!
By using this we can override the function available in the later libraries. Even we can over ride the functions available in C programs libc libraries. Here i demonstrate the usage of LD_PRELOAD with simple example.
Simple C program named as ldmain.c
#include <stdio.h>
int main()
{
printf("PID = %d\n", getpid());
return 0;
}
Above program will print the process id of the current process using libc function getpid.
Compile the above program using gcc compiler and run the program, it will print the process id.
sujinsr@fedo:~/workspace/c $ gcc -o main ldmain.c
sujinsr@fedo:~/workspace/c $ gcc -o main ldmain.c
sujinsr@fedo:~/workspace/c $ ./main
PID = 1082
Now you see how we can override the libc's getpid with our own. Write our own version of the getpid function. Here i named the file as ldpid.c
#include <stdio.h>
int getpid()
{
printf("My own version of getpid() for testing it will return always 99999\n");
return 99999;
}
Create the shared object of that function using gcc
Create the shared object of that function using gcc
sujinsr@fedo:~/workspace/c $ gcc -o ldpid.so ldpid.c -fPIC -shared
Set the LD_PRELOAD envirnonment as new shared library we created before.
sujinsr@fedo:~/workspace/c $ export LD_PRELOAD=./ldpid.so
Run the program and see our own version of getpid called instead of libc's function.
sujinsr@fedo:~/workspace/c $ ./main
My own version of getpid() for testing it will return always 99999
PID = 99999
If you want to remove shared library configured to LD_PRELOAD just unset the environment variable like below.
sujinsr@fedo:~/workspace/c $ unset LD_PRELOAD
sujinsr@fedo:~/workspace/c $ ./main
PID = 1638
Cheers !!!!!
No comments:
Post a Comment