You can wrap around the original malloc.
static void* (*r_malloc)(size_t) = NULL;
void initialize() {
r_malloc = dlsym(RTLD_NEXT, "malloc");
}
void* malloc(size_t size) {
//Do whatever you want
return r_malloc(bsize);
}
But don't forget you must also wrap around calloc and realloc probably. And there are also less commonly used functions in the libc to allocate memory.
To wrap calloc you need to do a dirty hack because dlsym tries to allocate memory using calloc but doesn't really need it.
static void* __temporary_calloc(size_t x __attribute__((unused)), size_t y __attribute__((unused))) {
return NULL;
}
static void* (*r_calloc)(size_t,size_t) = NULL;
and in the init function add this:
r_calloc = __temporary_calloc;
r_calloc = dlsym(RTLD_NEXT, "calloc");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…