ELF(Executable and Linkable Format)是 Linux 標準可執行文件、目標文件、共享庫、核心轉儲文件格式。本文從文件頭、程序頭、節頭表、核心段(.text/.data/.bss)解析,配合 readelf、objdump 實戰演示,揭示二進制文件內部結構。
$ file prim
prim: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=..., not stripped
strip 後變 stripped+------------------+ | ELF Header | 文件頭:魔數、架構、入口點、程序頭/節頭表偏移量 +------------------+ | Program Header | 程序頭表(段視圖):載入時內核讀取,描述段在內存映射 | Table | +------------------+ | Section 1 (.text)| 代碼段:只讀、可執行指令 | Section 2 (.data)| 數據段:已初始化全局/靜態變量,可讀寫 | Section 3 (.bss) | BSS 段:未初始化全局/靜態變量,文件不佔空間,運行時置零 | ... | 其他節:.rodata .symtab .strtab .rel.* .debug_* 等 +------------------+ | Section Header | 節頭表(鏈接視圖):鏈接器讀取,描述節屬性、符號、重定位 | Table | +------------------+
readelf -h:查看 ELF 文件頭$ readelf -h prim
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
Type: EXEC (Executable file)
Machine: Intel 80386
Version: 0x1
Entry point address: 0x8048350
Start of program headers: 52 (bytes into file)
Start of section headers: 4680 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 9
Size of section headers: 40 (bytes)
Number of section headers: 31
Section header string table index: 28
關鍵字段:Entry point address(程序入口,_start)、program headers(載入視圖)、section headers(鏈接視圖)。
objdump -h:查看節頭表(段信息)$ g++ -c prim.cpp -o prim.o
$ objdump -h prim.o
prim.o: file format elf32-i386
Sections:
Idx Name Size VMA LMA File off Algn
0 .text 0000031f 00000000 00000000 00000034 2**2
CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
1 .data 00000000 00000000 00000000 00000354 2**2
CONTENTS, ALLOC, LOAD, DATA
2 .bss 003d3c21 00000000 00000000 00000360 2**5
ALLOC
3 .rodata 00000008 00000000 00000000 00000360 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
4 .ctors 00000004 00000000 00000000 00000368 2**2
CONTENTS, ALLOC, LOAD, RELOC, DATA
5 .comment 0000002c 00000000 00000000 0000036c 2**0
CONTENTS, READONLY
6 .note.GNU-stack 00000000 00000000 00000000 00000398 2**0
CONTENTS, READONLY
7 .eh_frame 000000dc 00000000 00000000 00000398 2**2
CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
| 標誌 | 含義 |
|---|---|
CONTENTS | 節在文件中佔有空間(非 BSS) |
ALLOC | 載入時需在內存分配空間 |
LOAD | 程序頭中有對應 LOAD 段(需載入內存) |
READONLY | 內存映射只讀 |
CODE | 包含可執行指令 |
DATA | 包含數據 |
RELOC | 存在重定位條目(目標文件典型) |