KDOC 686: ELFヘッダを見る
この文書のステータス
- 作成
- 2026-10-17 貴島
- レビュー
- 2026-10-17 貴島
概要
ELFファイルの先頭にはELFヘッダがある。64ビットのELFなら64バイトで、構造体 Elf64_Ehdr のフィールドが順に並んでいる(elf(5))。生のバイトを見て、 readelf -h の表示と照らし合わせる。
xxd -l 64 /bin/ls
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............
00000010: 0300 3e00 0100 0000 306d 0000 0000 0000 ..>.....0m......
00000020: 4000 0000 0000 0000 2824 0200 0000 0000 @.......($......
00000030: 0000 0000 4000 3800 0d00 4000 1f00 1e00 ....@.8...@.....
readelf -h /bin/ls
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: DYN (Position-Independent Executable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x6d30
Start of program headers: 64 (bytes into file)
Start of section headers: 140328 (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
| オフセット | バイト | フィールド | 値 |
|---|---|---|---|
| 0x00 | 7f 45 4c 46 | e_ident[EI_MAG0] 〜 [EI_MAG3] |
\x7f E L F |
| 0x04 | 02 | e_ident[EI_CLASS] |
2 = ELFCLASS64 |
| 0x05 | 01 | e_ident[EI_DATA] |
1 = ELFDATA2LSB |
| 0x10 | 03 00 | e_type |
3 = ET_DYN |
| 0x12 | 3e 00 | e_machine |
62 = EM_X86_64 |
| 0x18 | 30 6d 00 … 00 | e_entry |
0x6d30 |
リトルエンディアンなので、2バイト以上の値は下位のバイトが先に来る。 e_entry の 30 6d は逆から読んで 0x6d30 になる。数値と名前の対応は /usr/include/elf.h にある。
grep -E '#define (ELFCLASS64|ELFDATA2LSB|ET_DYN|EM_X86_64)\b' /usr/include/elf.h
#define ELFCLASS64 2 /* 64-bit objects */
#define ELFDATA2LSB 1 /* 2's complement, little endian */
#define ET_DYN 3 /* Shared object file */
#define EM_X86_64 62 /* AMD x86-64 architecture */
関連
- 補足: KDOC 179: 『ハロー“Hello, World” OSと標準ライブラリのシゴトとしくみ』。readelfでELFを読む例が出てくる