Skip to content
Advertisement

How can a shared library know where it resides?

I’m developing a shared library for linux machines, which is dynamically loaded relative to the main executable with rpath. Now, the library itself tries to load other libraries dynamically relative to its location but without rpath (I use scandir to search for shared libraries in a certain folder – I don’t know their names yet).

This works only, if the working directory is set to the shared libraries location, as otherwise I look in a different directory as intended.

Is there any practical, reliable way for the shared library to determine where it resides?

I know, I could use /proc/self/maps or something like that, to get the loaded files, but this works only, as long the library knows its own name.

Another idea is so use dlinfo(), but to use it, the shared library need to know its own handle.

Advertisement

Answer

Is there any practical, reliable way for the shared library to determine where it resides?

I’d use dlinfo and /proc/self/maps (proc may not always be mounted, especially in containers).

I know, I could use /proc/self/maps or something like that, to get the loaded files, but this works only, as long the library knows its own name.

Not really, you can take a pointer to some code inside library (preferably to some internal label, to avoid messing with PLT/GOT) and compare result against memory range obtained from /proc/self/maps (or dlinfo).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement