Darryl Gove's blog
Interposing on malloc
Ended up wanting to look at malloc calls, how much was requested, where the memory was located, and where in the program the request was made. This was on S9, so no dtrace, so the obvious thing to do was to write an interpose library and use that. The code is pretty simple:
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <ucontext.h>
void * malloc(size_t size)
{
static void* (*func)(size_t)=0;
void* ret;
if (!func) {func=(void*(*)(size_t))dlsym(RTLD_NEXT,"malloc");}
ret=func(size);
printf("size = %i address=%x\n",size,ret);
printstack(0);
return ret;
}
The code uses a call to printstack to print out the stack at the point of the call.
The code is compiled and run with:
$ cc -O -G -Kpic -o libmallinter.so mallinter.c $ LD_PRELOAD=./libmallinter.so ls size = 17 address=25118 /home/libmallinter.so:malloc+0x5c /usr/lib/libc.so.1:_strdup+0xc /usr/lib/libc.so.1:0x73b54 /usr/lib/libc.so.1:0x72d44 /usr/lib/libc.so.1:0x720e4 /usr/lib/libc.so.1:setlocale+0x3c /usr/bin/ls:main+0x14 /usr/bin/ls:_start+0x108 size = 17 address=25138 /home/libmallinter.so:malloc+0x5c /usr/lib/libc.so.1:_strdup+0xc /usr/lib/libc.so.1:0x73b54 /usr/lib/libc.so.1:0x72d44 /usr/lib/libc.so.1:0x720e4 /usr/lib/libc.so.1:setlocale+0x3c /usr/bin/ls:main+0x14 /usr/bin/ls:_start+0x108
Posted at 01:07PM Feb 08, 2008 by Darryl Gove in Sun | Comments[1]

Posted by c0t0d0s0.org on February 09, 2008 at 03:23 AM PST #