我正在尝试覆盖pthread_create
and pthread_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=%d\n", (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: %p\n", (void*)Thr);
r = real_pthread_create(Thr, Attr, Fn, Arg);
printf("CREATE END: %p\n", (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("%p\n", (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,问题就完全消失了。