2017-02-20 87 views
0

我正在使用LD_PRELOAD从应用程序中记录malloc调用并映射出虚拟地址空间,但malloc在fopen/printf内部使用。有没有办法解决这个问题?使用LD_PRELOAD修复malloc的递归调用

我知道glibc的钩子,但我想避免更改应用程序的源代码。

+0

http://stackoverflow.com/questions/7811656/ld-preload-only-working-for-malloc-not-free? –

+1

请定义您遇到的问题。说明没有说关于递归的任何事情。 – yugr

回答

0

我的问题是由malloc的是由glibc的内部使用造成的事实,所以当我用LD_PRELOAD覆盖malloc的任何尝试登录引起的malloc被称为导致递归调用malloc的本身

解决方案: 调用每当TLS需要的内存分配 提供的代码原有的malloc:

static __thread int no_hook; 
static void *(*real_malloc)(size_t) = NULL; 
static void __attribute__((constructor))init(void) { 
    real_malloc = (void * (*)(size_t))dlsym(RTLD_NEXT, "malloc"); 
} 

void * malloc(size_t len) { 
    void* ret; 
    void* caller; 

    if (no_hook) { 
     return (*real_malloc)(len); 
    } 

    no_hook = 1; 
    caller = (void*)(long) __builtin_return_address(0); 
    printf("malloc call %zu from %lu\n", len, (long)caller); 
    ret = (*real_malloc)(len); 
    // fprintf(logfp, ") -> %pn", ret); 
    no_hook = 0; 
    return ret; 
} 

+0

来源:http://www.slideshare.net/tetsu.koba/tips-of-malloc-free – bnm