title: How to hook without using dlsym in linux
body: <p>I'm trying to hook some functions of glibc, like fopen, fread etc. But in the hook function, i have to use the same function as in glibc. Like this:</p>
  
  <pre><code>// this is my fopen
  FILE *fopen(.....)
  {
      fopen(....);// this is glibc fopen
  }
  </code></pre>
  
  <p>I have found one way to do this using dlsym, but in this way i have to replace all the glibc function calls with wrappers inside which call glibc function using dlsym.
  I'm curious whether where is another way to do the same job without coding wrapper functions. I ever tryed this :</p>
  
  <p>fopen.c</p>
  
  <pre><code>....fopen(..)
  {
    myfopen(..);
  }
  </code></pre>
  
  <p>myfopen.c</p>
  
  <pre><code>myfopen(..)
  {
    fopen(...);// glibc version
  }
  </code></pre>
  
  <p>main.c</p>
  
  <pre><code>int main()
  {
    fopen(...);
  }
  
  $ gcc -c *.c
  $ gcc -shared -o libmyopen.so myopen.o
  $ gcc -o test main.o fopen.o libmyopen.so
  </code></pre>
  
  <p>In my understanding, gcc will link from left to right as specified in the command line, so main.o will use fopen in fopen.o, fopen.o will use myfopen in libmyfopen.so, libmyfopen.so will use fopen in glibc. But when running, i got a segment fault, gdb shows there is a recusive call of fopen and myfopen. I'm a little confused. Can anyone explain why ?</p>