Search code examples
c++cposixshared-librariesdlopen

Portable way to determine path to dynamic library opened with dlopen


I'm searching for a portable (POSIX) way to determine the path to a library opened with dlopen(). Functions like dl_iterate_phdr() and dladdr() are not portable.

Some man pages detail the path taken by dlopen() to find libraries to open (ld.so.cache, LD_LIBRARY_PATH, /lib, /usr/lib, ...), so checking all of these directories could be possible, but not portable. For example, under Linux, I'd need a way to parse ld.so.cache but under Mac OS X, there is no such concept.

Please see a previous question for detail on why I want to do this, since using dlopen is ill-advised in the general case.


Solution

  • There's not really any way to do what you want portably. Really it's probably a bad idea to use dlopen without an absolute path, and also a bad idea to use it for anything other than modules intended to be loaded with dlopen (created by and distributed with either your own project itself or another library your application uses). If you use it with the system library search path and libraries "already present" on the system, you run serious risks of loading the wrong version or even the wrong library with the same name. As long as you always pass an absolute path to dlopen, you can be sure you know exactly what file was loaded (or better yet, know exactly what file will be loaded before it gets loaded).

    If this answer doesn't help, perhaps you could better explain what you're trying to achieve..