Search code examples
creflectiondebug-symbolsdlsym

dlsym-like functionality for non-dynamically-loaded code?


I know how to use dlsym() to find symbols keyed by a string - when these symbols are exported by a shared library which I've dlopen()ed. But - what about other code? Just object code I've linked statically. Is it possible to somehow lookup symbols?

Notes:

  • If it helps, make any reasonable assumptions about the compilation and linking process (e.g. which compiler, presence of debug info, PIC code etc.)
  • I'm interested more in a non-OS-specific solution, but if it matters: Linux.
  • Solutions involving pre-registration of functions are not relevant. Or rather, maybe they are, but I would rather avoid that.

Solution

  • You can indeed just use dlsym() for that purpose.. You just have to export all symbols to the dynamic symbol table. Link the binary with gcc -rdynamic for that.

    Example:

    #include <stdio.h>
    #include <dlfcn.h>
    
    void foo (void) {
        puts("foo");
    }
    
    int main (void) {
        void (*foo)(void) = dlsym(NULL, "foo");
        foo();
        return 0;
    }
    

    Compile with: gcc -rdynamic -O2 dl.c -o dl -ldl

    $ ./dl
    foo
    $