-Wl,-wrap =符号不适用于共享库

Fra*_*ter 6 c linux linker gcc 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);
}
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我看到包装程序被要求直接从我的应用程序完成的malloc调用。不会钩住在共享库之一中完成的malloc调用。

难道我做错了什么?

Tho*_*mas 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);
}
Run Code Online (Sandbox Code Playgroud)

编译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
...
Run Code Online (Sandbox Code Playgroud)