我正在使用这个malloc包装器代码面对SIGEV,有人可以帮助我吗?
enter code here
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
void *handle;
static void* (*ef_libc_malloc) (size_t);
static void* (*ef_libc_calloc) (size_t, size_t);
static void init1() __attribute__ ((constructor));
void *malloc(size_t size)
{
return (*ef_libc_malloc)(size);
}
void *calloc(size_t nmemb, size_t size)
{
return (*ef_libc_calloc)(nmemb, size);
}
void init1()
{
//handle=dlopen("/devel/lib/libc.so.6",RTLD_LAZY);
handle=dlopen("libc.so.6",RTLD_LAZY);
if(!handle) {
printf("dlopen failed\n");
exit(1);
}
ef_libc_malloc = dlsym(handle, "malloc");
if(!ef_libc_malloc) {
printf("Could not resolve malloc in libc.so\n");
}
ef_libc_calloc = dlsym(handle, "calloc");
if(!ef_libc_calloc) {
printf("Could not resolve calloc in libc.so\n");
}
}
int main()
{
char *ptr;
ptr=(char*)malloc(20);
strcpy(ptr,"jghjghbj");
puts(ptr);
}
以下是GDB回溯:
enter code here
(gdb) r
Starting program: /usr/local/arm-sony-linux-gnueabi/target/arm/tmp/efence/a.out
Program received signal SIGSEGV, Segmentation fault.
0x00000000 in ?? ()
(gdb) bt
#0 0x00000000 in ?? ()
#1 0x080484c8 in malloc (size=20) at dlopen10.c:13
#2 0x0067cb42 in _dl_map_object_deps () from /lib/ld-linux.so.2
#3 0x00681aed in dl_open_worker () from /lib/ld-linux.so.2
#4 0x0067de26 in _dl_catch_error () from /lib/ld-linux.so.2
#5 0x00681472 in _dl_open () from /lib/ld-linux.so.2
#6 0x00803c4d in dlopen_doit () from /lib/libdl.so.2
#7 0x0067de26 in _dl_catch_error () from /lib/ld-linux.so.2
#8 0x008042cc in _dlerror_run () from /lib/libdl.so.2
#9 0x00803b84 in dlopen@@GLIBC_2.1 () from /lib/libdl.so.2
#10 0x08048501 in init1 () at dlopen10.c:25
#11 0x0804866b in __do_global_ctors_aux ()
#12 0x0804836d in _init ()
#13 0x080485f9 in __libc_csu_init ()
#14 0x006a8e41 in __libc_start_main () from /lib/libc.so.6
#15 0x08048401 in _start ()
(gdb) q
The program is running. Exit anyway? (y or n) y
我无法找到根本原因。请帮我解决这个问题。 请帮帮我。
答案 0 :(得分:1)
根本原因似乎是在init1函数的dlopen调用中使用malloc。在dlopen时,ef_libc_malloc变量为null,它触发SIGSEGV,因为dlopen使用本地malloc例程而不是libc中的例程。
答案 1 :(得分:1)
根据您的堆栈跟踪dlopen
(在初始化期间调用),在某个阶段内部调用malloc
。在这里调用malloc
的实现,然后调用ef_libc_malloc
。但它尚未初始化!它是NULL
。
答案 2 :(得分:1)
看起来在错误的时间加载libc.so会导致问题。尝试不加载它:
dlsym(RTLD_NEXT, "malloc");