I have a small patch that can be added to a specific application and track the calls of some functions. Among them are malloc () and open (). I use dlsym to keep the pointer to the source character and replace the function name with my own. It compiles and works fine under Linux. Here is the code:
#define _GNU_SOURCE
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <dlfcn.h>
int open(char * filename, int flags)
{
static int (*real_open)(char*, int) = NULL;
if (!real_open)
real_open = dlsym(RTLD_NEXT, "open");
int p = real_open(filename, flags);
fprintf(stderr, "Abrimos %s) = %i\n", filename, flags);
return p;
}
void* malloc(size_t size)
{
static void* (*real_malloc)(size_t) = NULL;
if (!real_malloc)
real_malloc = dlsym(RTLD_NEXT, "malloc");
void *p = real_malloc(size);
fprintf(stderr, "Reserva de memoria (%d) = %p\n", size, p);
return p;
}
Then I will compile it with the following instruction, creating pi.so.
gcc -Wall -O2 -fPIC -shared -ldl -o pi.so pi.c
And then I use the LD_PRELOAD directive to implement it in any application.
LD_PRELOAD=/home/.../injection/pi.so <binary>
And it excites wonderfully under Linux! But when I get home and try to compile it using GCC for Mac, it will not compile and the LD_PRELOAd directive does not work. What should i change? Thank you very much.