PE File Format Deep Dive
Windows Internals for Low-Level Programming · Windows Programming track
8 min read
In this module
The Portable Executable Format
The PE (Portable Executable) format is the binary container for executables (.exe), DLLs (.dll), drivers (.sys), and other Windows binaries. PE internals are unavoidable if you're doing reverse engineering, malware analysis, exploit development, or trying to understand how the Windows loader works.
PE File Layout
The DOS Header
Every PE file begins with a DOS header for backward compatibility:
typedef struct _IMAGE_DOS_HEADER { WORD e_magic; // "MZ" (0x5A4D) - Mark Zbikowski's initials WORD e_cblp; // Bytes on last page // ... other DOS fields (rarely used) ... LONG e_lfanew; // File offset to PE signature} IMAGE_DOS_HEADER;The only fields that matter for PE parsing are e_magic (must be "MZ") and e_lfanew (offset to the PE signature).
The COFF File Header
typedef struct _IMAGE_FILE_HEADER { WORD Machine; // 0x14C = i386, 0x8664 = AMD64, 0xAA64 = ARM64 WORD NumberOfSections; // Number of section table entries DWORD TimeDateStamp; // Compilation timestamp (Unix epoch) DWORD PointerToSymbolTable; // 0 for images DWORD NumberOfSymbols; // 0 for images WORD SizeOfOptionalHeader; // Size of Optional Header WORD Characteristics; // Flags} IMAGE_FILE_HEADER;
// Characteristics flags:// IMAGE_FILE_EXECUTABLE_IMAGE (0x0002) - File is an executable// IMAGE_FILE_LARGE_ADDRESS_AWARE (0x0020) - Can use >2GB address space// IMAGE_FILE_DLL (0x2000) - File is a DLLBetween the DOS stub and the PE signature, Microsoft's linker embeds an undocumented Rich header containing information about the build environment: which compiler and linker versions were used, and the object files that were linked. The data is XOR-encrypted with a checksum key. The Rich header is useful for malware attribution - different build environments produce different Rich headers, which can link malware samples to the same author or toolchain.
The Optional Header
Despite its name, the Optional Header is required for executables and DLLs:
typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; // 0x20B = PE32+ (64-bit) BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; // RVA of entry point (e.g., WinMain/DllMain) DWORD BaseOfCode; ULONGLONG ImageBase; // Preferred load address DWORD SectionAlignment; // Alignment in memory (typically 4096) DWORD FileAlignment; // Alignment on disk (typically 512) // ... version fields ... DWORD SizeOfImage; // Total size when loaded in memory DWORD SizeOfHeaders; // Size of all headers DWORD CheckSum; // Image checksum (required for drivers) WORD Subsystem; // WINDOWS_GUI, WINDOWS_CUI, NATIVE, etc. WORD DllCharacteristics; // ASLR, DEP, CFG flags // ... stack/heap sizes ... DWORD NumberOfRvaAndSizes; // Usually 16 IMAGE_DATA_DIRECTORY DataDirectory[16]; // Important tables} IMAGE_OPTIONAL_HEADER64;Data Directories
The 16 data directories point to important structures within the PE:
Index Name Purpose───── ─────────────────────── ──────────────────────── 0 Export Table Functions this DLL exports 1 Import Table DLLs and functions imported 2 Resource Table Icons, dialogs, strings, version info 3 Exception Table SEH unwind information (x64) 4 Certificate Table Authenticode digital signatures 5 Base Relocation Table Fixups for ASLR/non-preferred base 6 Debug Directory Debug information (PDB path) 9 TLS Table Thread Local Storage callbacks 11 Bound Import Table Pre-resolved import addresses 12 Import Address Table Runtime import addresses (IAT) 13 Delay Import Table DLLs loaded on first use 14 CLR Runtime Header .NET metadataA data directory is just an RVA and a size, so each one points into the middle of some section. Here's where the common ones land in a typical MSVC-built 64-bit image, and what the loader does when it gets there:
The odd one out is the certificate table. Its "address" is a raw file offset and the signature bytes sit outside every section, which is why appending data to a signed binary is a whole topic of its own.
Section Table
Each section describes a contiguous block of data with uniform permissions:
typedef struct _IMAGE_SECTION_HEADER { BYTE Name[8]; // ".text", ".data", ".rdata", etc. DWORD VirtualSize; // Size in memory DWORD VirtualAddress; // RVA when loaded DWORD SizeOfRawData; // Size on disk DWORD PointerToRawData; // File offset to raw data // ... relocation/line number fields ... DWORD Characteristics; // Flags (read/write/execute)} IMAGE_SECTION_HEADER;Common Sections
.text - Executable code (READ | EXECUTE).rdata - Read-only data: import/export tables, strings (READ).data - Initialized read-write global data (READ | WRITE).bss - Uninitialized data (READ | WRITE, zero size on disk).rsrc - Resources: icons, manifests, version info (READ).reloc - Base relocation entries for ASLR (READ).pdata - Exception handling unwind data for x64 (READ).tls - Thread Local Storage template (READ | WRITE)Import and Export Tables
Import Table
The import table lists all DLLs and functions that the executable needs:
Import Directory:┌─────────────────────────┐│ kernel32.dll ││ ├── CreateFileW ││ ├── ReadFile ││ ├── CloseHandle ││ └── ExitProcess │├─────────────────────────┤│ user32.dll ││ ├── MessageBoxW ││ ├── RegisterClassExW ││ └── CreateWindowExW │└─────────────────────────┘The Import Address Table (IAT) starts as an array of pointers to import name entries. After loading, the loader overwrites each IAT entry with the actual address of the imported function.
Export Table
DLLs use the export table to advertise functions they provide:
Export Table of kernel32.dll:Ordinal Name Address─────── ──────────────────── ────────── 1 AcquireSRWLockExclusive 0x00012340 2 AcquireSRWLockShared 0x00012380 ... 820 CreateFileW 0x0001A200 ...TLS Callbacks
Thread Local Storage callbacks execute before the entry point:
// TLS callbacks run before main() - used by packers and anti-debugvoid NTAPI TlsCallback(PVOID DllHandle, DWORD Reason, PVOID Reserved) { if (Reason == DLL_PROCESS_ATTACH) { // This runs BEFORE WinMain/main // Malware uses this for anti-debugging checks if (IsDebuggerPresent()) ExitProcess(0); }}Most addresses in a PE file are stored as RVAs - offsets from the image base address. When the PE is loaded at its ImageBase (or a different address due to ASLR), the loader adds the actual base to each RVA to get the runtime virtual address. This allows the PE to be loaded at any base address without modifying most internal pointers. Only pointers that cannot be expressed as RVAs require base relocations.
The PE format is the foundation for reverse engineering Windows binaries. Every tool that analyses, packs, unpacks, or instruments executables has to parse these structures. The format also directly shapes security: ASLR relies on the relocation table, DEP depends on section permissions, and Authenticode signatures live in the certificate data directory.