2011-08-03 53 views
1

我正面臨SIGEV與此malloc包裝代碼,任何人都可以請幫我嗎?malloc包裝代碼問題

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 [email protected]@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 

我無法找到問題的根源。請幫我解決這個問題。 請幫幫我。

回答

1

看起來像在不正確的時間加載libc.so導致了問題。嘗試不加載它:

dlsym(RTLD_NEXT, "malloc"); 
+0

謝謝!確切地說,我只是試過這個,它的工作。 – kingsmasher1

1

根本原因看起來是在init1函數的dlopen調用中使用malloc。在dlopen時,ef_libc_malloc變量爲空,它觸發SIGSEGV,因爲dlopen使用本地malloc例程而不是libc中的那個例程。

+0

如何解決它? – kingsmasher1

1

根據您的堆棧跟蹤dlopen(您在初始化過程中調用)在某個階段內部調用malloc。在這裏調用malloc,然後調用ef_libc_malloc。但它尚未初始化!這是NULL

+0

如何解決? – kingsmasher1