Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook function to shared library unloading

I want to add hook function, which will be called when shared library is unloaded. Library is linked on complitaion. Is it possible to do such thing? Maybe gcc has flag for it?

I saw similar solution for loading library on runtime, but it doesn't meet my expectations.

like image 948
mmichal10 Avatar asked Oct 19 '25 04:10

mmichal10


1 Answers

For Linux systems, the dlopen()/dlclose() man page explains how to add such a function to your library:

Initialization and finalization functions

Shared objects may export functions using the __attribute__((constructor)) and __attribute__((destructor)) function attributes. Constructor functions are executed before dlopen() returns, and destructor functions are executed before dlclose() returns. A shared object may export multiple constructors and destructors, and priorities can be associated with each function to determine the order in which they are executed. See the gcc info pages (under "Function attributes") for further information.

An older method of (partially) achieving the same result is via the use of two special symbols recognized by the linker: _init and _fini. If a dynamically loaded shared object exports a routine named _init(), then that code is executed after loading a shared object, before dlopen() returns. If the shared object exports a routine named _fini(), then that routine is called just before the object is unloaded. In this case, one must avoid linking against the system startup files, which contain default versions of these files; this can be done by using the gcc(1) -nostartfiles command-line option.

Use of _init and _fini is now deprecated in favor of the aforementioned constructors and destructors, which among other advantages, permit multiple initialization and finalization functions to be defined.

like image 110
Toby Speight Avatar answered Oct 22 '25 05:10

Toby Speight