CHAPTER 67. LINUX CHAPTER 67. LINUX
opened_fd=fd; // that's our file! record its file descriptor
else
opened_fd=0;
return fd;
};
int close(int fd)
{
find_original_functions();
if (fd==opened_fd)
opened_fd=0; // the file is not opened anymore
return (*close_ptr)(fd);
};
ssize_t read(int fd, void *buf, size_t count)
{
find_original_functions();
if (opened_fd!=0 && fd==opened_fd)
{
// that's our file!
return snprintf (buf, count, "%d %d", 0x7fffffff, 0x7fffffff)+1;
};
// not our file, go to real read() function
return (*read_ptr)(fd, buf, count);
};
(Source code at GitHub)
Let’s compile it as common dynamic library:
gcc -fpic -shared -Wall -o fool_uptime.so fool_uptime.c -ldl
Let’s runuptimewhile loading our library before the others:
LD_PRELOAD=pwd
/fool_uptime.so uptime
And we see:
01:23:02 up 24855 days, 3:14, 3 users, load average: 0.00, 0.01, 0.05
If theLD_PRELOAD environment variable always points to the filename and path of our library, it is to be loaded for all
starting programs.
More examples:
- Very simple interception of the strcmp() (Yong Huang)http://go.yurichev.com/17143
- Kevin Pulo—Fun with LD_PRELOAD. A lot of examples and ideas.yurichev.com
- File functions interception for compression/decompression files on fly (zlibc).http://go.yurichev.com/17146