4

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.
einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

3

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
$
Ctx
  • 18,090
  • 24
  • 36
  • 51
  • That's awesome! Thank you... it's not gcc-specific, though, right? – einpoklum Jan 19 '16 at 23:02
  • Well, it's more a matter of the linker. gcc just passes `-export-dynamic` to `ld` when `-rdynamic` is specified. Any ELF-linker should support it one way or another. It of course doesn't work, if the binary format doesn't know a symbol table or similar construct. – Ctx Jan 19 '16 at 23:05
  • 1
    Note that if you link a static library, the only symbols from the library accessible via this method will be those exported by the object files actually linked in the executable. – chqrlie Jan 20 '16 at 00:44