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
Comments:

[Trackback] Solaris TCP Latency for HPC This is important for software like memcached, too. Interposing on malloc How to write your own interposer library

Posted by c0t0d0s0.org on February 08, 2008 at 07:23 PM PST #

Post a Comment:
Comments are closed for this entry.
About

Darryl Gove is a senior engineer in the Solaris Studio team, working on optimising applications and benchmarks for current and future processors. He is also the author of the books:
Multicore Application Programming
Solaris Application Programming
The Developer's Edge
Free Download

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today
Bookmarks
The Developer's Edge
Solaris Application Programming
Publications
Webcasts
Presentations
OpenSPARC Book
Multicore Application Programming
Docs