ELF (Executable and Linking Format).
根据elf文档, elf文件有三种类型:
• A relocatable file holds code and data suitable for linking with other object files to create an executable or a shared object file.
• An executable file holds a program suitable for execution.
• A shared object file holds code and data suitable for linking in two contexts. First, the link editor may process it with other relocatable and shared object files to create another object file.
Second, the dynamic linker combines it with an executable file and other shared objects to
create a process image.
layout
一般来说elf文件有三个部分elf header/section header table/program header table
三种类型的elf文件都具有elf header, relocatable file通常没有program header table, executable通常没有section header table。因为section header table一般用于指导链接而program header table则是用于指导如何加载到内存中运行。通常使用mmap系统调用将内容映射到虚拟内存中。
section header table主要包含
- .text
- .data(初始化数据)
- .rodata
- .bss(未初始化数据)
program header table主要包含
- Load
- INTERP
This segment type is meaningful only for executable files
指明需要使用的linker一般来说是ld.so/ld-linux.so。用于动态链接程序并执行程序 - DYNAMIC
ldd to find shared library used by this program
.a vs .o
在linux上通常用gcc编译可能会碰到的文件有.a / .o / .so / executable
.o文件即为relocatable file,即为一个compilation unit的编译结果, .so文件即为shared object file. .a 文件不属于上述三种文件,而是relocatable file的archive。可以理解为一堆.o文件的集合。
一个生成.a文件的makefile1
2
3
4
5
6
7
8
9
10AR = ar
CC = gcc
objects := hello.o world.o
libby.a: $(objects)
$(AR) rcu $@ $(objects)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
.so vs executable
gcc common symbols
weak/strong/common
common symbol: unitialized global variable without extern is treated as common symbol, compiler will try to merge this symbols and allocate the memory at one location.
note that common only exist in link time, therefore executable file doesn’t have .common
section and these symbols goes to either .bss or .data, depends on whether it is initialized in other files.
linkaege type
global
extern
local(static)
local(static) variables will not be exported as symbols.