I want to override memory allocations in my program on Mac OS 10.9 using DYLD_INSERT_LIBRARIES. This is a very simple skeleton of the code I have implemented:
void *(*default_malloc)(size_t) = NULL;
void (*default_free)() = NULL;
void *(*default_calloc)(size_t, size_t) = NULL;
void *(*default_realloc)(void *, size_t) = NULL;
void *malloc(size_t size)
{
if(!default_malloc)
{
default_malloc = dlsym(RTLD_NEXT, "malloc");
}
size_t allocSize = size + 16;
char *mem = (char *)default_malloc(allocSize);
malloc_printf("malloc returned %p\n", mem + 16);
return mem + 16;
}
void *calloc(size_t num, size_t size)
{
if(!default_calloc)
{
default_calloc = dlsym(RTLD_NEXT, "calloc");
}
void *p = malloc(num*size);
memset(p, 0, num*size);
malloc_printf("calloc function returned %p\n", p);
return p;
}
void *realloc(void *xp, size_t size)
{
if(!default_realloc)
{
default_realloc = dlsym(RTLD_NEXT, "realloc");
}
char *p = (char *)default_realloc((char *)xp - 16, size + 16);
malloc_printf("realloc function returned %p\n", p + 16);
return p + 16;
}
void free(void *buff)
{
if(buff == NULL)
return;
if(!default_free)
{
default_free = dlsym(RTLD_NEXT, "free");
}
char *mem = buff;
malloc_printf("free function called for %p\n", mem);
default_free(mem - 16);
}
I am not sure what is wrong here. When I run my program with it, I get the following output:
$ DYLD_INSERT_LIBRARIES=lib_overrides.dylib ls
ls(2431) malloc: malloc returned 0x7fa6b0400030
ls(2431) malloc: malloc returned 0x7fa6b04000a0
ls(2431) malloc: malloc returned 0x7fa6b0400110
ls(2431) malloc: malloc returned 0x7fa6b0400130
ls(2431) malloc: free function called for 0x7fa6b04000a0
ls(2431) malloc: malloc returned 0x7fa6b04000a0
ls(2431) malloc: malloc returned 0x7fa6b04003c0
ls(2431) malloc: free function called for 0x7fa6b04003e0
ls(2431) malloc: *** error for object 0x7fa6b04003e0: pointer being freed was not allocated
How did free
get the pointer 0x7fa6b04003e0
? It is not returned by malloc
anywhere as the logs suggest. I have reviewed the code many times but unable to locate the problem. Any help is much appreciated.
Kindly help.
NOTE: If I stop adding 16 from allocations functions and subtracting 16 from free, then everything works fine. So does it mean that there is some other allocation function which is not overridden here(apart from malloc/calloc/realloc)?