Why aren't memory allocations inside libc redirected to my deployment wrappers?

I am trying to provide memory wrappers on CentOS and use the clang compiler / linker. I wrote wrappers for distribution functions (malloc, etc.) and redirected calls using -Wl, -wrap, malloc.

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

However, the problem I see is that any memory allocated in libc is not routed to my shell, but the application makes a free call that gets intercepted (and, as a result, crashes). For instance,

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 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'm doing wrong? Do you need any special compiler / linker flags?

Thanks in advance.

+4
3

glibc malloc ELF:

, , glibc, malloc - , glibc malloc.

__wrap (, , ) , ( glibc) .

+3

glibc (__malloc_hook, __realloc_hook, __free_hook, __memalign_hook) "" ), mallocs glibc: https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

GNU C malloc, realloc free, hook. , , , .

. __malloc_hook glibc

, mallocs, jemalloc, tcmalloc , " / " glibc malloc.

+1

The only way to guarantee compliance with malloc/ freeis to recompile everything, including libc. This is probably not practical for you, so your best way is to somehow track the memory allocated by your shell malloc, and then either respectively free it yourself or call it __real_freein your wrapper freedepending on how the memory was allocated.

0
source

Source: https://habr.com/ru/post/1694945/


All Articles