Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does wrapping printf with ld fail when there's a newline?

Tags:

c

gcc

linker

ld

I'm trying to intercept calls to printf using ld's -wrap option. I have the two files:

main.c:

#include <stdio.h>

int main(void) {
    printf("printing\n");
    printf("printing");
}

printf_wrapper.c:

int __real_printf(const char *format, ...);

int __wrap_printf(const char *format, ...) {
    (void)format;
    return __real_printf("WRAPPED\n");
}

And I compile with the following command:

gcc -Wl,-wrap,printf *.c

When I run the resulting a.out binary, I get this output:

printing
WRAPPED

Why does the wrapping fail if there's a newline in the string? I checked my system's stdio.h and printf isn't a macro. This is with gcc 5.3.0

like image 963
awelkie Avatar asked Oct 31 '22 08:10

awelkie


1 Answers

Use the -fno-builtin option to tell gcc not to mess around with some specified functions. So, if you added -fno-builtin-printf it should work. In general it may cause some problems that would have been caught by the compiler to be missed. See the gcc docs for details, e.g. https://gcc.gnu.org/onlinedocs/gcc-4.2.2/gcc/C-Dialect-Options.html

like image 50
bruceg Avatar answered Nov 15 '22 06:11

bruceg