Post

Windows Exceptions: Dispatching, SEH and VEH

How Windows turns a CPU fault or an explicit RaiseException into a call to a handler: hardware and software exceptions, the EXCEPTION_RECORD, the kernel-to-user dispatch through KiUserExceptionDispatcher, frame-based Structured Exception Handling on x86 and table-based unwinding on x64, vectored exception handlers, and the related mitigations and telemetry.

Windows Exceptions: Dispatching, SEH and VEH

Introduction

An exception is an event that interrupts the normal flow of a thread: an access to an invalid address, a division by zero, a breakpoint, or an explicit request made by the program. Windows handles every exception, from the CPU or from software, through one mechanism: Structured Exception Handling (SEH).1

SEH has two notable properties:

  • it is implemented by the operating system, in the kernel and in ntdll.dll, not by a particular compiler or runtime;
  • it is language-agnostic: the C __try/__except extension, C++ exceptions in MSVC and the exceptions of managed runtimes are all built on top of it.

This article follows an exception from the moment it is raised to the moment a handler runs, on x86 and on x64, and then describes vectored exception handling.

Exception types

Kind Origin Examples
Software exceptions Raised explicitly by code through RaiseException or an equivalent primitive C++ throw in MSVC (code 0xE06D7363), application-defined codes
Hardware exceptions Raised by the CPU as a fault or a trap, then translated by the kernel into an exception code See below

The most common hardware exceptions and their codes are:2

Condition Exception code
Access violation: read, write or execute of an invalid address EXCEPTION_ACCESS_VIOLATION (0xC0000005)
Stack overflow: the thread touched the guard page at the end of its stack EXCEPTION_STACK_OVERFLOW (0xC00000FD)
Integer division by zero EXCEPTION_INT_DIVIDE_BY_ZERO (0xC0000094)
Breakpoint: the INT 3 instruction EXCEPTION_BREAKPOINT (0x80000003)
Single step: the trap flag is set EXCEPTION_SINGLE_STEP (0x80000004)
Invalid instruction EXCEPTION_ILLEGAL_INSTRUCTION (0xC000001D)

In C and C++ compiled with MSVC, SEH is exposed through the __try and __except keywords:3

1
2
3
4
5
6
7
__try {
    int* volatile ptr = NULL;
    *ptr = 42;                       // access violation: 0xC0000005
}
__except (EXCEPTION_EXECUTE_HANDLER) {
    printf("Exception caught: 0x%08X\n", GetExceptionCode());
}

The expression in __except is the filter. It decides what happens to the exception and evaluates to one of three values:

Filter value Meaning
EXCEPTION_EXECUTE_HANDLER (1) This handler takes the exception: the stack is unwound and the __except block runs
EXCEPTION_CONTINUE_SEARCH (0) Not handled here: the search continues with the next handler
EXCEPTION_CONTINUE_EXECUTION (-1) The condition has been fixed: execution resumes at the faulting instruction

From the CPU to the handler

The EXCEPTION_RECORD

Whatever its origin, an exception is described by an EXCEPTION_RECORD, paired with a CONTEXT that holds the register state of the thread at the moment of the exception:2

Field Content
ExceptionCode The exception code, such as 0xC0000005
ExceptionFlags For example EXCEPTION_NONCONTINUABLE
ExceptionRecord Pointer to a chained record, for nested exceptions
ExceptionAddress The address where the exception occurred (the value of EIP/RIP)
NumberParameters, ExceptionInformation[] Code-specific data; for an access violation, the kind of access and the faulting address

Handlers receive both structures through an EXCEPTION_POINTERS structure, which is also what GetExceptionInformation returns inside a filter.

Kernel dispatch

The path of a user-mode exception is the same on x86 and x64 (Figure 1):4

flowchart TB
    A["CPU fault or trap, or NtRaiseException"] --> D["Kernel trap handler, then KiDispatchException<br/>builds EXCEPTION_RECORD and CONTEXT"]
    D --> E{"Debugger attached?"}
    E -->|"first chance"| DBG["Debugger may handle it"]
    E -->|"no, or not handled"| F["Thread redirected to<br/>ntdll!KiUserExceptionDispatcher"]
    F --> H["RtlDispatchException:<br/>vectored exception handlers"]
    H -->|"continue search"| I["Frame-based handlers (SEH)"]
    I -->|"handled"| R["Resume execution"]
    H -->|"continue execution"| R
    I -->|"not handled"| J["Second chance: debugger,<br/>then unhandled exception filter / WER"]
    J --> K["Process terminated"]

Figure 1. Dispatch of a user-mode exception.

  1. The CPU detects the condition and transfers control to the corresponding kernel trap handler (for example, the page fault handler for an access violation). A software exception reaches the same point through the NtRaiseException system call.
  2. KiDispatchException builds the EXCEPTION_RECORD and the CONTEXT. If a user-mode debugger is attached, it receives a first-chance notification.
  3. The kernel copies both structures to the user-mode stack of the thread and changes its instruction pointer so that, when the thread returns to user mode, it starts executing ntdll!KiUserExceptionDispatcher. The kernel does not call the handlers itself: it redirects the thread.
  4. KiUserExceptionDispatcher calls RtlDispatchException, which first calls the vectored exception handlers, then searches the frame-based handlers of the thread.
  5. If no handler takes the exception, it is raised again for a second chance: the debugger, if any, is notified again; otherwise the unhandled exception filter runs, Windows Error Reporting collects the crash and the process is terminated.

How step 4 finds the frame-based handlers is the main difference between x86 and x64.

SEH on x86: a linked list on the stack

On 32-bit x86, SEH is frame-based. Every function that contains a __try block pushes an exception registration record on its stack frame: two pointers, one to the next record and one to the handler function.4 The records form a linked list that follows the nesting of the call stack (Figure 2).

flowchart TB
    TEB["TEB: NtTib.ExceptionList, at FS:[0]"] --> R1
    R1["Registration record, innermost frame<br/>Next, Handler"] -->|"Next"| R2
    R2["Registration record<br/>Next, Handler"] -->|"Next"| R3
    R3["Registration record, outermost frame<br/>Next, Handler"] -->|"Next"| END["0xFFFFFFFF: end of list"]

Figure 2. The x86 SEH chain, rooted in the TEB.

The head of the list is stored in the Thread Environment Block, in the ExceptionList field of the NT_TIB. On x86 the FS segment register points to the TEB, so the head is at FS:[0].

When an exception is dispatched, RtlDispatchException walks the list from the head and calls each handler. The handler, usually the compiler’s language-specific routine such as _except_handler4, evaluates the filter of the corresponding __except and returns a disposition:

  • ExceptionContinueSearch: pass to the next record;
  • ExceptionContinueExecution: resume at the faulting instruction;
  • if the filter returned EXCEPTION_EXECUTE_HANDLER, the handler does not return: it starts the unwind.

Exception handling is therefore done in two phases. In the search phase, handlers are asked in turn whether they take the exception. In the unwind phase (RtlUnwind), the records between the top of the stack and the selected one are called again with an unwinding flag, which runs the __finally blocks and destructors, and are then removed from the list. Finally, the __except block of the selected handler executes.

Why the x86 model needed mitigations

Because the registration records are stored on the stack together with local variables and buffers, a stack buffer overflow can overwrite them and redirect the handler pointer. Windows and the MSVC toolchain added two mitigations:5

  • SafeSEH (/SAFESEH): the linker records in the image a table of valid handlers, and the dispatcher refuses to call a handler that is not in it.
  • SEHOP (Structured Exception Handling Overwrite Protection): before dispatching, the system verifies that the chain is intact and ends with a known final handler.

SEH on x64: table-based unwinding

On x64 the stack no longer contains exception registration records. Exception handling is table-based: the compiler generates, at build time, a description of every function that allocates stack space or has a handler, and stores it in the image (Figure 3).6

flowchart LR
    subgraph PDATA[".pdata: RUNTIME_FUNCTION table"]
        direction TB
        RF1["BeginAddress RVA<br/>EndAddress RVA<br/>UnwindInfoAddress RVA"]
        RF2["BeginAddress RVA<br/>EndAddress RVA<br/>UnwindInfoAddress RVA"]
    end
    subgraph XDATA[".xdata: UNWIND_INFO"]
        direction TB
        UI["Prolog size, frame register<br/>Unwind codes"]
        EH["Exception handler RVA<br/>Language-specific data (scope table)"]
    end
    RF1 --> UI
    UI --- EH
    STACK["Stack: only locals and<br/>return addresses"]

Figure 3. The x64 exception directory: .pdata entries pointing to unwind information.

  • The .pdata section (the exception directory of the PE file) is a sorted array of RUNTIME_FUNCTION entries. Each entry holds the start and end RVA of a function and the RVA of its unwind information.
  • The UNWIND_INFO structure, usually in .xdata, describes how the function’s prolog modified the stack (the unwind codes) and, if the function has a handler, the RVA of the language-specific handler and its data, such as the scope table of the __try blocks.

The dispatcher uses these tables instead of a linked list (Figure 4):

flowchart TB
    A["RIP from the CONTEXT"] --> B["RtlLookupFunctionEntry:<br/>find the RUNTIME_FUNCTION by RVA"]
    B --> C{"Handler in<br/>UNWIND_INFO?"}
    C -->|"yes"| D["Call the language handler"]
    C -->|"no, or continue search"| E["RtlVirtualUnwind:<br/>compute the caller's frame"]
    D -->|"continue search"| E
    E --> B
    D -->|"execute handler"| F["Unwind and run the __except block"]

Figure 4. Handler lookup on x64.

  1. RtlDispatchException starts from the instruction pointer saved in the CONTEXT, and looks up its RUNTIME_FUNCTION in the .pdata of the image that contains it, with a binary search on the RVA.
  2. If the function has a handler, the dispatcher calls it, exactly as on x86.
  3. Otherwise, or if the handler continues the search, it applies the unwind codes to the CONTEXT (RtlVirtualUnwind). This recovers the return address and registers of the caller, and the process repeats for the caller’s frame.

The stack is still walked frame by frame, but virtually, using read-only metadata from the image, without following pointers stored on the stack. This has two consequences:

  • zero cost on the normal path: entering a __try block executes no instructions to register a handler;
  • no handler pointers on the stack: the overwrite problem that SafeSEH and SEHOP address on x86 does not exist in this form.

Code generated at run time, for example by a JIT compiler, has no .pdata. It must register its unwind information with RtlAddFunctionTable or RtlInstallFunctionTableCallback, otherwise exceptions cannot be dispatched through it.7

Vectored Exception Handling

Vectored Exception Handling (VEH), introduced in Windows XP, is a second, independent mechanism. Its handlers are:8

  • registered at run time, with AddVectoredExceptionHandler, and removed with RemoveVectoredExceptionHandler;
  • process-wide, not tied to a function or a stack frame;
  • called before any frame-based handler, for every exception in every thread of the process.
1
2
3
4
5
6
7
8
9
10
11
LONG CALLBACK MyExceptionHandler(PEXCEPTION_POINTERS info)
{
    if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
        // log, then let the frame-based handlers decide
    }
    return EXCEPTION_CONTINUE_SEARCH;
}

PVOID cookie = AddVectoredExceptionHandler(1, MyExceptionHandler);
// ...
RemoveVectoredExceptionHandler(cookie);

The first parameter selects the position of the new handler in the list: non-zero inserts it at the head (called first), zero at the tail (called last). The handler returns EXCEPTION_CONTINUE_SEARCH to pass the exception on, or EXCEPTION_CONTINUE_EXECUTION to resume the thread with the (possibly modified) CONTEXT. The list is kept by ntdll.dll in the process’s memory. A related API, AddVectoredContinueHandler, registers handlers that are called when execution is about to continue.8

VEH is used by debuggers and diagnostic tools, by crash reporters that need to see every exception, and by runtimes that rely on hardware exceptions for their own purposes, such as guard pages or null-check elimination.

Telemetry and hardening

Exceptions themselves are not logged, but their consequences are:

Source Event Use
Application log 1000 Application Error9 An unhandled exception terminated a process: image, faulting module, exception code, offset
Application log 1001 Windows Error Reporting Crash report bucket, with the path of the collected dump
WER LocalDumps Crash dumps on disk10 Post-mortem analysis of repeated crashes

Repeated access violations in the same network-facing service, or crashes in modules that should never fault, can be the visible side of exploitation attempts and deserve the same attention as a security alert.

On the hardening side:

Control Effect
SEHOP Validates the x86 SEH chain before dispatch; configurable per process through Exploit Protection (Set-ProcessMitigation)11
SafeSEH Link 32-bit images with /SAFESEH so that only registered handlers can run
Control Flow Guard Validates indirect calls, including those to handlers and callbacks12
Build for x64 Table-based exception handling removes handler pointers from the stack

Summary

Windows handles hardware faults and software exceptions through a single mechanism. The kernel captures the exception in an EXCEPTION_RECORD and a CONTEXT, offers it to an attached debugger, and redirects the thread to ntdll!KiUserExceptionDispatcher, which calls the vectored handlers first and then the frame-based handlers. On x86, frame-based handlers form a linked list of registration records on the stack, rooted at FS:[0], and need SafeSEH and SEHOP to resist overwrites. On x64, the compiler emits .pdata and unwind information, and the dispatcher finds handlers by RVA lookup and virtual unwinding, with no cost on the normal path and no handler pointers on the stack. VEH adds process-wide handlers registered at run time. When no handler takes an exception, Windows Error Reporting records the crash, which gives defenders a source of telemetry often overlooked.

References

  1. Microsoft Learn, Structured Exception Handling. ↩︎

  2. Microsoft Learn, EXCEPTION_RECORD structure (winnt.h). ↩︎ ↩︎2

  3. Microsoft Learn, try-except statement. ↩︎

  4. A. Allievi, A. Ionescu, M. Russinovich, D. Solomon, Windows Internals, Part 2, 7th edition, Microsoft Press, 2021, chapter 8 (Exception dispatching). ↩︎ ↩︎2

  5. Microsoft, Preventing the Exploitation of Structured Exception Handler (SEH) Overwrites with SEHOP. ↩︎

  6. Microsoft Learn, x64 exception handling. ↩︎

  7. Microsoft Learn, RtlAddFunctionTable function (winnt.h). ↩︎

  8. Microsoft Learn, Vectored Exception Handling. ↩︎ ↩︎2

  9. Microsoft Learn, Windows Error Reporting. ↩︎

  10. Microsoft Learn, Collecting User-Mode Dumps. ↩︎

  11. Microsoft Learn, Customize exploit protection. ↩︎

  12. Microsoft Learn, Control Flow Guard for platform security. ↩︎

This post is licensed under CC BY 4.0 by the author.