title: Dynamically loading Linux shared libraries?
body: <p>I want to create a shared library which can be loaded in two different ways into targets:</p>
  
  <ol>
  <li>LD_PRELOAD</li>
  <li>Dynamic loading via <code>dlsym</code></li>
  </ol>
  
  <p>My shared library looks like this:</p>
  
  <pre><code>#include "stdio.h"
  
  void __attribute__ ((constructor)) my_load(void);
  
  void my_load(void) {
    printf("asdf");
  }
  
  void someFunc(void) {
    printf("someFunc called");
  }
  </code></pre>
  
  <p>I am compiling it like so:</p>
  
  <pre><code>all:
      gcc -fPIC -g -c -Wall MyLib.c
      gcc -shared -W1,-soname,MyLib.so.1 -o MyLib.so.1.0.1 -lc
  </code></pre>
  
  <p>I do not wish to install it with <code>ldconfig</code>, etc. The target process looks like this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;dlfcn.h&gt;
  
  void func1() {
    printf("%d\n", 1);
  }
  
  void func2() {
    printf("%d\n", 2);
  }
  
  void func3() {
    printf("%d\n", 3);
  }
  
  int main() {
    void* lib_handle = dlopen("/home/mike/Desktop/TargetProcess/MyLib.so.1.0.1",
                           RTLD_NOW|RTLD_GLOBAL);
  
    if(lib_handle == NULL) {
      printf("Failed loading lib\n");
    } else {
      printf("Loaded lib successfully\n");
  
      void (*some_func)() = dlsym(lib_handle, "someFunc");
      printf("%p\n", some_func);
  
      dlclose(lib_handle);
    }
  
    func1();
    func2();
    func3();
  
    return 0;
  }
  </code></pre>
  
  <p>The target is compiled as so:</p>
  
  <pre><code>all:
      gcc TestProg.c -ldl -o TestProg
  </code></pre>
  
  <p>My questions are:</p>
  
  <ol>
  <li>With the dynamic loading with <code>dlopen</code> as above, why does <code>my_load</code> not appear to be called?</li>
  <li>With the same method, why does <code>dlsym</code> always return <code>nil</code> even though <code>dlopen</code> returns non-null? Similarly, <code>nm</code> doesn't list either <code>my_load</code> or <code>someFunc</code> as symbols of the .so.</li>
  <li>Is it possible to use <code>LD_PRELOAD</code> to load the library? I tried copying the .so into the same directory as the target then invoking <code>LD_PRELOAD="./MyLib.so.1.0.1" ./TestProg</code> but again <code>my_load</code> seems not to be being called.</li>
  </ol>