Structured Exception Handling

24
Structured Exception Handling

description

Structured Exception Handling. OVERVIEW. Structured Exception Handling (SEH) provides a robust mechanism for applications to respond to unexpected events Hardware faults Addressing exceptions System errors User generated exceptions SEH assures the ability to free resources Perform clean-up - PowerPoint PPT Presentation

Transcript of Structured Exception Handling

Page 1: Structured Exception Handling

Structured Exception Handling

Structured Exception Handling

Page 2: Structured Exception Handling

– 2 –

OVERVIEWOVERVIEW

Structured Exception Handling (SEH) provides a robust Structured Exception Handling (SEH) provides a robust mechanism for applications to respond to unexpected mechanism for applications to respond to unexpected eventsevents Hardware faults Addressing exceptions System errors User generated exceptions

SEH assures the ability to free resourcesSEH assures the ability to free resources Perform clean-up

SEH simplifies program logicSEH simplifies program logic

Page 3: Structured Exception Handling

– 3 –

PARTSPARTS

Part IPart I Exception HandlersException Handlers

Part IIPart II Termination HandlerTermination Handlerss

Page 4: Structured Exception Handling

PART IPART I

Exception HandlersException Handlers

Page 5: Structured Exception Handling

– 5 –

TRY AND EXCEPT BLOCKSTRY AND EXCEPT BLOCKS

__try__try and and __except__except Keywords recognized by Visual C++ compiler

Actual keywords are specific to the compiler

__try {__try {/* Block of monitored code *//* Block of monitored code */

}}__except (__except (filter_expressionfilter_expression) {) {

/* Exception handling block *//* Exception handling block */}}

Page 6: Structured Exception Handling

– 6 –

SEH, BLOCKS, AND FUNCTIONSSEH, BLOCKS, AND FUNCTIONS{ DWORD x1; /* Block 1 */ ... _try { /* Block 2 */ DWORD x2; .... x2 = f (x1); .... } _except () { /* SEH 2 */ }}DWORD f (DWORD y){ /* Block f */ DWORD z; z = y / (y - 1); return z / y;}

STACK

Windows Exception Handler

Block 1 x1

Block 2x2

SEH 2

Block fyz

Exception OccursExecute this SEH

Page 7: Structured Exception Handling

– 7 –

FILTER EXPRESSIONSFILTER EXPRESSIONS

The The filter_expressionfilter_expression is evaluated after an exception is evaluated after an exception

It is a literal constant, expression, or a function callIt is a literal constant, expression, or a function call

Returns one of three valuesReturns one of three values EXCEPTION_EXECUTE_HANDLER

Normal case

EXCEPTION_CONTINUE_SEARCHThis handler does not process this exception; unwind the stack for

the next exception handler

EXCEPTION_CONTINUE_EXECUTION

Some exceptions cannot be continued, and another exception would occur immediately

Page 8: Structured Exception Handling

– 8 –

EXCEPTION CODES (1 of 2)EXCEPTION CODES (1 of 2)

How do you know what exception occurred? How do you know what exception occurred? And how do you know what filter expression value to generate?

DWORD GetExceptionCode (VOID)DWORD GetExceptionCode (VOID)

The filter function itself cannot call GetExceptionCode, so a common usage is:

__except (MyFilter (GetExceptionCode ())) { . . .__except (MyFilter (GetExceptionCode ())) { . . .

}}

Page 9: Structured Exception Handling

– 9 –

EXCEPTION CODES (2 of 2)EXCEPTION CODES (2 of 2)

An alternative function that returns additional information:An alternative function that returns additional information:

LPEXCEPTION_POINTERSLPEXCEPTION_POINTERS

GetExceptionInformation (VOID)GetExceptionInformation (VOID)

including information on the virtual address causing an including information on the virtual address causing an access violationaccess violation

Page 10: Structured Exception Handling

– 10 –

EXCEPTION CODE VALUES (1 of 2)EXCEPTION CODE VALUES (1 of 2)

1.1. Program violations, including:Program violations, including: EXCEPTION_ACCESS_VIOLATION EXCEPTION_DATATYPE_MISALIGNMENT EXCEPTION_NONCONTINUABLE_EXECUTION

2..2.. Memory allocation exceptions (See Memory allocation exceptions (See CChapter 4)hapter 4)

((HeapAllocHeapAlloc and and HeapCreateHeapCreate)) STATUS_NO_MEMORY

Page 11: Structured Exception Handling

– 11 –

EXCEPTION CODE VALUES (2 of 2)EXCEPTION CODE VALUES (2 of 2)

3.3. User-defined exception codesUser-defined exception codes

4.4. Arithmetic codes, such as:Arithmetic codes, such as: EXCEPTION_INT_DIVIDE_BY_ZERO EXCEPTION_FLT_DIVIDE_BY_ZERO

5.5. Debugger exceptions — Debugger exceptions — EXCEPTION_BREAKPOINTEXCEPTION_BREAKPOINT

Page 12: Structured Exception Handling

– 12 –

EXCEPTION CONTROL FLOWEXCEPTION CONTROL FLOW_try {

. . .i = j / 0;. . .

}_except (Filter (GetExceptionCode ())) {

. . .}

. . .DWORD Filter (DWORD ExCode){

switch (ExCode) {. . .case EXCEPTION_INT_DIVIDE_BY_ZERO:. . .return EXCEPTION_EXECUTE_HANDLER;case . . .}

}

2

6

7

3

5

4

1

Page 13: Structured Exception Handling

– 13 –

USER-GENERATED EXCEPTIONS(1 of 2)USER-GENERATED EXCEPTIONS(1 of 2)

VOID RaiseException (DWORD dwExceptionCode,VOID RaiseException (DWORD dwExceptionCode,DWORD dwExceptionFlags, DWORD cArguments,DWORD dwExceptionFlags, DWORD cArguments,LPDWORD lpArguments)LPDWORD lpArguments)

dwExceptionCodedwExceptionCode bits 31, 30: bits 31, 30:

0 — Success0 — Success 1 — Informational1 — Informational

2 — Warning2 — Warning 3 — Error3 — Error

Bit 29: SetBit 29: Set

Bit 28: 0Bit 28: 0 Bits 27–0: User SpecifiedBits 27–0: User Specified

Typical value: Typical value: 0XE00000060XE0000006

Page 14: Structured Exception Handling

– 14 –

USER-GENERATED EXCEPTIONS(2 of 2)USER-GENERATED EXCEPTIONS(2 of 2)

dwExceptionFlagsdwExceptionFlags — — EXCEPTION_NONCONTINUABLEEXCEPTION_NONCONTINUABLE indicates filter expression should not generateindicates filter expression should not generate

EXCEPTION_CONTINUE_EXECUTIONEXCEPTION_CONTINUE_EXECUTION

lpArgumentslpArguments — If not — If not NULLNULL, points to an array of , points to an array of cArgumentscArguments

EXCEPTION_MAXIMUM_PARAMETERS == 15EXCEPTION_MAXIMUM_PARAMETERS == 15

Page 15: Structured Exception Handling

– 15 –

ReportException Function (1 of 2)ReportException Function (1 of 2)

VOID ReportException (LPCTSTR UserMessage, VOID ReportException (LPCTSTR UserMessage, DWORD ExceptionCode)DWORD ExceptionCode)/* ReportException *//* ReportException *//* Extension of ReportError to generate a user/* Extension of ReportError to generate a user exception code rather than terminating. */exception code rather than terminating. *//* UserMessage: Message to be displayed /* UserMessage: Message to be displayed ExceptionCode: 0 - ReturnExceptionCode: 0 - Return

> 0 - ExitProcess with this code */> 0 - ExitProcess with this code */{{ /* Report as a non-fatal error *//* Report as a non-fatal error */ if (lstrlen (UserMessage) > 0)if (lstrlen (UserMessage) > 0) ReportError (UserMessage, 0, TRUE);ReportError (UserMessage, 0, TRUE);

Page 16: Structured Exception Handling

– 16 –

ReportException Function (2 of 2)ReportException Function (2 of 2)

/* If fatal, raise an exception *//* If fatal, raise an exception */ /* Mask out any high order bits in the *//* Mask out any high order bits in the */ /* user-supplied exception code *//* user-supplied exception code */

if (ExceptionCode != 0)if (ExceptionCode != 0) RaiseException (RaiseException ( (0x0FFFFFFF & ExceptionCode) |(0x0FFFFFFF & ExceptionCode) | 0xE0000000, 0, 0, NULL);0xE0000000, 0, 0, NULL); return;return;}}

Page 17: Structured Exception Handling

– 17 –

ENABLING FLOATING POINT EXCEPTIONS (1 of 2)ENABLING FLOATING POINT EXCEPTIONS (1 of 2)

Skip if you are not interested in floating point arithmeticSkip if you are not interested in floating point arithmetic

To enable floating point exceptions, you need to set the To enable floating point exceptions, you need to set the fp fp maskmask (set the bit off to enable the exception) (set the bit off to enable the exception)

int iFPMask; /* Save old control mask */int iFPMask; /* Save old control mask */iFPMask = _controlfp (0, 0);iFPMask = _controlfp (0, 0);iFPMask &= ~(EM_OVERFLOW | EM_UNDERFLOW |iFPMask &= ~(EM_OVERFLOW | EM_UNDERFLOW | EM_INEXACT | EM_ZERODIVIDE | EM_DENORMAL);EM_INEXACT | EM_ZERODIVIDE | EM_DENORMAL);_controlfp (iFPMask, MCW_EM);_controlfp (iFPMask, MCW_EM); /* Set new control mask*//* Set new control mask*//* Restore the old mask to disable exceptions *//* Restore the old mask to disable exceptions */_controlfp (iFPMask, 0xFFFFFFFF);_controlfp (iFPMask, 0xFFFFFFFF);

Page 18: Structured Exception Handling

– 18 –

ENABLING FLOATING POINT EXCEPTIONS (2 of 2)ENABLING FLOATING POINT EXCEPTIONS (2 of 2)

Formula: Formula: (current_mask & ~mask) | (new & mask)(current_mask & ~mask) | (new & mask)

After a FP exception, clear it with After a FP exception, clear it with _clearfp()_clearfp()

Page 19: Structured Exception Handling

PART IIPART II

Termination HandlersTermination Handlers

Page 20: Structured Exception Handling

– 20 –

TRY-FINALLY BLOCKSTRY-FINALLY BLOCKS

Example:Example: The finally block (almost) The finally block (almost) always exectutesalways exectutes

while (...) __try {while (...) __try { hTemp = CreateFile (TempFileName, ...);hTemp = CreateFile (TempFileName, ...); /* Block of guarded code *//* Block of guarded code */ ...... if (...) break; /* finally block will run */if (...) break; /* finally block will run */ ......}}__finally { /* Executes on every loop iteration */__finally { /* Executes on every loop iteration */ /* termination handler (finally block) *//* termination handler (finally block) */ CloseHandle (hTemp);CloseHandle (hTemp); DeleteFile (TempFileName);DeleteFile (TempFileName);}}

Page 21: Structured Exception Handling

– 21 –

TERMINATION HANDLERSTERMINATION HANDLERS

Executed whenever control flow leaves the try block Executed whenever control flow leaves the try block because of:because of: Reaching the end of the __try block Leaving the block because of execution of:

return break longjump

continue goto __leave

An exception

Executed in the context of the block or function it guardsExecuted in the context of the block or function it guards

Control can pass from end of termination handler to next Control can pass from end of termination handler to next statementstatement

Page 22: Structured Exception Handling

– 22 –

ABNORMAL TERMINATIONABNORMAL TERMINATION

To detect termination for any reason other than reaching the To detect termination for any reason other than reaching the end of the try block—useend of the try block—use

BOOL AbnormalTermination (VOID)BOOL AbnormalTermination (VOID)

to determine how the try block terminatedto determine how the try block terminated

TRUETRUE — For abnormal termination — For abnormal termination

FALSEFALSE — For normal termination — For normal termination

Page 23: Structured Exception Handling

– 23 –

COMBINING FINALLY ANDEXCEPT BLOCKS (1 of 2)COMBINING FINALLY ANDEXCEPT BLOCKS (1 of 2)

__try {__try {

/* Block of guarded code *//* Block of guarded code */

}}

__except (filter_expression) {__except (filter_expression) {

/* Except block *//* Except block */

}}

__finally {__finally {

/* /* You cannot do thisYou cannot do this ! */ ! */

}}

Page 24: Structured Exception Handling

– 24 –

COMBINING FINALLY ANDEXCEPT BLOCKS (2 of 2)COMBINING FINALLY ANDEXCEPT BLOCKS (2 of 2)

__try { /* Outer try-except block */__try { /* Outer try-except block */ while (...) __try { /* Inner try-fin block */while (...) __try { /* Inner try-fin block */ hFile = CreateFile (TempFile, ...);hFile = CreateFile (TempFile, ...); if (...) __try { /* Inner try-ex block */if (...) __try { /* Inner try-ex block */ ...... }} __except (EXCEPTION_EXECUTE_HANDLER) {__except (EXCEPTION_EXECUTE_HANDLER) { ... /* Process FP exception. */ _clearfp();... /* Process FP exception. */ _clearfp(); }} }} __finally { /* End of while loop */__finally { /* End of while loop */ CloseHandle (hFile); DeleteFile (TempFile);CloseHandle (hFile); DeleteFile (TempFile); }}}}__except (__except (filter-expressionfilter-expression) { } ) { }