Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the global variables in shared library when dlclose is called on it?

If a shared library (or a DLL) is being used through dlopen and dlclose mechanism and if the shared library created has some global variables whose memory comes from the heap, then what will happen to those variables and the memory when dlclose is called?

If in the same process, dlopen is called again, what will be the behaviour?

like image 910
Jay Avatar asked Feb 26 '23 08:02

Jay


1 Answers

If dlclose reduces the reference count to zero and the library is actually unloaded, any future reloading of the library should reset all variables with static storage duration in the library to their original values.

However, if the library was opened more than once, all but the final call to dlclose will just decrement the reference count. Sometimes it may not be obvious whether a library was opened more than once, since it might have gotten loaded as a dependency of some other library without you knowing, unless it's a module local to your program, so it's probably not a good idea to rely on this "reset" behavior.

Employed Russian added:

Even if the library is dlopen()ed and dlclose()d exactly once, and is not a dependency of something else, the act of referencing symbols from it (via dlsym()) will also increment the reference count (and make the library not unloadable); at least on Linux.

I have no idea if this information is accurate or not. In the future, please post new information as a comment or a new answer, not an edit to other people's answers. If you just edit someone else's answers, you make them take responsibility for the correctness of your answer, which they may not want.

like image 113
R.. GitHub STOP HELPING ICE Avatar answered Mar 22 '23 22:03

R.. GitHub STOP HELPING ICE