c - -Wl,-wrap=symbol 不适用于共享库

标签 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 调用未 Hook 。

我做错了什么吗?

最佳答案

您的解决方案不适用于共享库。

但是你可以这样做:

将以下代码放入名为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.c:gcc 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
...

关于c - -Wl,-wrap=symbol 不适用于共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615123/

相关文章:

linux - 如何在centos 6上退出linux sendmail

c - gcc 预处理器输出中以哈希符号和数字(如 '# 1 "a.c"')开头的行的含义是什么?

c - 在项目中期切换到 Jenkins 时,如何为旧标签构建工件?

c - 正值和负值的不同输出

linux - GitHub SSH 访问无效

使用 MATLAB 引擎和 g++ 的 C++ 源代码编译

c++ - GCC:独立 C++ 应用程序中符号的可见性

c - 当内循环索引不等于外循环索引时的嵌套循环

c++ - _asm 在 C 代码中不起作用,如何启用它

c - 调用fork()然后变成调用sys_fork()的过程是怎样的?