问题
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.
回答1:
Solaris and GNU/Linux support the LD_AUDIT
interface in their dynamic linkers. You need to load an auditor module which implements the la_objclose
callback function:
- Runtime Linker Auditing Interface
The implementation can be as simple as this:
unsigned int
la_objclose (uintptr_t *cookie)
{
printf ("objclose\n");
return 0;
}
In order to determine which object is being closed, you also need to implement la_objsearch
(and possibly la_objopen
), to establish a cookie value which somehow refers to the information you need at close time (you could store a pointer to a heap-allocated struct in the cookie, for example).
回答2:
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 beforedlopen()
returns, and destructor functions are executed beforedlclose()
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, beforedlopen()
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.
来源:https://stackoverflow.com/questions/52551525/hook-function-to-shared-library-unloading