加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

覆盖C中的_init函数,它有多安全?

发布时间:2020-12-13 19:00:29 所属栏目:Linux 来源:网络整理
导读:我正在以共享库的形式构建调试内存工具,我在运行时链接可执行文件(包括malloc系列的重写方法).为了处理我的数据结构的初始化,我简单地使用了一个条件变量.每次调用malloc时,我都会检查变量是否未设置,然后调用一个负责初始化结构的函数.现在,这适用于运行单

我正在以共享库的形式构建调试内存工具,我在运行时链接可执行文件(包括malloc系列的重写方法).为了处理我的数据结构的初始化,我简单地使用了一个条件变量.每次调用malloc时,我都会检查变量是否未设置,然后调用一个负责初始化结构的函数.现在,这适用于运行单个执行线程的程序,但如果程序包含多个线程,则会出现问题.

确保在用户生成任何线程之前进行初始化的唯一方法(我能想到)是覆盖_init,如图所示in this link.

现在这个小例子运行正确,但是当我尝试在我自己的共享库中覆盖_init时,我在尝试链接时遇到此错误:

memory2.o: In function `_init':
memory2.c(.text+0x0): multiple definition of `_init'
/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crti.o(.init+0x0): 
 first defined here
collect2: ld returned 1 exit status

我使用与链接中的示例完全相同的步骤,只是我的共享库还包括一组全局变量和malloc / free的覆盖版本等.

任何人都可以给我一个指出错误的指针?此外,在覆盖_init时还有什么需要考虑的因素(我猜这不是一件很正常的事情).

谢谢

最佳答案
请查看以下常见问题页面:

http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP

它将_init / _fini描述为危险且过时,并建议使用__attribute __((构造函数))和__attribute __((析构函数)).

gcc manual开始:

constructor (priority)
destructor (priority)

The
constructor attribute causes the
function to be called automatically
before execution enters main().
Similarly,the destructor attribute
causes the function to be called
automatically after main() has
completed or exit() has been called.
Functions with these attributes are
useful for initializing data that will
be used implicitly during the
execution of the program. You may
provide an optional integer priority
to control the order in which
constructor and destructor functions
are run. A constructor with a smaller
priority number runs before a
constructor with a larger priority
number; the opposite relationship
holds for destructors. So,if you have
a constructor that allocates a
resource and a destructor that
deallocates the same resource,both
functions typically have the same
priority. The priorities for
constructor and destructor functions
are the same as those specified for
namespace-scope C++ objects (see C++
Attributes).

These attributes are not currently
implemented for Objective-C.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读