title: Ansi C patch using dlsym compiles OK under linux but fails on Mac Os X
body: <p>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:</p>
  
  <pre><code>#define _GNU_SOURCE
  #include &lt;stdint.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdarg.h&gt;
  #include &lt;dlfcn.h&gt;
  
  /**
   * 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;
  }
  </code></pre>
  
  <p>Then, I compile it with the following instruction, creating a pi.so.</p>
  
  <pre><code>gcc -Wall -O2 -fPIC -shared -ldl -o pi.so pi.c 
  </code></pre>
  
  <p>And then, I use the LD_PRELOAD directive to inject it into any app.</p>
  
  <pre><code>LD_PRELOAD=/home/.../injection/pi.so &lt;binary&gt;
  </code></pre>
  
  <p>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.</p>