When you dlopen()
a shared object, is there a mechanism for having code in that DLL execute without being called explicitly? Specifically, C++ static initialization code for globals/statics which the caller of dlopen()
might not know about? I'm pretty sure the answer should be "yes" but I don't remember what mechanism makes that happen, and how to utilize it for running arbitrary code.
Asked
Active
Viewed 1,255 times
5

Employed Russian
- 199,314
- 34
- 295
- 362

einpoklum
- 118,144
- 57
- 340
- 684
-
1http://stackoverflow.com/questions/2053029/how-exactly-does-attribute-constructor-work – Brian Bi Sep 16 '16 at 22:09
-
@Brian: I think you can make that an answer... although - what if I don't use GCC? e.g. clang or icc? – einpoklum Sep 16 '16 at 22:59
1 Answers
4
Yes: dlopen
respects an ELF binary format mechanism for running code at load time.
There are actually two such mechanisms:
- An older one uses special
.init
and.fini
s sections, which contain an array of function pointers fordlopen
anddlclose
to call. Since the sections may not be present at runtime, there are alsoDT_INIT
andDT_FINI
dynamic tags which point to the corresponding sections. - The newer mechanism is
.init_array
and.fini_array
and correspondingDT_INIT_ARRAY
,DT_INIT_ARRAYSZ
,DT_FINI_ARRAY
andDT_FINI_ARRAYSZ
dynamic tags.
The difference between the two mechanisms is described here.
Going up to the source code level, if you decorate a C function with __attribute__((constructor))
, the compiler will use one of those two mechanisms to make it run when the object is dlopen
ed. The same goes for the construction code for global C++ objects requiring dynamic initialization.

einpoklum
- 118,144
- 57
- 340
- 684

Employed Russian
- 199,314
- 34
- 295
- 362