Structured Exception Handling (SEH)
Windows Internals for Low-Level Programming · Windows Programming track
9 min read
In this module
Exception Handling on Windows
Structured Exception Handling (SEH) is the Windows mechanism for handling both hardware exceptions (access violations, divide by zero) and software exceptions. Unlike C++ exceptions — which are language-specific — SEH is baked into the OS and works with any language that generates native code. It's unavoidable territory for debugging, exploit development, and Windows internals.
SEH Syntax: __try/__except/__finally
#include <windows.h>#include <stdio.h>
void DemonstrateExceptionHandling(void) { __try { // Protected code int *p = NULL; *p = 42; // Access violation! } __except (EXCEPTION_EXECUTE_HANDLER) { // Exception handler printf("Caught access violation!\n"); printf("Exception code: 0x%08X\n", GetExceptionCode()); }}
void DemonstrateFinally(void) { HANDLE hFile = INVALID_HANDLE_VALUE;
__try { hFile = CreateFile("test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) return; // __finally still runs!
// ... do work ... // Even if an exception occurs, __finally runs } __finally { // Cleanup code - ALWAYS runs if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); printf("Cleanup complete (abnormal=%d)\n", AbnormalTermination()); }}The Filter Expression
The __except block takes a filter expression that determines how to handle the exception:
__except (FilterFunction(GetExceptionInformation())) { // Handler body}
// Filter return values:// EXCEPTION_EXECUTE_HANDLER (1) - Run the handler// EXCEPTION_CONTINUE_SEARCH (0) - Pass to next handler in chain// EXCEPTION_CONTINUE_EXECUTION (-1) - Retry the faulting instruction
LONG FilterFunction(PEXCEPTION_POINTERS ep) { DWORD code = ep->ExceptionRecord->ExceptionCode; PCONTEXT ctx = ep->ContextRecord;
switch (code) { case EXCEPTION_ACCESS_VIOLATION: printf("Access violation at %p\n", ep->ExceptionRecord->ExceptionAddress); // Check if read or write: // ep->ExceptionRecord->ExceptionInformation[0] // 0 = read, 1 = write, 8 = DEP violation return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_INT_DIVIDE_BY_ZERO: return EXCEPTION_EXECUTE_HANDLER;
default: return EXCEPTION_CONTINUE_SEARCH; // Not our problem }}The Exception Dispatch Process
When an exception occurs, Windows follows a specific dispatch sequence:
Trace a null-pointer write through it. With no debugger and no handlers of your own, it drops through VEH and every SEH frame until the outermost one, which the thread start-up code installed for you. That frame calls UnhandledExceptionFilter, and you get the familiar "has stopped working" dialog. Run the same program under a debugger and that filter steps aside, so the debugger gets its second chance instead.
A debugger gets two opportunities to handle an exception. The first-chance notification occurs before any user-mode handler runs - the debugger can choose to handle it or pass it on. If all handlers decline, the debugger gets a second-chance notification, which usually means the process is about to terminate. In a debugger, you typically pass first-chance exceptions (let the program handle them) and break on second-chance exceptions (unhandled = bug).
Vectored Exception Handling (VEH)
VEH (added in Windows XP) provides process-wide exception handlers that run before the frame-based SEH chain:
LONG CALLBACK VectoredHandler(PEXCEPTION_POINTERS ep) { if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) { printf("VEH caught access violation at %p\n", ep->ExceptionRecord->ExceptionAddress); return EXCEPTION_CONTINUE_SEARCH; // Let SEH handle it } return EXCEPTION_CONTINUE_SEARCH;}
// Register at process startupPVOID handle = AddVectoredExceptionHandler( 1, // 1 = first in list, 0 = last VectoredHandler);
// Remove when doneRemoveVectoredExceptionHandler(handle);VEH is used by:
- Crash reporters: Catch unhandled exceptions and generate reports
- JIT compilers: Handle access violations for guard pages (growing stacks)
- Anti-cheat systems: Monitor for certain exception patterns
- Debuggers: Intercept exceptions before the application sees them
The SEH Chain (x86 32-bit)
On 32-bit x86, SEH uses a linked list of handler records stored on the stack:
Thread Stack:┌──────────────────┐│ SEH Frame 3 │ ← fs:[0] points to current frame│ Next: Frame 2 ││ Handler: func3 │├──────────────────┤│ Local vars │├──────────────────┤│ SEH Frame 2 ││ Next: Frame 1 ││ Handler: func2 │├──────────────────┤│ Local vars │├──────────────────┤│ SEH Frame 1 ││ Next: 0xFFFFFFFF│ (end of chain)│ Handler: func1 │└──────────────────┘typedef struct _EXCEPTION_REGISTRATION_RECORD { struct _EXCEPTION_REGISTRATION_RECORD *Next; PEXCEPTION_HANDLER Handler;} EXCEPTION_REGISTRATION_RECORD;SEH Exploitation
The SEH chain on 32-bit x86 has historically been a prime target for exploit developers:
SEH Overwrite Attack
Normal stack: After buffer overflow:┌─────────────┐ ┌─────────────┐│ SEH Handler │ → legit │ SEH Handler │ → shellcode addr│ SEH Next │ → next │ SEH Next │ → junk├─────────────┤ ├─────────────┤│ Buffer[256] │ │ AAAAAAAAAA │ ← overflow│ │ │ AAAAAAAAAA │ overwrites│ │ │ AAAAAAAAAA │ SEH frame└─────────────┘ └─────────────┘When the overflow triggers an exception (often by overwriting further up the stack), the exception dispatcher walks the SEH chain and calls the overwritten handler - which now points to attacker-controlled code.
Mitigations
- SafeSEH: Compiler generates a list of valid handler addresses. The dispatcher checks that the handler address is in the SafeSEH table before calling it.
- SEHOP (SEH Overwrite Protection): Validates the integrity of the SEH chain by checking that the last entry has the expected sentinel value.
- x64 table-based SEH: On 64-bit Windows, SEH is entirely table-based (stored in .pdata section), not stack-based. There is no SEH chain on the stack to overwrite, so the classic attack has nothing to aim at on 64-bit. 32-bit processes running under WOW64 still use the stack-based chain.
On 64-bit Windows, exception handling uses a table-based approach instead of the stack-based chain used on 32-bit. The .pdata section contains RUNTIME_FUNCTION entries that map code address ranges to unwind information and exception handlers. When an exception occurs, the dispatcher uses the instruction pointer to look up the correct handler in the table. Since no handler information is stored on the stack, there's no handler pointer for a stack overflow to overwrite in 64-bit code. Attackers go after other targets instead, such as return addresses or function pointers, and 32-bit code under WOW64 still uses the old stack-based chain.
x64 Exception Handling Internals
On x64, every function that allocates stack space, saves nonvolatile registers or calls another function (anything but a leaf function) needs a RUNTIME_FUNCTION entry, whether or not it handles exceptions, because the unwinder can't walk past it otherwise:
typedef struct _RUNTIME_FUNCTION { DWORD BeginAddress; // RVA of function start DWORD EndAddress; // RVA of function end DWORD UnwindData; // RVA of UNWIND_INFO} RUNTIME_FUNCTION;
typedef struct _UNWIND_INFO { UBYTE Version : 3; UBYTE Flags : 5; // UNW_FLAG_EHANDLER, UNW_FLAG_UHANDLER UBYTE SizeOfProlog; UBYTE CountOfCodes; UBYTE FrameRegister : 4; UBYTE FrameOffset : 4; UNWIND_CODE UnwindCode[]; // Stack unwind operations // Followed by: exception handler RVA and language-specific data} UNWIND_INFO;The table-based approach is more secure, more efficient (no stack-based setup cost for each __try block), and enables the system to unwind stacks correctly for debugging and crash reporting.
SEH matters for exploit development on 32-bit targets, for understanding how Windows handles errors internally, for writing code that survives hardware exceptions cleanly, and for making sense of crash dumps. The shift from stack-based to table-based SEH is a clean case study in how a widely-exploited design flaw forces fundamental architectural change.