clinuxshared-librariesdlopendlsym

How to get address of a symbol in a shared library when provided address of the library?


I am learning about working with shared libraries in C/C++ on Linux. I encountered a little problem that I don't know how to solve.

Let's say I have a shared library and an executable. However I don't know the library's name or file location (so I can't dlopen it). I can only find the address range where the library is mapped into my executable's memory.

Is there a way to programmatically get either the handle of the library (something like handle = dlopen(library_address)) or offset of a symbol within the library (something like address = dlsym(library_address, symbol_name))?


Solution

  • If you knew the library's name, you could just call dlopen again.

    From the man page:

    If the same shared object is loaded again with dlopen(), the same object handle is returned.

    To discover the loaded modules, you can use dl_iterate_phdr().

    You can also use dladdr() to inquire about a specific address.