Search code examples
c++shared-librariesdlopen

How to get the mangled symbol of a function in C++?


Context

I'm using dlmopen to load multiple instance of a shared library which I can't modify (proprietary). I do this because this library is not thread-compatible, so I need an independent version of it to be loaded for each thread.

void *handle = dlmopen(LM_ID_NEWLM, "/myLib.so", RTLD_LAZY);

In order to get the function I need, I call dlsym :

void * test_load = dlsym(handle, <function_symbol>);

My question is :

How do i get <function_symbol> knowing that :

  • My library is in C++ (aka the function symbol is mangled)
  • I can't modify the library (aka no extern "C" to get a predicable symbol)

I know that dlopen/dlmopen is initialy meant to be used in C, not C++, but unless there is an other way to load many time the same shared library, I am stuck


Solution

  • How do i get <function_symbol> knowing that

    Presumably you know which function you want to call. Let's say its name is somelib::Init(int, char**).

    1. Find that function address:
      nm -CD libsomelib.so | grep 'somelib::Init\(int, char\*\*\).
      This should produce something like 12345fa T somelib::Init...

    2. Find its mangled name of that symbol: nm -D libsomelib.so | grep '^12345fa '.
      This should produce something like 12345fa T _ZN7somelib4InitEiPPc.

    Use the mangled name in the dlsym call.


    There is no way to map somelib::Init(int, char**) to its mangled name because that mapping is not a 1:1 and depends on the exact compiler used to build libsomelib.so.