Can someone explain me the working of a malloc wrapper for below code??
RTLD_NEXT should find the next syblo in search order, which means it should hit my malloc, where i haven't put any allocation scheme like original malloc.
Then how come the allocation is taking place?
I have done something like this in my code:
enter code here: tracer.cc
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
static void* (*lt_malloc)(size_t size);
#define LT_MALLOC (*lt_malloc)
void *malloc(size_t sz)
{
printf("My malloc called开发者_JAVA百科");
return LT_MALLOC(sz);
}
int main()
{
if (!lt_malloc)
{
lt_malloc = (void*(*)(size_t))dlsym(RTLD_NEXT, "malloc");
if (!lt_malloc)
{
fprintf(stderr, "LeakTracer: could not resolve 'malloc' in 'libc.so': %s\n", dlerror());
exit(1);
}
}
int *p=(int*)malloc(10);
*p=34;
printf("Address of p: %u, value: %d\n",p,*p);
p=(int*)malloc(10);
*p=45;
printf("Address of p: %u, value: %d\n",p,*p); */
}
Check the GDB output, nowhere it goes to libc malloc. Then from where is the memory allocation taking place?
enter code here
Breakpoint 1 at 0x804855d: file malloc1.c, line 25.
(gdb) s
The program is not being run.
(gdb) r
Starting program: /home/raj/timer_test/malloc_wrapper/a.out
Breakpoint 1, main () at malloc1.c:25
25 int *p=(int*)malloc(20);
(gdb) s
malloc (sz=20) at malloc1.c:10
10 printf("My malloc called");
(gdb) s
11 return LT_MALLOC(sz);
(gdb) s
12 }
(gdb) s
main () at malloc1.c:26
26 *p=45;
(gdb) s
27 printf("Address of p: %u, value: %d\n",p,*p);
(gdb) s
My malloc calledAddress of p: 146501640, value: 45
29 p=(int*)malloc(20);
(gdb) s
malloc (sz=20) at malloc1.c:10
10 printf("My malloc called");
(gdb) s
11 return LT_MALLOC(sz);
(gdb) s
12 }
(gdb) s
main () at malloc1.c:30
30 *p=56;
(gdb) s
31 printf("Address of p: %u, value: %d\n",p,*p);
(gdb) s
My malloc calledAddress of p: 146501664, value: 56
32 }
(gdb) s
0x006a8e9c in __libc_start_main () from /lib/libc.so.6
(gdb) s
Single stepping until exit from function __libc_start_main,
which has no line number information.
Program exited with code 043.
(gdb)
My confusion, is in which step and how the libc original malloc is called? And why can't the GDB trace it?
One more question, suppose after certain time (may be timer expiry) i want to call original malloc and not mine. How to do that?
I might be wrong, but I think that what is going on is that with the dlsym() call you are getting the address to the malloc in the libc, so your malloc function is acting as a wrapper around the libc malloc [but with the same name] You say:
"which means it should hit my malloc"
but are you sure the symbol for your malloc is the second one? ;) It might be it is the first one, as your malloc is in the same compilation unit.
精彩评论