对main函数hook

__attribute__ 是GCC的特殊语法,
利用这个标识符可以支持在main函数之前和main函数执行完毕之后运行一些操作

__attribute__((constructor)) syntax
在一个函数前面加上这个标识符,可以使这个函数在 main() 函数之前运行
若有多个,按照定义先后顺序运行, 也可constructor(priority)这样显示定义优先级

注意 优先级0~100是作为保留使用的,
若使用了可能得到一个
Warning constructor priorities from 0 to 100 are reserved for the implementation [-Wprio-ctor-dtor]

__attribute__((destructor)) syntax
在一个函数前面加上这个标识符,可以使这个函数在 main() 函数之后运行

同样也有优先级,同上.

e.g. 使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
###include <cstdio>

__attribute__((constructor)) void calledSecond();
__attribute__((constructor(200))) void calledFirst();
__attribute__((destructor)) void calledEnd();

int main(int argc, char *argv[]) {
printf("main: hello world\n");
return 0;
}

void calledFirst() { printf("start: foo\n"); }
void calledSecond() { printf("second: bar\n"); }
void calledEnd() { printf("end: over\n"); }

运行结果:

1
2
3
4
start: foo
second: bar
main: hello world
end: over

其他属性

__attribute__((noinline)) 拒绝内联优化