9

Is there a way to find out the number of references to a dynamic library in a process? i.e. in an application many modules might have loaded the same library using dlopen and when a module does dlclose, can we know if the library is really being unloaded or it's reference is just being decremented?

Jay
  • 24,173
  • 25
  • 93
  • 141
  • I think you can export LD_DEBUG=files on your program to see that on your own e.g., `17491: opening file=libs/liblang1/libliblang1_shared.so [0]; direct_opencount=6` I don't know if there is a way to code it – Aviv May 21 '22 at 09:10

2 Answers2

5

From the man page:

dlclose()

The function dlclose() decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in it, then the dynamic library is unloaded.
The function dlclose() returns 0 on success, and nonzero on error.

So reference counting is done automatically, but the fact that this call is the last one and does unload the library is not indicated. You'll need to count yourself if you need that.

Or you could dlopen with the RTLD_NOLOAD after the dlclose:

Don't  load  the  library.   This  can  be  used  to  test if the library is already resident  (dlopen() returns NULL if it is not, or the library's handle if it is resident).

(Note that you'll need to dlclose() it again if you got a reference. This is racy, so make sure all the potential manipulations happen in a single thread or are serialized.)

You might be interested in the RTLD_NODELETE option:

Do not unload the library during dlclose(). Consequently, the library's static variables are not reinitialized if the library is reloaded with dlopen() at a later time. This flag is not specified in POSIX.1-2001.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    `Note that you'll need to dlclose() it again if you got a reference` This may be the wrong way. If there is a reference count, it proves that there are other libraries referencing it. This operation is not very recommended – daohu527 Nov 02 '20 at 00:51
0

You can check whether the library has been unmapped from the process address space by checking the file /proc/self/maps.

I'm afraid that this is probably quite linux specific, but it should work.

rodrigo
  • 94,151
  • 12
  • 143
  • 190