How can a shared library know where it resides?

拥有回忆 提交于 2021-01-28 00:44:31

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/41563643/how-can-a-shared-library-know-where-it-resides

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!