-Wl,-wrap = symbol对共享库不起作用

时间:2015-02-19 19:25:49

标签: c linux gcc linker ld

我尝试使用GNU链接器功能“-wrap = symbol”来拦截大型应用程序对malloc()的所有调用。该应用程序正在使用一大堆共享库。

链接器阶段如下所示:

g++ -Wl,-wrap=malloc -o samegame .obj/main.o .obj/qrc_samegame.o -lQt5Quick -lQt5Qml -lQt5Network -lQt5Gui -lQt5Core -lGL -lpthread

我的包装看起来像这样:

extern "C" {
void *
__real_malloc(size_t c);

void *
__wrap_malloc(size_t c)
{
    printf("my wrapper");
    return __real_malloc (c);
}
}

我的问题是我看到我的包装器被调用直接从我的应用程序完成的malloc调用。在其中一个共享库中完成的malloc调用没有被挂钩。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的解决方案无法使用共享库。

但你可以这样做:

将以下代码放在名为malloc.c

的文件中
#include <stdlib.h>
#include <stdio.h>

void *__libc_malloc(size_t size);

void *malloc(size_t size)
{
    printf("malloc'ing %zu bytes\n", size);
    return __libc_malloc(size);
}

汇编malloc.cgcc malloc.c -shared -fPIC -o malloc.so

然后运行:

$ LD_PRELOAD='./malloc.so' ls

malloc'ing 568 bytes
malloc'ing 120 bytes
malloc'ing 5 bytes
malloc'ing 120 bytes
malloc'ing 12 bytes
malloc'ing 776 bytes
malloc'ing 112 bytes
malloc'ing 952 bytes
malloc'ing 216 bytes
malloc'ing 432 bytes
malloc'ing 104 bytes
malloc'ing 88 bytes
malloc'ing 120 bytes
malloc'ing 168 bytes
malloc'ing 104 bytes
malloc'ing 80 bytes
malloc'ing 192 bytes
...
相关问题