研究这一块的必须工具:
readelf
-h
将可执行文件内的内容读出来 比如: riscv 的readelf -h 如下:
readelf -h Hello (riscv bin)
ELF 头:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
类别: ELF64
数据: 2 补码,小端序 (little endian)
Version: 1 (current)
OS/ABI: UNIX - System V
ABI 版本: 0
类型: EXEC (可执行文件)
系统架构: RISC-V
版本: 0x1
入口点地址: 0x278be
程序头起点: 64 (bytes into file)
Start of section headers: 609704 (bytes into file)
标志: 0x5, RVC, double-float ABI
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 9
Size of section headers: 64 (bytes)
Number of section headers: 19
Section header string table index: 17
上面是riscv的elf头文件. x86_64的elf文件源代码: cat elf.c:
int main(){
printf("Hello Wrold\n");
}
下面是x86_64 的elf文件展出:
readelf -h elf
ELF 头:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
类别: ELF64
数据: 2 补码,小端序 (little endian)
版本: 1 (current)
OS/ABI: UNIX - System V
ABI 版本: 0
类型: DYN (共享目标文件)
系统架构: Advanced Micro Devices X86-64
版本: 0x1
入口点地址: 0x530
程序头起点: 64 (bytes into file)
Start of section headers: 8696 (bytes into file)
标志: 0x0
本头的大小: 64 (字节)
程序头大小: 56 (字节)
Number of program headers: 9
节头大小: 64 (字节)
节头数量: 34
字符串表索引节头: 33
ELF Magic tag表明这是一个elf文件,如果没有这16个字节,则就不是elf文件。
-S
hexdump
根据上一个工具readelf读出相应地址的内容 ?
objdump
反汇编代码
ELF 简介
请先参考这篇文章 ELF(Executable and Linking Format)是一种对象文件格式,从名字上我们也能窥探出 他的作用来。这里主要三种类型的。
1 可重定位(relocalable)
2 可执行文件(Exectuable)
3 共享目标文件(shared object file)
gcc生成的object文件在linking和Execution的角度来看是不一样的。 先说在Linking的角度:
linking view _________________ | ELF Header | |----------------| |Program Header | | Table Optional | |----------------| | Section 1 | |----------------| | ... | |----------------| | Section n | |----------------| |Section Header | | Table | |----------------|
还是在这里分开吧
Executeable View |----------------| | ELF Header | |----------------| | Program Header | | Table | |----------------| | | | segment 1 | |----------------| | | | segment 2 | |----------------| | ... | |----------------| | section Header | | Table Optional | |________________|
其实上面的图示忽略了一点,即segment是由多个Section组成的。
在这两种的观点来看,都是包含着指令、数据、符号表、重定位等信息。 program header table 告诉系统如何创造一个进程镜像 .在链接阶段必须有一个 section header table.
as
as输出的目标文件至少有三个section,他们是text,data,bss段。你如果不写出.text 或者.data段,但是目标文件依然会有他们,只不过是空的。
update: as 汇编器连接的.S文件生成的是.o文件,这是一个重定位文件 然后才是ld的任务生成可执行文件,当生成了可执行文件, 以静态连接为例,作为ld的输入文件,可重定位文件x.o的包含了好几个sections:指令 、被初始化的全局变量、未初始化的变量。
./p
会激活装载器(loader),它的作用是将可执行文件中的数据和代码复制到内存中去。 然后开始执行程序
Address 0 ---->|--------------| | .text | |______________| | .data | |______________| | .bss | |______________|
#