Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find location of loaded shared library, from in that shared library?

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?

All of the answers I've found involve using things such as ldd at the command line, or by peeking in /proc/self/maps.

On Win32, I'd just use GetModuleFileName(GetModuleHandle("foo.dll"), szPath, COUNTOF(szPath)). What's the Linux equivalent?

Bonus question: I need the same information in OS X.

like image 433
Roger Lipscombe Avatar asked Apr 14 '17 09:04

Roger Lipscombe


1 Answers

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.

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.

like image 98
yugr Avatar answered Sep 24 '22 22:09

yugr