什麼是 ELF

這篇文章,這篇將接續對於ELF(Executable Linkable Format)的認識。.o, .a與 .so皆是透過ELF檔的格式儲存,ELF檔的結構由多個區段組成,包括file header, .text section, .data section 以及 .bss section等區段。其中”file header”描述檔案的基本屬性,包括檔案版本,目的機器型號,程式入口位址等等,”.text”存放程式碼區段,”.data”存放已初始化的全域變數以及靜態變數,而”.bss”存放已初始化的全域變數以及靜態變數。這篇的小實驗同樣是藉由main.cpp這支簡單的小程式來進行。

main.cpp

1
2
3
4
#define N 81
int main(){
return 0;//this is the end
}

查看ELF檔內容

readelf這個指令可以用來詳細查看ELF檔,如下面的範例中查看 main.o的file header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ readelf -h main.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: 600 (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: 12
Section header string table index: 11

查看ELF檔各個區段的長度

size這個指令可以用來查看ELF檔各個區段的長度。在main.cpp檔中,我們並未宣告任何的變數,於是可以看到以下在於”.text”以及”.data”區段的長度皆為0。

1
2
3
$ size main.o
text data bss dec hex filename
103 0 0 103 67 main.o