27 May, 2011

How to wrap/overwrite/override function in C (gcc and clang)

Today I was tinkering with executing some code right before main() in C. I found a good description in this post. Here is some code similar to the code in that post:
__attribute__((constructor)) void before() {
    printf("Before main\n");
}

int main() {
    printf("Main\n");
    return 0;
}

Another task was to access to the argc and argv outside main(). The reason is that I reimplement some library and can't modify its users. With wrap option available both in gcc and clang I can at first execute my version of main (which can store argc and argv somewhere) and then call real main. Code below can be compiled with "clang sample.c -Wl,-wrap,main" or "gcc sample.c -Wl,-wrap,main":
int __real_main(int argc, char* argv[]);

int __wrap_main(int argc, char* argv[])
{
    printf("Wrapped main\n");
    return __real_main(argc, argv);
}

int main(int argc, char* argv[])
{
    printf("Main\n");
    return 0;
}

A good addition to the "LD_PRELOAD" trick with shared libraries.