Search code examples
cmallocclangglibc

Why are Memory allocations within libc are not routed to my allocation wrappers?


I am trying to provide memory wrappers on CentOS and using clang compiler/linker. I wrote wrappers for the allocation functions (malloc et al) and rerouted the calls using -Wl,-wrap,malloc.

This all works fine and I can see it in action. void* mem = malloc(10); // routes to __wrap_malloc free(mem);// routes to __wrap_free

However, the problem I am seeing is that any memory allocated within libc is not being routed to my wrapper but the application is making the free call that gets intercepted (and crash as a result). For example,

char* newStr = strdup("foo"); // The internal malloc in libcdoes not come to wrapper free(newStr); // The free call makes it to the wrapper

My program is in C++. I created a mallocimpl.cpp and did something like

extern "C"{ void* __wrap_malloc(size_t size) { // Route memory via custom memory allocator } //Similarly, __wrap_calloc, __wrap_realloc, __wrap_memalign and __wrap_free

Any ideas what I am doing wrong? Do I need any special compiler/linker flags?

Thanks in advance.


Solution

  • The recommended way to replace the glibc malloc implementation is ELF symbol interposition:

    This way, you do not have to recompile everything, including glibc, and your malloc replacement will still be called once glibc removes the malloc hooks.

    The __wrap approach does not work without recompiling (or at least rewriting) everything because all other libraries (including glibc) will use non-wrapped symbols.