目录
生成可执行文件
可执行文件也是ELF文件,这里同样从ELF文件的观点分析可执行文件的结构
使用如下两端代码来模拟多个文件生成一个可执行文件的过程
//add.c
extern int times;
int add(int n1, int n2) {
times++;
return n1 + n2;
}
//main.c
#include <stdio.h>
extern int add(int, int);
int times = 0;
int main(void)
{
int a = 2;
int b = 3;
printf("%d, The sum of a and b is %d\n", times, add(a,b));
return 0;
}
使用命令如下,先生成两个可重定位文件,然后对其进行链接,生成可执行文件add
gcc -c add.c -o add.o
gcc -c main.c -o main.o
gcc -o add add.o main.o
注意,假如下面查看可执行文件,发现type是共享库文件类型,可能是因为gcc默认加了--enable-default-pie选项,可以使用-no-pie禁用,如下
gcc -o add add.c main.c -no-pie
可执行文件的结构
可执行文件的ELF Header
使用readelf查看文件
$ readelf -h add
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x401050
Start of program headers: 64 (bytes into file)
Start of section headers: 14736 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 13
Size of section headers: 64 (bytes)
Number of section headers: 31
Section header string table index: 30
字段分析如下
- Type: EXEC (Executable file): 该文件是一个可执行文件;
- Entry point address: 0x401050: 文件的入口地址为0x401050,该地址是代码段的起始地址;
- xxx of program headers: xxx: 该文件中共有13个program header,每个的大小为56字节;
- xxx of section headers: xxx: 该文件中共有31个section header,每个的大小为64字节。
这里可以看出,链接之后生成的可执行文件,该文件结构具有了完整的ELF文件结构。
可执行文件的section
从ELF Header中可以看出 add 有31个 section,使用readelf查看section的内容
$ readelf -S add
There are 31 section headers, starting at offset 0x3990:
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 0] NULL 0000000000000000 0