【问题标题】:-Wl,-wrap=symbol doesn't work for shared libraries-Wl,-wrap=symbol 不适用于共享库
【发布时间】:2015-02-19 19:25:48
【问题描述】:

我尝试使用 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 调用未挂钩。

我做错了吗?

【问题讨论】:

  • 这可能只适用于静态库。
  • 似乎如此。这是我问题的主要方向。

标签: c linux gcc linker ld


【解决方案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.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
...

【讨论】:

  • 我需要一个 open__libc_open 没有工作。我发现包括 malloc 在内的大多数函数都可以用两个初始下划线 int __open(const char *pathname, int flags); 来调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2013-11-19
相关资源
最近更新 更多