Search code examples
cgccmakefilestdio

Can I intercept normal stdio calls in a C program, do some work and then call the original ones?


I have a bunch of C files that try to read and write CSV and other random data to and from disk using stdio functions like fread(), fwrite(), fseek(). (If it matters, it's for a university assignment where we are to experiment with IO performance using different block sizes, and various structures to track data on disk files and so on.)

What I wanted to do was compile these source files (there are dozens of them) without the definitions for fopen(), fread(), fwrite() that come from <stdio.h>. I want to supply my own fopen(), fread(), fwrite() where I track some information, like which process tried to read which file, and how many blocks/pages where read and things like that, and then call the normal stdio functions.

I don't want to have to go through every line of every file and change fopen() to my_fopen() .... is there better way to do this at compile time?

I am half way working on a Python program that scans the source files and changes these calls with my functions but it's getting a bit messy and I am kind of lost. I thought maybe there is a better way to do this; if you could point me in the right direction, like what to search for that would be great.

Also I don't want to use some Linux profiling stuff that reports which syscalls where made and what not; I just want to execute some code before calling these functions.


Solution

  • An alternative to the LD_PRELOAD trick (which requires you to write a separate library and works only on Linux) you can use the --wrap option of the GNU linker. See here for an example of this technique.

    Main differences with LD_PRELOAD:

    • no external library needed - it's all in the executable;
    • no runtime options needed;
    • works on any platform as long as you are using the GNU toolchain;
    • works only for the calls that are resolved at link time - dynamic libraries will still use the original functions