-Wl,-wrap=symbol对于共享库无效。

6
我尝试使用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调用没有被挂钩。

我做错了什么吗?


这可能只适用于静态库。 - Thomas
似乎是这样。这是我问题的主要方向。 - Frank Meerkötter
1个回答

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
...

我需要一个用于“open”的函数,但__libc_open无法正常工作。 我发现大多数函数,包括malloc,都可以使用两个初始下划线进行调用:int __open(const char *pathname, int flags); - Ramast

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接