0

How to write a shared library that:

  • wraps a system function (say malloc),
  • internally uses the real version of wrapped functions (e.g., malloc defined in libc), AND
  • can be linked from client code without giving --wrap=malloc every time it is used?

I learned from several posts that I can wrap system functions with --wrap option of ld; something like this:

void * __wrap_malloc(size_t sz) {
  return __real_malloc(sz);
}

and get a shared library with:

gcc -O0 -g -Wl,--wrap=malloc -shared -fPIC m.c -o libwrapmalloc.so

But when a client code links this library, it needs to pass --wrap=malloc every time. I want to hide this from the client code, as the library I am working on actually wraps tons of system functions.

An approach I was using was to define malloc and find the real malloc in libc using dlopen and dlsym. This was nearly what I needed, but just as someone posted before Function interposition in Linux without dlsym, dlsym and dlopen internally call mem-alloc functions (calloc, as I witnessed it) so we cannot easily override calloc/malloc functions with this approach.

I recently learned --wrap and thought it was neat, but I just do not want to ask clients to give tons of --wrap=xxxx arguments every time they get executables...

I want to have a situation in which malloc in the client code calls malloc defined in my shared library whereas malloc in my shared library calls malloc in libc.

If this is impossible, I would like to reduce the burden of the clients to give lots of --wrap=... arguments correctly.

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Forget all these 'wraps'; write your malloc/free/etc functions; load the standard functions from `libc.so.6` via dlopen+dlsym, and call them. – Lorinczy Zsigmond Sep 01 '16 at 15:03
  • @LorinczyZsigmond, thanks, but as I wrote in my original post, this approach has a trouble in wrapping functions used by dlopen/dlsym (I witnessed calloc is one). Thank you for a suggestion anyway. – Kenjiro Taura Sep 02 '16 at 00:35
  • Well, it is not trivial, but it can be done. Here I my example: http://web.axelero.hu/lzsiga/memtrace.c – Lorinczy Zsigmond Sep 02 '16 at 03:50

0 Answers0