Fork me on GitHub

    通过一个简单的例子介绍一下gcc的__attribute__ ((constructor))属性的作用。gcc允许为函数设置__attribute__ ((constructor))和__attribute__ ((destructor))两种属性,顾名思义,就是将被修饰的函数作为构造函数或析构函数。程序员可以通过类似下面的方式为函数设置这些属性:  

void funcBeforeMain() __attribute__ ((constructor)); 

void funcAfterMain() __attribute__ ((destructor));

也可以放在函数名之前:
void __attribute__ ((constructor)) funcBeforeMain();
void __attribute__ ((destructor)) funcAfterMain();
带有(constructor)属性的函数将在main()函数之前被执行,而带有(destructor)属性的函数将在main()退出时执行。
下面给出一个简单的例子:
 1 #include <stdio.h>
 2 
 3 void __attribute__((constructor)) funcBeforeMain()
 4 {
 5     printf("%s...\n", __FUNCTION__);
 6 }
 7 
 8 void __attribute__((destructor)) funcAfterMain()
 9 {
10     printf("%s...\n", __FUNCTION__);
11 }
12 
13 int main()
14 {
15     printf("main...\n");
16     return 0;
17 }
View Code

运行结果:

funcBeforeMain...
main...
funcAfterMain...

  为什么有这么神奇的函数呢?它是怎么实现的呢?

  通过翻看GNU的link文档,我找到了答案:

在GNU link中,也就是你的系统中的XX.S文件,找到了详细的答案,

当使用a.out文件来链接程序时,链接器使用一个与众不同的关键字construct 来支持C++里面的全局constructors 和 destructors,当链接对象不支持任意剖分时,链接器可以通过名字来自动识别构造器和解析器。

link文件中的构造器格式如下:

 1       __CTOR_LIST__ = .;
 2       LONG((__CTOR_END__ - __CTOR_LIST__) / 4 - 2)
 3       *(.ctors)
 4       LONG(0)
 5       __CTOR_END__ = .;
 6       __DTOR_LIST__ = .;
 7       LONG((__DTOR_END__ - __DTOR_LIST__) / 4 - 2)
 8       *(.dtors)
 9       LONG(0)
10       __DTOR_END__ = .;
View Code

符号__CTOR_LIST__标志者全局构造器的开始,符号__DTOR_LIST标志着构造器的结束。列表中的第一个关键字代表条目的个数,后面紧跟者是构造器和解析器的地址。最后是一个零字符。编译器必须排队去执行这些代码。

GNU编译器通常通过一个子程序__main函数前面调用constructor,__main在被调用时会自动的插入到main函数的起始代码中。同样的是,GNU通过运行atexit来调用destructors,或者是通过函数exit来直接调用。

 

参考文档:

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/4/html/Using_ld_the_GNU_Linker/sections.html

posted on 2018-07-11 11:13  虚生  阅读(2637)  评论(0编辑  收藏  举报