9

If I use dlopen on the same lib/file two times in the same application-run, will it yield the same handle in both cases? Is there any guarantee for this (a short experiment showed that it at least does on my box)?

I'm currently playing around with a little plugin-system (out of curiosity) and if there would be some kind of guarantee for this observed behaviour I could use this address as a key for a plugin to prevent duplicated loads.

mageta
  • 677
  • 2
  • 8
  • 12

1 Answers1

17

Yes. The dlopen(3) linux man page says:

   If the same library is loaded again with dlopen(), the same file 
   handle is returned. The dl library maintains reference counts for 
   library handles, so a dynamic library is not deallocated until 
   dlclose() has been called on it as many times as dlopen() 
   has succeeded on it.

BTW, on Linux systems, you can dlopen a lot (many dozens of thousands) of shared libraries, as my example manydl.c demonstrates. The main limitation is address space. So practically, not bothering about dlclose-ing stuff is possible.

(unless your dlopen-ed shared libraries have weird or resource consuming constructor or destructor functions)

Added in December 2017:

Notice that what is relevant is the exact path string passed to dlopen. So if you use "./foo.so" and "././foo.so" (or "../foosymlink.so" where foosymlink.so is a symlink to foo.so) the dlopen-ed handles are different, and in some cases weird behavior of the two instances of that shared library might happen.

added in june 2019:

Read also Drepper's How to write shared libraries paper (it explains also well how to use them!).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    .. and I just read this man page, why didn't I read this paragraph as well? Hmpf.. well, thank you none the less for answering my stupid question :) – mageta Aug 27 '12 at 20:11
  • 1
    May make sense to mention that each successive `dlopen` will increase the refcount so plugin will not be unloaded until it's `dlclose`d a matching number of times. – yugr Jun 03 '19 at 09:04
  • "Notice that what is relevant is the exact path string passed to dlopen." Doesn't seem to be the case generally. I just tested on macOS and it still returned the same handle when using different paths, or a symlink, or even copying the file. It did return a different handle when I patched the LC_ID_DYLIB. – tbodt Jul 11 '20 at 19:02
  • just note that dlopen NOLOAD flag also increases direct_opencount – Aviv May 19 '22 at 12:09