Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 26 Dec 2015 14:28:18 +0200
From:      Konstantin Belousov <kostikbel@gmail.com>
To:        Ivan Radovanovic <radovanovic@gmail.com>
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: Unexpected behavior of dynamic linker
Message-ID:  <20151226122818.GI3625@kib.kiev.ua>
In-Reply-To: <567E810C.3040809@gmail.com>
References:  <567E810C.3040809@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sat, Dec 26, 2015 at 12:59:08PM +0100, Ivan Radovanovic wrote:
> Hello,
> 
> While investigating possibility of building some module system on 
> FreeBSD I stumbled upon unexpected (at least for me) behavior of dynamic 
> linker.
> 
> I have several (C++) modules organized like this:
> 
> * main program (executable)
> * main library (shared object, loaded with RTLD_GLOBAL since it provides 
> symbols for main program and other modules)
> * module 1 (shared object, loaded with RTLD_LOCAL)
> 
> I put all private initializations for library and module in (static) 
> global object constructors, but I gave to both classes same (original) 
> name "PrivateClass" (so there is in fact PrivateClass in mainlib.so, and 
> unrelated PrivateClass in module.so).
> 
> What is happening is that when main program loads main library (via 
> dlopen(3)) its _init calls correctly mainlib::PrivateClass constructor 
> which performs initialization, but when main program later loads module 
> (again via dlopen(3)) its _init doesn't call module::PrivateClass 
> constructor, but rather mainlib::PrivateClass constructor. I understand 
> this is happening because symbols with same name exist in both shared 
> objects and dynamic linker is replacing reference to 
> module::PrivateClass with reference to mainlib::PrivateClass, but I 
> would expect symbol to be looked up outside of module only if it doesn't 
> exist within it (ie, the inner-most definition to be used) - in this 
> case PrivateClass exists within module?
> 
> Further I am not sure what would be correct solution for this in my case 
> - C++ has static modifier for objects and functions, but not for classes 
> to make them unavailable from other modules and solution with same 
> random namespace name doesn't sound elegant enough :-)
> 
> Any thoughts regarding this (I can also supply source files to test this 
> behavior)?

This is expected behaviour, it is mandated by the ELF standard.  ELF
tried to emulate the behaviour of the static libraries as much as possible.
Think what would happen in your case if both modules where linked statically
into the binary.

To augment the behaviour, read about linker option -Bsymbolic, compiler
option -fhidden, and GNU-specific attribute __visibility__("hidden").



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20151226122818.GI3625>