In my program I have code like the following
/* libname may be a relative path */
void loadLib(char const *libname) {
void *handle = dlopen(libname);
/* ... */
dlclose(handle);
}
Within /* .. */
, I need to read the memory map file /proc/self/maps
, to find the virtual memory address at which libname
is mapped to and I also need to open the library to find certain sections in it. For this, I need the absolute name that dlopen
found by searching in the various places (like, in the ldconfig
cache file). How can I receive that file name?
This is what I finally ended up with (yes, this is C++ code, nonetheless the C tag makes sense for this question because dlopen
is used with both C++ and C and my question is eligible for both and POSIX specifies it for C.).
boost::shared_ptr<void> dl;
if(void *handle = dlopen(libfile, RTLD_LAZY)) {
dl.reset(handle, &dlclose);
} else {
printdlerr();
return -1;
}
/* update sofile to be an absolute file name */
{
struct link_map *map;
dlinfo(dl.get(), RTLD_DI_LINKMAP, &map);
if(!map) {
return -1;
}
char *real = realpath(map->l_name, NULL);
if(!real)
return -1;
sofile.reset(real, &free);
}
libfile
is the relative / plain filename. The map will yield a non-plain file name (i.e not foo.so
but may be ./foo.so
). Afterwards I used realpath
to get the final absolute path name. It works nicely!
you could use
... dlinfo(handle, RTLD_DI_LINKMAP, p)
p->l_name ...
where p is of type Link_map**
see man dlinfo for details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With