UD NightWish UD NightWish - 3 months ago 23
C Question

Does gcc wrap option takes effects on function printf ?

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;
}

Answer

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.

Comments