如何获取与dlopen相对路径对应的绝对库文件名?

Joh*_*itb 11 c c++ linux posix dlopen

在我的程序中,我有如下代码

/* libname may be a relative path */
void loadLib(char const *libname) {
   void *handle = dlopen(libname);
   /* ... */
   dlclose(handle);
}
Run Code Online (Sandbox Code Playgroud)

在内部/* .. */,我需要读取内存映射文件/proc/self/maps,找到libname映射到的虚拟内存地址,我还需要打开库来查找其中的某些部分.为此,我需要dlopen通过在各个位置搜索找到的绝对名称(例如,在ldconfig缓存文件中).我怎样才能收到该文件名?


这就是我最终得到的结果(是的,这是C++代码,但是C标签对于这个问题dlopen是有意义的,因为它与C++和C一起使用,我的问题适用于两者,POSIX为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);
   }
Run Code Online (Sandbox Code Playgroud)

libfile是相对/纯文件名.该映射将产生非纯文件名(即不是foo.so但可能是./foo.so).之后我常常realpath得到最终的绝对路径名.它工作得很好!

Ole*_*leg 10

你可以用

... dlinfo(handle, RTLD_DI_LINKMAP, p)
p->l_name ...
Run Code Online (Sandbox Code Playgroud)

其中p的类型为Link_map**

有关详细信息,请参阅man dlinfo