开发者

Issue with malloc wrapper code

I am facing SIGEV with this malloc wrapper code, can anybody please help me?

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 lib开发者_如何学Pythonc.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);
  }

Here is the GDB backtrace:

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

I am not able to find the root cause. Please help me to fix this issue. Please help me.


Looks like loading libc.so at the wrong time is causing the problem. Try without loading it:

dlsym(RTLD_NEXT, "malloc");


The root cause looks to be the use of malloc from within the dlopen call in your init1 function. At the time of the dlopen, the ef_libc_malloc variable is null, which is triggering the SIGSEGV as the dlopen uses your local malloc routine rather than the one in libc.


According to your stack trace dlopen (which you call during the initialization) internally calls malloc at some stage. Here your implementation of the malloc is called, which in turns calls ef_libc_malloc. But it's not initialized yet! It's NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜