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.

3 comments:

Anonymous said...

Thanks for this post.
I am having trouble getting clang to accept -wrap. Have you tried this with the latest version of clang?

Anonymous said...

clang.exe: warning: -Wl,-wrap,xxx: 'linker' input unused

Anonymous said...

#include

int __real_temp();

int __wrap_temp()
{
printf("Wrapped temp\n");
return __real_temp();
}
int __real_main();

int __wrap_main()
{
printf("Wrapped main\n");
return __real_main();
}

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

int main()
{
temp();
return 0;
}

I am trying to wrap temp function but it is not working please give some suggestions thank you