【问题标题】:Linker error with intercepting function calls in GCC在 GCC 中拦截函数调用的链接器错误
【发布时间】:2018-04-30 19:38:23
【问题描述】:

我正在使用标准的__wrap_function__real_function 来拦截-Wl,--wrap=function 的函数调用。这适用于大多数函数,如mallocfopen 等。但是,我无法包装这两个函数:

  1. int connect(int, const struct sockaddr*, socklen_t)
  2. int stat(const char*, struct stat*)

使用这些函数,链接器会抱怨对 __real_connect__real_stat 的未定义引用。

这有什么特别的原因吗? (注:例如,我也可以包装socket 函数)

【问题讨论】:

  • 您使用的是哪个操作系统和 C 库?
  • 了解您使用的 C 编译器和 libc 会很有帮助。鉴于您的个人资料图片和这些选项的性质,假设 gcc 和 glibc 是相当安全的,但最好明确指定。
  • 我卡在 GCC 4.4.7 和 glibc 2.12,Linux 内核 2.6.32

标签: c gcc linker-errors ld undefined-reference


【解决方案1】:

您可能忘记在链接行中添加-Wl,--wrap=connect-Wl,--wrap=stat

这对我有用:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>

int __wrap_connect (int s, const struct sockaddr *addr, socklen_t len)
{
    puts(__func__);
    return __real_connect(s, addr, len);
}

int __wrap_stat (const char *path, struct stat *buf)
{
    puts(__func__);
    return __real_stat(path, buf);
}

int main(void) {
    connect(0, NULL, 0);
    stat("/", 0);
    return 0;
}

在我的系统上编译时。

$ uname -s -r
Linux 2.6.32-696.16.1.el6.x86_64
$ gcc --version | grep gcc
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-18)
$ gcc c.c -Wl,--wrap=connect -Wl,--wrap=stat
$

但是,例如,当离开 -Wl,--wrap=stat 时,我得到:

$ gcc c.c -Wl,--wrap=connect
/tmp/cchVzvsE.o: In function `__wrap_stat':
c.c:(.text+0x65): undefined reference to `__real_stat'
collect2: ld returned 1 exit status
$

【讨论】:

  • 这似乎与我的 cmake 文件有关。清除缓存并运行 cmake 。然后make解决了这个问题!但在核心,是的,如果我错过了链接器行,那将是一个未定义的引用!感谢您的帮助。
  • @a_pradhan:由于我的回答并没有真正解决您的问题,您应该继续使用您的问题的具体情况更新您的问题。然后,编写一个答案来解决您更新的问题中提出的具体问题。这将增加您的问题和答案与未来读者的相关性。我将留下我的答案只是为了提供更多信息(我已经将其作为社区 wiki 答案,因为我没有任何信心它会解决您的具体问题)。
【解决方案2】:

似乎错误是由于 cmake 问题引起的。清除 cmake 缓存并运行 cmake 。然后 make all 解决它。

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多