c - 在 glibc 上覆盖 pthread 函数但不在 musl 上时出现神秘的段错误



我正在尝试覆盖pthread_createpthread_exit。覆盖应调用原始项。

我可以覆盖pthread_create,只要我用pthread_exit(0);退出我的主线程,它似乎就可以工作。如果我不这样做,它就会出现段错误。

如果我甚至尝试覆盖pthread_exit,我会得到段错误。

我的设置如下:

#!/bin/sh
cat > test.c <<EOF
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void *thr(void *Arg)
{
printf("i=%dn", (int)(intptr_t)Arg);
return 0;
}
int main()
{
putchar('n');
pthread_t tids[4];
for(int i=0; i < sizeof tids / sizeof tids[0]; i++){
pthread_create(tids+i, 0, thr, (void*)(intptr_t)i);
}
pthread_exit(0); //SEGFAULTS if this isn't here
return 0;
}
EOF
cat > pthread_override.c <<EOF
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <stdio.h>
#if 1
__attribute__((__visibility__("default")))
int pthread_create(
pthread_t *restrict Thr, 
pthread_attr_t const *Attr,
void *(*Fn) (void *), 
void *Arg
)
{
int r;
int (*real_pthread_create)(
pthread_t *restrict Thr, 
pthread_attr_t const *Attr,
void *(*Fn) (void *), 
void *Arg
) = dlsym(RTLD_NEXT, "pthread_create");
printf("CREATE BEGIN: %pn", (void*)Thr);
r = real_pthread_create(Thr, Attr, Fn, Arg);
printf("CREATE END: %pn", (void*)Thr);
return r;
}
#endif
#if 0 
//SEGFAULTS if this is allowed
__attribute__((__visibility__("default")))
_Noreturn
void pthread_exit(void *Retval)
{
__attribute__((__noreturn__)) void (*real_pthread_exit)( void *Arg);
real_pthread_exit = dlsym(RTLD_NEXT, "pthread_exit");
printf("%pn", (void*)real_pthread_exit);
puts("EXIT");
real_pthread_exit(Retval);
}
#endif
EOF
: ${CC:=gcc}
$CC -g -fpic pthread_override.c -shared -o pthread.so -ldl
$CC -g test.c $PWD/pthread.so -ldl -lpthread 
./a.out

谁能向我解释我做错了什么以及段错误的原因是什么?

如果我用 musl-gcc 代替 gcc,问题就会完全消失。

谁能向我解释我做错了什么以及段错误的原因是什么?

这很复杂。

您可能使用的是Linux/x86_64,并且受到此错误的打击。另请参阅此原始报告。

更新:

事实证明,符号版本与问题无关(在x86_64上,没有多个版本的pthread_createpthread_exit)。

问题是gcc配置为将--as-needed传递给链接器。

当您与pthread_exit#ifdefed out 链接时,a.out二进制文件会从libpthread.so.0pthread_exit,该二进制文件被记录为NEEDED共享库:

readelf -d a.out | grep libpthread
0x0000000000000001 (NEEDED)             Shared library: [libpthread.so.0]

当您#ifdefpthread_exit时,不再需要任何真正的libpthread.so.0符号(引用由pthread.so满足):

readelf -d a.out | grep libpthread
# no output!

然后,这会导致dlsym失败(没有下一个符号要返回 --pthread.so定义唯一的符号):

Breakpoint 2, __dlsym (handle=0xffffffffffffffff, name=0x7ffff7bd8881 "pthread_create") at dlsym.c:56
56  dlsym.c: No such file or directory.
(gdb) fin
Run till exit from #0  __dlsym (handle=0xffffffffffffffff, name=0x7ffff7bd8881 "pthread_create") at dlsym.c:56
pthread_create (Thr=0x7fffffffdc80, Attr=0x0, Fn=0x40077d <thr>, Arg=0x0) at pthread_override.c:17
17      int (*real_pthread_create)(
Value returned is $1 = (void *) 0x0

解决方案:在-lpthread之前将-Wl,--no-as-needed添加到主应用程序链接行。

附言我想起了大卫·阿甘斯(David Agans)的书中的规则#3(我强烈推荐):放弃思考和观察

你可以改用-Wl,--wrap=pthread_create进行编译,并通过调用__real_pthread_create()来实现__wrap_pthread_create()

这是做这种插话的更常见的方法。

最新更新