2

I am trying to hook printf function in c and implement a very similar function only that it prints to stderr stream.

printf code:

int printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

I changed stdout to stderr but when running with > /dev/null (which redirects stdout to null) I still don't see the output. When running ltrace I can see it calls puts instead of printf, I think this is the problem.

3
  • 2
    If you are calling printf with a string literal then the compiler optmises it out to puts() call. Try with something that requires format string parsing (e.g. int x=5; printf("%d\n", x*x);. You still call vfprintf with stdout? Have you verified your preloaded library is actually loaded (try with simple write(1, "hi", 2); in your hook)?
    – P.P
    Jul 27, 2016 at 11:30
  • Is it okay to redirect everything from stdout to stderr? If so and if you are using bash, just write myprog arg1 arg2 argN 1>&2. That last 1>&2 part will redirect stdout to stderr. See this. Jul 27, 2016 at 12:27
  • Why not just fprintf(stderr, ....)? Trying to write a replacement function for a library function is not always as simple as just writing a same-named function...
    – twalberg
    Jul 27, 2016 at 19:47

2 Answers 2

1

According to ISO/IEC 9899:201x redefining an reserved identifier like printf results in undefined behaviour:

7.1.3.2 ... If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

So like P.P. pointed out it is totally legal for the compiler to optimize certain calls to printf by replacing them with puts because the observable behaviour is the same if printf is not redefined and UB rules (meaning anything can happen) apply if you redefine it.

0

so I figured it out.. the code above was fine, the preload was fine, and as I said for some reason puts was called instead of printf. The simple Hello World program that demonstrated LD_PRELOAD looked like this:

printf("Hello World\n");

when I removed the \n it worked fine, and puts was not called! more about this issue can be found here: Problems on injecting into printf using LD_PRELOAD method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.