If you know that the library call that you want to intercept, you can insert into the call with a shared object loaded through LD_PRELOAD .
shortread.c:
#include <sys/types.h>
Compile something like:
gcc -shared [-m32|-m64] shortread.c -o libshortread.so
Then:
export LD_PRELOAD=/path/to/libshortread.so
Be extremely careful with such LD_PRELOAD - all processes in the process tree will be forced to load the library. A 32-bit process will not work if it needs to load a 64-bit library, as well as a 64-bit process that will be forced to load a 32-bit library. You can add the init function to the source above, which removes the LD_PRELOAD environment variable (or sets it to something harmless) to control it a bit.
You also probably need to be careful if any application uses the O_DIRECT flag for open() . Changing the number of bytes read can violate direct I / O for some Linux file systems and / or implementations, since only page-size I / O can be supported.
And this code only processes read() . You may also have to deal with creat() . Also pread() , readat() , aio_read() and lio_listio() (and maybe even a few others that I can't remember at the moment), although this is admittedly not very likely. And be careful with 32-bit processes that process large files. It has been some time since I talked to them, but it can get ugly, as I recall.
Another caveat is that calls like fopen() and fread() cannot call open() and read() library calls and can issue the corresponding system call directly. In this case, you cannot easily change the behavior of these calls. Interacting with the entire STDIO-based call family that can read data like fgets() can be very difficult without breaking anything.
And if you know that your applications are single-threaded, you can opt out of mutexes.
source share