Hook function to shared library unloading

笑着哭i 提交于 2020-02-22 07:33:45

问题


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 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.



来源:https://stackoverflow.com/questions/52551525/hook-function-to-shared-library-unloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!