ELF serves different stages: compilers generate relocatable object files, linkers combine code and data, and the kernel and dynamic loader establish process images. Debuggers also read symbols and debug information. They access different indices of the same file, rather than a layered structure that must be executed sequentially.
When understanding ELF, first answer three questions: Is this value a file offset or a virtual address? Which stage is this table for? Does this part really need to be mapped into the process?
Two Views, Not a Containment Chain
Sections organize content by purpose: code, data, symbols, relocations, etc. Program headers describe mapping and other runtime requirements, where only PT_LOAD indicates a loadable segment. Multiple sections can be covered by a single PT_LOAD; PT_DYNAMIC, PT_INTERP, etc., may also describe data already within the range of a PT_LOAD. Do not treat these entries as mutually exclusive file partitions.
.dynsym does not "belong to PT_DYNAMIC". PT_DYNAMIC points to an array of dynamic entries, where DT_SYMTAB points to the dynamic symbol table. Runtime resolution does not depend on the section name .dynsym. Read-only data does not necessarily share an executable segment with code; the actual permission layout is determined by linker options. ELF Dynamic Link Structure
ELF Header as the Index Entry
The e_ident at the beginning of the file first explains how to interpret subsequent structures:
Byte/Field
Meaning
0–3
0x7f, E, L, F magic number
EI_CLASS, byte 4
ELF32 or ELF64, determines structure layout
EI_DATA, byte 5
Data byte order
EI_VERSION, byte 6
ELF format version
EI_OSABI, byte 7
Operating system/ABI identifier
EI_ABIVERSION, byte 8
Version corresponding to the ABI; not padding bytes
Subsequent reserved bytes
Should not be interpreted as another set of arbitrarily concatenated fields
In the remaining header, e_machine describes the target architecture, e_entry describes the entry virtual address, and e_phoff/e_shoff are the file offsets of the two tables. The number of entries and their sizes are described by e_*entsize and e_*num; do not infer the target file layout from the host machine's pointer size. elf(5)
e_type
Common Use
Conclusion That Cannot Be Directly Drawn
ET_REL
.o obtained from compilation
Usually cannot be executed directly
ET_EXEC
Usually a non-PIE executable image
Does not mean all addresses in the entire process are fixed
ET_DYN
Shared object, also used for PIE
Does not guarantee ASLR is enabled, nor does it alone prove it is the main program
ET_CORE
Process dump
Does not guarantee it contains all memory and complete debug information
Whether PIE is enabled by default depends on the toolchain and distribution configuration. Explicitly using -fPIE -pie is more convenient for teaching experiments; when checking results, combine program headers, dynamic flags, and tool interpretations, and do not rely solely on the file extension.
PT_LOAD: How File Content Corresponds to Memory
Let the load offset be B. The main fields of a PT_LOAD are: p_offset (file start), p_vaddr (linking perspective virtual start), p_filesz (file content length), p_memsz (memory length), p_flags (read/write/execute permissions), and p_align (alignment constraints).
For the file-supported region of this segment, the runtime address corresponding to file offset f is:
runtime_address = B + p_vaddr + (f - p_offset)
This requires f to be within the file range of this segment. p_memsz must be no less than p_filesz; the excess memory area is initialized to zero; when p_align is greater than 1, it must be a corresponding power-of-two alignment value, p_vaddr and p_offset satisfy congruence requirements, and loading also needs to satisfy page alignment rules. ELF Program Loading
For example, for a read-write segment with p_offset=0x3000, p_vaddr=0x5000, p_filesz=0x600, p_memsz=0xa00: the file range [0x3000, 0x3600) corresponds to memory [B+0x5000, B+0x5600), and the subsequent [B+0x5600, B+0x5a00) is zero. File offset 0x3120 corresponds to B+0x5120.
Actual mapping is handled in pages; zeroing the page containing the end of the file and subsequent anonymous pages may require different steps. Do not directly treat p_memsz as the file mapping length and assume that everything after the end of the file naturally conforms to ELF zero-filling semantics.
When Reverse-Looking Up Addresses, First Determine Which Region It Belongs To
Assume the debugger provides a runtime address r, and it is known to belong to this ELF image. First, subtract the load offset of this image B to get the linking virtual address v. Then, look up the PT_LOAD that covers v, and only then attempt to convert to a file offset. The main program of the same process and different shared libraries each have their own load offsets; do not use the main program's B to interpret addresses in libc.
Below, we only calculate the address classification for the aforementioned single segment, without reading the ELF or simulating page tables. Using half-open intervals allows direct checking of the two most error-prone boundaries.
If v is 0x5800, mechanically substituting into the formula yields file offset 0x3800, but that location is not the initial data source for that address; even if other file content exists there, it cannot be used to interpret this zero-initialized memory. Conversely, the file classification only describes the initial source of the image: after relocation or program writes, runtime bytes may no longer match the disk.
One address, three coordinates
Classify Δ before applying a conversion. Both bands share the same segment-relative scale: file bytes stop at 0x600, memory continues to 0xa00. Crossing that boundary removes file provenance without removing the runtime address. Changing B leaves provenance unchanged.
Δ=r−B−pvaddr,f=poffset+Δ(0≤Δ<pfilesz)
Preparing the visual
One address, three coordinates
Only the file-backed region has source bytes. The zero-filled tail has no corresponding file byte; load bias shifts runtime addresses.
Quick Reference for Common Sections by Responsibility
Responsibility
Common Names
Key Reading Points
Program Content
.text, .rodata, .data
Whether it has SHF_ALLOC, and the final segment permissions
Zero-Initialized Storage
.bss, SHT_NOBITS
Has memory size, but no equally sized valid payload in the file
Symbols
.symtab, .dynsym
Different roles for regular symbol table and runtime dynamic symbol table
Names
.strtab, .dynstr, .shstrtab
String offsets must correspond to the correct string table
Relocations
.rel., .rela.
REL and RELA store addends differently
Dynamic Information
.dynamic, .interp
Dependencies, symbol addresses, interpreter path, etc.
Initialization
.init_array, .fini_array
Usually stores function pointers, not equal to the instruction content of .init/.fini
Debugging
.debug_*
Usually not loaded, may be split into separate debug files
sh_name is an offset within the section name string table, not a pointer. The interpretation of sh_link and sh_info depends on the section type; for example, relocation tables need to associate with the symbol table and target section, and cannot be given a global fixed meaning.
An executable ELF without a section header table may still run if it meets loading requirements; this does not mean it is safe to delete arbitrary bytes. strip usually removes some symbols or debug information; content still needed for dynamic relocation must be retained. Debugging can also rely on matching independent debug files; it is not accurate to simply say "core dumps are unanalyzable after strip".
The output should be 7 and 0. First, find .data/.bss in the -SW output, then look at the Section to Segment mapping at the end of -lW, and finally compare the FileSiz and MemSiz of the corresponding LOAD. Do not assume there are exactly two LOADs, and do not copy addresses from another machine.
Stop the Same Source Code at Three Different Stages
In Linux GCC/Clang toolchains that support these options, continue building the following artifacts. Here, PIE and non-PIE are explicitly specified to avoid distribution defaults affecting the comparison.
ET_EXEC can also be dynamically linked, so "non-PIE" and "static linking" are two different issues. When comparing initialized, read it together with Ndx: Value=0 in ET_REL may simply mean the variable is at the beginning of .data; Value=0 for an undefined printf does not mean the function is located at address zero. TLS symbols have specific offset meanings, and not all st_value should be directly added to B. ELF Symbol Values
Why BSS Size Is Not Directly Added to the File
zeros has 8192 bytes, but its initial content can be expressed by "size and zeroing rules" without storing 8192 zeros in the file. Use readelf -SW to check the NOBITS type and Size of .bss, and then use readelf -lW to view the MemSiz and FileSiz of the writable LOAD. The difference may also include alignment and other zero-initialized objects, so it does not need to exactly equal 8192.
The total file size also includes ELF tables, debug information, symbols, and padding; it cannot be replaced by simply summing the FileSiz of all LOADs; segment ranges themselves are not guaranteed to be mutually exclusive partitions. Similarly, MemSiz expresses the virtual memory requirements of the image and does not directly give the number of physical pages currently resident in the process. Understanding these quantities allows one to distinguish between "large disk file size", "large address space", and "large current physical memory usage".
When Writing a Parser, First Guard Structural Boundaries
Casting a file buffer directly to Elf64_Ehdr* ignores byte order, alignment, truncation, and ELF32. Reliable parsing should first verify e_ident, read fields according to the target encoding, and then check if offsets and lengths are within the file range; checking for multiplication and addition overflows should occur before access.
Quantity fields also have extended encoding: e_phnum's PN_XNUM, e_shnum's extended value, and SHN_XINDEX need to be decoded in conjunction with section 0. String tables should also verify offsets and termination boundaries. "Reading 64 bytes and printing a few fields" in teaching is only format recognition, not a complete ELF validator.
String Offsets Also Need to Be Interpreted Within Their Own Table
For example, if the string table is b"\0.text\0.data\0", offset 1 corresponds to .text, and offset 7 corresponds to .data. Offsets are allowed to point to the middle of an existing string; offset 2 corresponds to text; do not only accept the start of strings previously scanned. Reading must find a NUL within the boundaries of this single table, and cannot scan continuously into subsequent sections. ELF String Table
defread_name(table,offset):ifnot0<=offset<len(table):raiseValueError("string offset outside table")end=table.find(b"\0",offset)ifend==-1:raiseValueError("unterminated name")returntable[offset:end]# Keep original bytes, do not assume name is UTF-8
table=b"\0.text\0.data\0"assertread_name(table,0)==b""assertread_name(table,1)==b".text"assertread_name(table,2)==b"text"assertread_name(table,7)==b".data"fordata,offsetin[(table,-1),(table,len(table)),(b"\0bad",1)]:try:read_name(data,offset)exceptValueError:passelse:raiseAssertionError("invalid name accepted")
This function is only responsible for single name reading; file-level parsing still needs to verify the position, length, and structural rules of the entire string table. Section names use the table specified by e_shstrndx, and symbol names use the string table associated with the corresponding symbol table. Identical offset values do not mean identical names.
Next, use Dynamic Linking to understand how symbols become addresses, and then use Loading and Startup to track when these addresses are used.