linux - 共享库卸载的钩子(Hook)函数

标签 linux elf dynamic-linking

我想添加钩子(Hook)函数,它会在共享库卸载时被调用。库在编译时链接。有可能做这样的事情吗?也许 gcc 有它的标志?

我看到类似的运行时加载库的解决方案,但它不符合我的期望。

最佳答案

对于 Linux 系统,dlopen()/dlclose() 手册页解释了如何将这样的函数添加到您的库中:

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.

关于linux - 共享库卸载的钩子(Hook)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551525/

相关文章:

linux - Linux 上的 Qt5 - Linguist 在哪里?

c - SPARC 程序集 jmp\boot

linux - 有效地在 ELF 文件中添加新部分

c - C 运行时静态链接与动态链接中的内存分配

c - 通过 RTLD_LAZY 链接的动态库

linux - 如何在 tail -f 中只显示新记录的内容?

c - 简单的 shell linux C 实现,使用 freopen 重定向 stdout

linux - bash 命令变量内的变量

linux - Linux 应用程序的虚拟地址重整

c++ - 代码::阻止链接错误