views:

254

answers:

1

Hi Experts,

I was hacking printf() of glibc in one of my project and encountered some problem. Could you please give some clues? And one of my concern is why the same solution for malloc/free works perfect!

As attached, “PrintfHank.c” contains my own solution of printf() which will be preloaded before standard library; and “main.c” just outputs a sentence using printf(). After editing two files, I issued following commands:

  1. compile main.c gcc –Wall –o main main.c
  2. create my own library gcc –Wall –fPIC –shared –o PrintfHank.so PrintfHank.c –ldl
  3. test the new library LD_PRELOAD=”$mypath/PrintfHank.so” $mypath/main

But I received “hello world” instead of “within my own printf” in the console. When hacking malloc/free functions, it’s okay.

I log in my system as “root” and am using 2.6.23.1-42.fc8-i686. Any comments will be highly appreciated!!

main.c

#include <stdio.h>

int main(void)
{
    printf("hello world\n");

    return 0;
}

PrintfHank.c

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <dlfcn.h>

static int (*orig_printf)(const char *format, ...) = NULL;

int printf(const char *format, ...)
{
 if (orig_printf == NULL)
 {
  orig_printf = (int (*)(const char *format, ...))dlsym(RTLD_NEXT, "printf");
 }

 // TODO: print desired message from caller. 
 return orig_printf("within my own printf\n");
}
A: 

Check 1) preprocessor output. printf can be changed to smth else

gcc -E main.c

2) ld_debug info about printf symbol and preloading

LD_DEBUG=help LD_PRELOAD=”$mypath/PrintfHank.so” $mypath/main
LD_DEBUG=all LD_PRELOAD=”$mypath/PrintfHank.so” $mypath/main
osgx