Structured Exception Handling (SEH) is a Microsoft extension to C designed to handle faults gracefully, with the intention that memory and files can be released correctly when execution is unexpectedly terminated.
There are two types of SEH mechanisms:
- Exception Handlers, or
__except
blocks, which can respond or dismiss an exception - Termination Handlers, or
__finally
blocks, which are always called whether an exception causes termination or not.
When an exception occurs the stack is unwound and the OS looks for the most recent exception handler. As each layer of the stack is unwound the OS calls any termination handlers which have been written for each function, in the process cleaning up any resources which would have otherwise been left open. This might include closing critical sections, releasing mutexes, or freeing memory.
At each stage of the unwinding process the OS checks the latest functions PDATA structure to find out in an exception handler exists.
Offset | Bits | Field | Description |
---|---|---|---|
0 | 31-0 | Begin Address | Virtual address of the corresponding function |
4 | 7-0 | Prolog Length | Number of instructions in the function's prolog |
4 | 29-8 | Function Length | Number of instructions in the function |
4 | 30 | 32-bit Flag | Set if the function uses 32-bit instructions, clear for 16-bit instructions |
4 | 31 | Exception Flag | Set if an exception handler exists for the function |
If an exception handler is flagged to exist or the function length is zero then an additional PDATA_EH
structure will precede the function in the .text
section. This structure will contain pointers to the exception handler and the handler’s data record.
struct PDATA_EH { unsigned int* pHandler; unsigned int* pHandlerData; };