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;
}
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With