Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does gcc wrap option takes effects on function printf ?

Tags:

c

gcc

ld

I wrote a wrap function to replace the printf of stdio.h. I found that the wrap option worked on functions in stdlib.h, like malloc or exit. But it did not work on printf or fprintf.

Does the option wrap takes effects on functions in stdio.h ? And how can I wrap an arbitrary function ? I cannot get useful guide from the ld document.

Here is the code :

//gcc wrap.c -g -Wl,--wrap,fprintf
int __real_fprintf(FILE *stream, const char *format, ...);

int main(){
    fprintf(stderr, "MAIN!\n"); 
    return 0;
}

int __wrap_fprintf(FILE *stream, const char *format, ...){
    __real_fprintf(stderr, "WRAP!\n");
    return 0;
}
like image 558
wangbo15 Avatar asked Dec 25 '22 02:12

wangbo15


2 Answers

If you want this to work properly for fprintf, you need to also add the flag -fno-builtin-fprintf to the command line. Othwise, gcc will optimize the call to fprintf to instead call fwrite, and the linker will not see a call to fprintf to wrap.

In general, to properly wrap any function, you may need the corresponding -fno-builtin- option as well.

like image 125
Chris Dodd Avatar answered Feb 01 '23 16:02

Chris Dodd


fprintf without arguments (other than the format string) is optimized to fwrite. Change your call of fprintf to fprintf(stderr, "%s\n", "MAIN!"); and the wrapping will take effect.

int __real_fprintf(FILE *stream, const char *format, ...);

int main(){
    fprintf(stderr, "%s\n", "MAIN!"); 
    return 0;
}

int __wrap_fprintf(FILE *stream, const char *format, ...){
    __real_fprintf(stderr, "WRAP!\n");
    return 0;
}
like image 42
Leon Avatar answered Feb 01 '23 17:02

Leon