From a function in a shared library, inside a running process (written in C), how do I discover where that shared library was loaded from?
从共享库中的函数,到正在运行的进程(用C编写),我如何发现共享库是从哪里加载的?
All of the answers I've found involve using things such as ldd
at the command line, or by peeking in /proc/self/maps
.
我发现的所有答案都涉及到在命令行中使用ldd,或者通过在/proc/self/maps中查看
On Win32, I'd just use GetModuleFileName(GetModuleHandle("foo.dll"), szPath, COUNTOF(szPath))
. What's the Linux equivalent?
在Win32中,我只使用GetModuleFileName(GetModuleHandle(“foo.dll”)、szPath、COUNTOF(szPath))。Linux等价的是什么?
Bonus question: I need the same information in OS X.
附加问题:我需要同样的信息在OS X。
1 个解决方案
#1
2
You could use dl_iterate_phdr to iterate all loaded libraries and their segments (similar functionality is available for OSX, see e.g. this question). But most of the projects just parse /proc/self/maps
.
您可以使用dl_iterate_phdr来迭代所有已加载的库及其段(类似的功能可用于OSX,请参见这个问题)。但是大多数项目只是解析/proc/self/maps
As a side note, keep in mind that mappings may change dynamically (if libraries are loaded via dlopen
) so reading them at startup may not be enough.
作为补充说明,请记住映射可能会动态变化(如果库是通过dlopen加载的),因此在启动时阅读它们可能是不够的。
#1
2
You could use dl_iterate_phdr to iterate all loaded libraries and their segments (similar functionality is available for OSX, see e.g. this question). But most of the projects just parse /proc/self/maps
.
您可以使用dl_iterate_phdr来迭代所有已加载的库及其段(类似的功能可用于OSX,请参见这个问题)。但是大多数项目只是解析/proc/self/maps
As a side note, keep in mind that mappings may change dynamically (if libraries are loaded via dlopen
) so reading them at startup may not be enough.
作为补充说明,请记住映射可能会动态变化(如果库是通过dlopen加载的),因此在启动时阅读它们可能是不够的。