文章目录
ELF文件结构
博客参考:https://segmentfault.com/a/1190000016766079
1.磁盘中的elf文件
1.1 宏观结构展示
•ELF文件头表(ELF header):记录了ELF文件的组织结构
•程序头表/段表(Program header table)
-
告诉系统如何创建进程
-
生成进程的可执行文件必须拥有此结构
-
重定位文件不一定需要
•节头表(Section header table)
-
记录了ELF文件的节区信息
-
用于链接的目标文件必须拥有此结构
-
其它类型目标文件不一定需要
1.2 ELF header解释
elf header的定义在:/usr/include/elf.h
1.2.1 字段定义
typedef struct
{
unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
Elf32_Half e_type; /* Object file type */
Elf32_Half e_machine; /* Architecture */
Elf32_Word e_version; /* Object file version */
Elf32_Addr e_entry; /* Entry point virtual address */
Elf32_Off e_phoff; /* Program header table file offset */
Elf32_Off e_shoff; /* Section header table file offset */
Elf32_Word e_flags; /* Processor-specific flags */
Elf32_Half e_ehsize; /* ELF header size in bytes */
Elf32_Half e_phentsize; /* Program header table entry size */
Elf32_Half e_phnum; /* Program header table entry count */
Elf32_Half e_shentsize; /* Section header table entry size */
Elf32_Half e_shnum; /* Section header table entry count */
Elf32_Half e_shstrndx; /* Section header string table index */
} Elf32_Ehdr;
typedef struct
{
unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
Elf64_Half e_type; /* Object file type */
Elf64_Half e_machine; /* Architecture */
Elf64_Word e_version; /* Object file version */
Elf64_Addr e_entry; /* Entry point virtual address */
Elf64_Off e_phoff; /* Program header table file offset */
Elf64_Off e_shoff; /* Section header table file offset */
Elf64_Word e_flags; /* Processor-specific flags */
Elf64_Half e_ehsize; /* ELF header size in bytes */
Elf64_Half e_phentsize; /* Program header table entry size */
Elf64_Half e_phnum; /* Program header table entry count */
Elf64_Half e_shentsize; /* Section header table entry size */
Elf64_Half e_shnum; /* Section header table entry count */
Elf64_Half e_shstrndx; /* Section header string table index */
} Elf64_Ehdr;
1.2.2 不同字段详细解释
e_ident
占16个字节。前四个字节被称作ELF的Magic Number。后面的字节描述了ELF文件内容如何解码等信息。
如图,前4个字节是ELF的Magic Number,固定为7f 45 4c 46
。
第5个字节指明ELF文件是32位还是64位的。
第6个字节指明了数据的编码方式,即我们通常说的little endian或是big endian。little endian我喜欢称作小头在前,低位字节在前,或者直接说低位字节在低 位地址,比如0x7f454c46
,存储顺序就是46 4c 45 7f
。big endian就是大头在前,高位字节在前,直接说就是高位字节在低位地址,比如0x7f454c46
,在 文件中的存储顺序是7f 45 4c 46
。
第7个字节指明了ELF header的版本号,目前值都是1。
第8-16个字节,都填充为0。
e_type
,2字节,描述了ELF文件的类型。以下取值有意义:
ET_NONE, 0, No file type
ET_REL, 1, Relocatable file(可重定位文件,通常是文件名以.o结尾,目标文件)
ET_EXEC, 2, Executable file (可执行文件)
ET_DYN, 3, Shared object file (动态库文件,你用gcc编译出的二进制往往也属于这种类型,惊讶吗?)
ET_CORE, 4, Core file (core文件,是core dump生成的吧?)
ET_NUM, 5,表示已经定义了5种文件类型
ET_LOPROC, 0xff00, Processor-specific
ET_HIPROC, 0xffff, Processor-specific
e_machine
,2字节。描述了文件面向的架构,可取值如下(参见/usr/include/elf.h
中的EM_
开头的宏定义):