Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does dlopen re-load already loaded dependencies? If so, what are the implications?

Tags:

c++

gcc

dlopen

I have a program, code-named foo. foo depends on common.so and is linked to it in the normal way (sorry I don't know the technical way to say that). When foo is running it then dynamically loads bar.so using dlopen(). So far so good.

But, bar.so also depends on common.so. Will dlopen() re-load common.so (from what I've read it loads any required dependencies recursively), or will it detect that it is already loaded? If it does re-load it, could that cause problems in my program? Both foo and bar.so need to see the changes in common.so that either of them make to static variables there.

Maybe my design needs to be changed or requires use of -rdynamic (which I also don't quite understand properly yet)?

like image 609
Gyan aka Gary Buyn Avatar asked Aug 30 '15 23:08

Gyan aka Gary Buyn


1 Answers

The POSIX spec for dlopen() says:

Only a single copy of an executable object file shall be brought into the address space, even if dlopen() is invoked multiple times in reference to the executable object file, and even if different pathnames are used to reference the executable object file.

On Linux, this is implemented using a reference count; until dlclose is called an equal number of times, the shared object will remain resident.

[update]

I realize you are asking about shared objects implicitly loaded as dependencies, but the same principle applies. Otherwise, many things would break... In particular, global constructors in the shared object would run multiple times, which would wreak havoc.

like image 198
Nemo Avatar answered Sep 21 '22 18:09

Nemo