Hi ;-)
I have build a little patch to append to a certain application and trace the invocations of some functions. Among them, malloc() and open(). I am using dlsym to store the pointer to the original symbol and replace the function name with my own. It compiles -and works- perfectly under linux. Here's the code:
#define _GNU_SOURCE
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <dlfcn.h>
/**
* Interponemos nuestra funcion open
*
* @param char* filename
* @param int flags
**/
int open(char * filename, int flags)
{
static int (*real_open)(char*, int) = NULL;
if (!real_open)
real_open = dlsym(RTLD_NEXT, "open");
// Entero
int p = real_open(filename, flags);
fprintf(stderr, "Abrimos %s) = %i\n", filename, flags);
// Devolvemos
return p;
}
//--------------------------------------------------------
/**
* Interponemos nuestra funcion malloc
*
* @param size_t size
*/
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);
// Memoria reservada
fprintf(stderr, "Reserva de memoria (%d) = %p\n", size, p);
// Devolvemos
return p;
}
Then, I compile it with the following instruction, creating a pi.so.
gcc -Wall -O2 -fPIC -shared -ldl -o pi.so pi.c
And then, I use the LD_PRELOAD directive to inject it into any app.
LD_PRELOAD=/home/.../injection/pi.so <binary>
And it worjks marvellous under Linux! But when I get back home and try to compile it using GCC under Mac, it fails to compile and the LD_PRELOAd directive does not work. What should I change? Thank you very much.