elf 文件解析

elf
gcc
Author

dd21

Published

December 11, 2022

Abstract

对elf文件的解析, 具体包括:elfhead, 节头表, 程序头表

Referance

计算机系统基础(袁春风)

ELF文件

ELF文件类型

节(section)是ELF 文件中具有相同特征的最小可处理单位.text节: 代码.data节: 数据.rodata: 只读数据.bss: 未初始化数据

由不同的段(segment)组成,描述节如何映射到存储段中,可多个节映射到同一段,如:可合并.data节和.bss节,并映射到一个可读可写数据段中

总结: 节是在链接视图的时候的概念, 段是在执行视图的时候的概念, 段就是将许多个相同的节放在一起就构成了段.

ELF头(ELF Header)

ELF头位于ELF文件开始,包含文件结构说明信息 。分32位系统对应结构 和64位系统对应结构(32位版本、64位版本)

以下是32位系统对应的数据结构

#define EI_NIDENT 16

typedef struct {
unsigned char e_ident[EI_NIDENT];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
} Elf32_Ehdr;

对应到下面的头文件中

readelf -h mian.o (//可重定位文件)
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
  ABI Version:                       0
  Type:                              REL (Relocatable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x0
  Start of program headers:          0 (bytes into file)
  Start of section headers:          824 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           0 (bytes)
  Number of program headers:         0
  Size of section headers:           40 (bytes)
  Number of section headers:         16
  Section header string table index: 15

Magic:文件开头几个字节通常用来确定文件的类型或格式a.out的魔数:01H 07HPE格式魔数:4DH 5AH加载或读取文件时,可用魔数确认文件类型是否正确