Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the absolute library file name corresponding to a relative path given to dlopen?

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!

like image 810
Johannes Schaub - litb Avatar asked Jul 13 '11 09:07

Johannes Schaub - litb


1 Answers

you could use

... dlinfo(handle, RTLD_DI_LINKMAP, p)
p->l_name ...

where p is of type Link_map**

see man dlinfo for details

like image 138
Oleg Avatar answered Nov 15 '22 04:11

Oleg