目录
section header table 及 sections
可重定位文件是一个ELF格式的二进制文件,这里从ELF文件格式入手分析可重定位文件的结构。
生成可重定位文件
使用代码如下
#include<stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
生成文件指令
gcc -E hello.c -o hello.i
gcc -S hello.i -o hello.s
gcc -c hello.s -o hello.o
可重定位文件分析
解析文件头
使用readelf命令查看构成
$ readelf -h hello.o
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: REL (Relocatable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x0
Start of program headers: 0 (bytes into file)
Start of section headers: 792 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 0 (bytes)
Number of program headers: 0
Size of section headers: 64 (bytes)
Number of section headers: 14
Section header string table index: 13
关注如下字段:
Type: REL (Relocatable file)
说明 .o 文件的类型为可重定位文件
Number of program headers: 0
可以看出可重定位文件的 program header table 的长度为 0 。因为 program header table 保存的是 segment 信息,而 segment 是为了给加载器提供可执行程序在加载时所需的信息的,又因为可重定位文件本身并不能直接执行,因此在可重定位文件里不需要 program header table 。
Entry point address: 0x0
由于可重定位文件不能直接执行,因此入口地址为 0(默认值)。
Start of section headers :
从ELF文件起始地址偏移 792 个字节处是 section header table 的起始地址,section header table 中有 14 项,每项的大小为 64 byte
Size of section headers: 64 (bytes)
ELF文件头大小为 64 byte。
分析ELF文件各部分
可重定位文件属于二进制文件,在linux机器上可以使用 hexdump 命令来查看二进制文件的内容
$ hexdump -C hello.o
00000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 |.ELF............|
00000010 01 00 3e 00 01 00 00 00 00 00 00 00 00 00 00 00 |..>.............|
00000020 00 00 00 00 00 00 00 00 18 03 00 00 00 00 00 00 |................|
00000030 00 00 00 00 40 00 00 00 00 00 40 00 0e 00 0d 00 |....@.....@.....|
00000040 f3 0f 1e fa 55 48 89 e5 48 8d 3d 00 00 00 00 e8 |....UH..H.=.....|
00000050 00 00 00 00 b8 00 00 00 00 5d c3 68 65 6c 6c 6f |.........].hello|
00000060 20 77 6f 72 6c 64 00 00 47 43 43 3a 20 28 55 62 | world..GCC: (Ub|
00000070 75 6e 74 75 20 39 2e 33 2e 30 2d 31 37 75 62 75 |untu 9.3.0-17ubu|
00000080 6e 74 75 31 7e 32 30 2e 30 34 29 20 39 2e 33 2e |ntu1~20.04) 9.3.|
00000090 30 00 00 00 00 00 00 00 04 00 00 00 10 00 00 00 |0...............|
000000a0 05 00 00 00 47 4e 55 00 02 00 00 c0 04 00 00 00 |....GNU.........|
000000b0 03 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 |................|
000000c0 01 7a 52 00 01 78 10 01 1b 0c 07 08 90 01 00 00 |.zR..x..........|
000000d0 1c 00 00 00 1c 00 00 00 00 00 00 00 1b 00 00 00 |................|
000000e0 00 45 0e 10 86 02 43 0d 06 52 0c 07 08 00 00 00 |.E....C..R......|
000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000100 00 00 00 00 00 00 00 00 01 00 00