使用 gcc wrap 选项时出现段错误

segfaulting while playing with gcc wrap option

你好,谁能告诉我这是怎么回事?

#include <stdlib.h>

void __wrap_exit(int code)
{
    return;
}

int main(int argc, char *argv[])
{
    exit(5);
    return 0;
}

编译:gcc main.c -g -Wl,--wrap=exit

我尝试调试程序并打印出:

Program  received signal    SIGSEGV, Segmentation fault.
0x00007fffffffde88 in ?? ()
(gdb) n
Cannot find bounds of current function

之前我用 open() 尝试过类似的实验并且效果很好。 为了避免围绕 exit() 进行一些有趣的编译器优化,我尝试使用 -O0 进行编译,但它似乎没有任何效果。

谢谢。

伙计们,我花了很长时间才发现发生了什么。

我的看法是,有时候 gcc 在不需要的时候太聪明了。在这种情况下,它将 exit 作为 builtin 处理,而不是将其视为普通 C 函数。

这是我的 test.c:

extern void exit(int code);

void __wrap_exit(int code)
{
    return;
}

int main(int argc, char *argv[])
{
    exit(5);
    return 0;
}

结果如下:

$ gcc -fno-builtin -otest test.c -Wl,--wrap=exit
$ ./test; echo $?
0
$ gcc -fno-builtin -otest test.c
$ ./test; echo $?
5