使用 .init_array 部分的分段错误
Segmentation fault using .init_array section
我正在学习 ELF 并且 运行 进入 st运行ge 段错误
代码:
#include <stdio.h>
#include <stdint.h>
__attribute__((constructor(102))) static void init1() {
printf("%s\n", __FUNCTION__);
}
__attribute__((constructor(101))) static void init2() {
printf("%s\n", __FUNCTION__);
}
void another_init1() {
printf("%s\n", __FUNCTION__);
}
void another_init2() {
printf("%s\n", __FUNCTION__);
}
typedef void (*init)();
__attribute__((section(".init_array"))) init init_arr[2] = {another_init1, another_init2};
static void my_function_1() {}
int main() {
printf("hello world\n");
return 0;
}
用 gcc -o hello hello.c
和 运行 ./hello
编译我看到
[root@20f890034489 ch5]# ./hello
init2
init1
Segmentation fault
这来自 .init_arr。如果我让这个数组包含一个函数 ptr,一切都会按预期工作,但是如果有 2 个 ptr,它就会出现错误。
有什么建议吗?找到这个 st运行ge
VK
init_array
应该与指针的大小对齐;如果您将其更改为:
__attribute__((section(".init_array"), aligned(sizeof (void*)))) init init_arr[2] = {another_init1, another_init2};
它会起作用。
如果不是(至少在 x86-64 上),gcc
会将您的数组对齐到 16 字节的边界,在 .init_array
部分中已经存在的 3 个函数指针之间创建 8 字节的间隙(frame_dummy
+ 你的 init1
和 init2
) 和 2 个新函数,它们将作为 NULL
指针出现在动态链接器中。
我正在学习 ELF 并且 运行 进入 st运行ge 段错误
代码:
#include <stdio.h>
#include <stdint.h>
__attribute__((constructor(102))) static void init1() {
printf("%s\n", __FUNCTION__);
}
__attribute__((constructor(101))) static void init2() {
printf("%s\n", __FUNCTION__);
}
void another_init1() {
printf("%s\n", __FUNCTION__);
}
void another_init2() {
printf("%s\n", __FUNCTION__);
}
typedef void (*init)();
__attribute__((section(".init_array"))) init init_arr[2] = {another_init1, another_init2};
static void my_function_1() {}
int main() {
printf("hello world\n");
return 0;
}
用 gcc -o hello hello.c
和 运行 ./hello
编译我看到
[root@20f890034489 ch5]# ./hello
init2
init1
Segmentation fault
这来自 .init_arr。如果我让这个数组包含一个函数 ptr,一切都会按预期工作,但是如果有 2 个 ptr,它就会出现错误。
有什么建议吗?找到这个 st运行ge
VK
init_array
应该与指针的大小对齐;如果您将其更改为:
__attribute__((section(".init_array"), aligned(sizeof (void*)))) init init_arr[2] = {another_init1, another_init2};
它会起作用。
如果不是(至少在 x86-64 上),gcc
会将您的数组对齐到 16 字节的边界,在 .init_array
部分中已经存在的 3 个函数指针之间创建 8 字节的间隙(frame_dummy
+ 你的 init1
和 init2
) 和 2 个新函数,它们将作为 NULL
指针出现在动态链接器中。