How can I obtain the file path which dlopen actually uses?

155 Views Asked by At

Suppose I make the following call:

void* my_dl_handle = dlopen("foo", RTLD_NOW);

(but it might be RLTD_LAZY). Now, I have a handle which I can use with dlsym() and a symbol name to get a function address.

Now, I want to determine the actuall full pathname which dlopen() used, e.g. /path/to/foo.so. Can I do this somehow?

Notes:

  • Ignore the possibility of files/directories been moved around while the program is running, i.e. the filename would not be resolved differently at different times
  • Motivation: This can be important when multiple paths are possible and you want to log exactly which one you used.
1

There are 1 best solutions below

2
einpoklum On

As @IanAbbot suggests, there are some platform-specific answers to your question. For the common case of GNU libc, you can use the dlinfo() function on your handle:

#include <linux/limits.h> // for PATH_MAX
#include <link.h>
#include <dlfcn.h>

// ... etc. etc.

void* my_dl_handle = dlopen("foo", RTLD_NOW);
#ifdef _GNU_SOURCE
char dyn_foo_path[PATH_MAX+1]; // we don't know how long the path might be
dlinfo(my_dl_handle, RTLD_DI_ORIGIN, &dl_path);
printf("I found foo at %s\n", dyn_foo_path);
#else
// Do something else for other platforms
#endif