I try to use the GNU linker feature "-wrap=symbol" to intercept all calls to malloc() done by a large application. The application is making use of a whole bunch of shared libraries.
The linker stage looks like this:
g++ -Wl,-wrap=malloc -o samegame .obj/main.o .obj/qrc_samegame.o -lQt5Quick -lQt5Qml -lQt5Network -lQt5Gui -lQt5Core -lGL -lpthread
My wrappers look like this:
extern "C" {
void *
__real_malloc(size_t c);
void *
__wrap_malloc(size_t c)
{
printf("my wrapper");
return __real_malloc (c);
}
}
My problem is that I see my wrapper being called for malloc invocations done directly from my application. malloc invocations done in one of the shared libraries aren't hooked.
Am I doing something wrong?
Your solution won't work with shared libraries.
But you can do something like this:
Put the following code in a file called malloc.c
#include <stdlib.h>
#include <stdio.h>
void *__libc_malloc(size_t size);
void *malloc(size_t size)
{
printf("malloc'ing %zu bytes\n", size);
return __libc_malloc(size);
}
Compile malloc.c
: gcc malloc.c -shared -fPIC -o malloc.so
Then run:
$ LD_PRELOAD='./malloc.so' ls
malloc'ing 568 bytes
malloc'ing 120 bytes
malloc'ing 5 bytes
malloc'ing 120 bytes
malloc'ing 12 bytes
malloc'ing 776 bytes
malloc'ing 112 bytes
malloc'ing 952 bytes
malloc'ing 216 bytes
malloc'ing 432 bytes
malloc'ing 104 bytes
malloc'ing 88 bytes
malloc'ing 120 bytes
malloc'ing 168 bytes
malloc'ing 104 bytes
malloc'ing 80 bytes
malloc'ing 192 bytes
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With