Search code examples
linuxdynamic-linkingdynamic-loading

dlopen() .so fails to find symbols in a stripped executable


I have an executable in linux - exe

This executable has some functions in it, that are used throughout the code:

  • sendMsg
  • debugPrint

I then want to dynamically load a .so that provides extra functionality to my executable.

In this shared library I include the headers for sendMsg and debugPrint.

I load this shared library with dlopen() and create an API with dlsym().

However, at dlopen() I use RTLD_NOW to resolve all symbols at load time.

It fails stating that it cannot find sendMsg symbol.

This symbol must be in the executable as the sendMsg.c is compiled in there.

However, my executable is stripped by the make process. As such, it would make sense that dlopen cannot find the symbol.

How can i solve this situation?

  • I could build the shared functions into a static library and link that static library into both exe and the .so. This would increase code size :(
  • I could remove the stripping of the exe so the symbols can be found
  • Do some compile time linking magic that I don't know about so the .so knows where the symbols are in exe

Solution

  • man ld:

       -E
       --export-dynamic
       --no-export-dynamic
           When  creating  a  dynamically  linked  executable, using the -E option or the --export-dynamic option causes the linker to add all symbols to the dynamic symbol table.  The
           dynamic symbol table is the set of symbols which are visible from dynamic objects at run time.
    
           If you do not use either of these options (or use the --no-export-dynamic option to restore the default behavior), the dynamic symbol table will normally contain only  those
           symbols which are referenced by some dynamic object mentioned in the link.
    
           If  you  use "dlopen" to load a dynamic object which needs to refer back to the symbols defined by the program, rather than some other dynamic object, then you will probably
           need to use this option when linking the program itself.
    
           You can also use the dynamic list to control what symbols should be added to  the  dynamic  symbol  table  if  the  output  format  supports  it.   See  the  description  of
           --dynamic-list.
    
           Note  that  this  option  is  specific  to  ELF  targeted  ports.   PE  targets  support  a  similar function to export all symbols from a DLL or EXE; see the description of
           --export-all-symbols below.
    

    You can also pass the -rdynamic option to gcc/g++ (as noted int the comment). Depending on how you setup your make script, this will be convenient