24th SEH Structured Exception handling-exception handling and software exceptions

Source: Internet
Author: User
Tags finally block

24.1 structure of the program

(1) try/except frame

__try{   // protected code block ...        } __except (except Fileter/* Exception filtering program */    ) {// Exception handler }

(2) Description

① the filter in __except () is called when the code in the __try block has an exception.

The ② filter can be a simple expression or a function (the return value should be one of exception_continue_search, Except_continue_execute, or Except_execute_handler)

The ③ filter expression can call the GetExceptionCode and getexceptioninformation functions to get the exception information being processed. However, these two functions cannot be used in an exception handler.

Unlike try/finally, ④ can use return, Goto, continue, and break in try/except, and they do not cause partial expansion.

24.2 Exception Filtering Program

(1) Return value

Identity

Value

Description

Exception_execute_handler

1

Executes the except curly braces code while performing a global expansion. Finally, the program proceeds from the first line of code that follows the except Curly brace.

Exception_continue_search

0

Look for the try block with except in the outer layer and call the corresponding exception filter program.

Exception_continue_execute

-1

Re-executes the CPU instruction itself that caused the exception.

(2) Global expansion -- The exception filter returns Exception_execute_handler is a global open .

① when the code in a __try block triggers an exception (or it could be an exception thrown in a function called in a __try block), the operating system will start looking for the __except block from the lower level (where the layer refers to the nesting layer of the __try block) from the next place where the exception code is raised, for each __ Except block, it calculates its exception filter first, if the filter returns Exception_continue_search, then this __except block does not handle such an exception, you need to continue to find the upper layer, if a filter returns Exception_execute_ Handler indicates that this __except block can handle such exceptions, that is, the processing code for the exception is found, and the lookup is stopped, but the global expansion is performed before the exception handling code in the __except block is executed.

The process of ② the global expansion is similar to finding the __except block, except this time finding the __finally block from the bottom up, and the code in every __finally block encountered during the lookup process is executed until you find the __except block of the exception that you said earlier. Stop , the global expansion completes, and then the exception handling code in the __except block is executed.

After ③ executes the exception handling code, the instruction stream starts with the first instruction after the __except block. It can also be seen from here that the global expansion is also to ensure the correctness of the __finally semantics, because the instruction flow from the throwing exception code to the __except exception handling code also causes the instruction stream to flow from all __finally corresponding __try blocks in the __try block nesting layer. From the previous __finally semantic description, it is necessary to perform the global expansion process to wrap the __finally semantics into the correctness.

(3) Stop global expansion --put return in the finally block to prevent global expansion. "Undefined behavior, VC2013 direct Error!" 】

(4) careful use of exception_continue_execution

① attempt to fix the error, A failed instance analysis occurred

*pchbuffer = TEXT ("J");//C + + statements//generated machine instructions after compilationmov eax,dword ptr[pchbuffer] mov WORD ptr[eax],'J'  //the instruction that caused the exception. After the exception filter catches the exception, fix//Pchbuffer to point to the correct address. And let the system re -//executes the second CPU instruction. The problem is that registers can't be updated automatically//to reflect the update of the variable Pchbuffer, the exception also leads to another//exception, the program is trapped in a dead loop

② virtual memory combined with SEH enables on-demand allocation of memory , sometimes writing fast and efficient applications (see Chapter 15th, "How to book bulk address space and sparse allocation memory for address space"

The ③ system built an SEH box for the thread stack . An exception is thrown when a thread attempts to access an area of the stack that has not been allocated memory. The exception filter inside the system captures the exception and internally calls VirtualAlloc to allocate more storage for the thread stack, and returns exception_continue_execution to re-execute the instruction that originally threw the exception.

"Sehandmemory" demo on-demand allocation of virtual memory

#include <windows.h>#include<tchar.h>#include<locale.h>#definePagelimit 80lpbyte Lpnxtpage;dword dwpages=0;D word dwpagesize;//page size, typically 4KBINT pagefualtexceptionfilter (DWORD dwcode) {lpvoid lpvresult; //not illegally accessing memory    if(Dwcode! =exception_access_violation) {        returnException_execute_handler;//executing the exception handler code for the except block    }    //When the specified number of pages is exceeded    if(Dwpages >=pagelimit) {        returnException_execute_handler;//executing the exception handler code for the except block    }    //illegal access to memory, the next page of physical memory is submitted for the booked spaceLpvresult =VirtualAlloc ((LPVOID) lpnxtpage, dwPageSize, Mem_commit, page_readwrite); if(Lpvresult = =NULL) {        returnException_execute_handler;//executing the exception handler code for the except block    }    //Submit Successdwpages++; Lpnxtpage+=dwpagesize; _tprintf (_t ("page%d submitted successfully! \ n"), dwpages); returnException_continue_execution;//re-executing the CPU instruction that triggered the exception}intMain () {_tsetlocale (Lc_all, _t ("CHS")); LPVOID Lpvbase; LPTSTR lpptr;    BOOL bsuccess;    System_info Ssysinfo; GetSystemInfo (&ssysinfo); dwPageSize=ssysinfo.dwpagesize; _tprintf (_t ("CPU Page size is%dkb.\n"), Ssysinfo.dwpagesize/1024x768); //Reservation StorageLpvbase = VirtualAlloc (NULL, pagelimit*dwpagesize, Mem_reserve, page_noaccess); Lpptr= (LPTSTR) (Lpnxtpage =(LPBYTE) lpvbase);  for(DWORD i =0; I < pagelimit*dwpagesize/sizeof(TCHAR); i++) {__try{lpptr[i]= _t ('a');//writes a byte of data} __except (Pagefualtexceptionfilter (GetExceptionCode ())) {_tprintf (_t ("exception is handled \ n")); //ExitProcess (GetLastError ());}} bsuccess= VirtualFree (Lpvbase,0, mem_release); _tprintf (_t ("release Operation%s.\n"), bsuccess? _t ("Success"): _t ("failed")); _tsystem (_t ("PAUSE")); return 0;}

24.3 GetExceptionCode

(1) GetExceptionCode is an inline function whose code is directly embedded in the called place (note the difference from a function call), and its return value indicates the type of exception that just occurred (defined in WinBase.h, such as Exception_access_ violation)

(2) This function can only be called in the exception filter program (that is, in parentheses after __except) or in the code of the exception handler (the curly braces behind the __except block), but not in the exception filter function.

Legal code

__try{

y = 0;

x =/y;

}

__except ((getexceptioncode () = = Exception_int_divide_by_zero)?

Exception_execute_handler:exception_continue_search) { // used in small enclosed __except blocks, legal

Switch (GetExceptionCode ()) { //__except block is used in the flower, legal!

......

}

}

Illegal code

LONG myfilter (void){}

{

// use GetExceptionCode in the exception filter function, illegal!

Return ((getexceptioncode () = = Exception_int_divide_by_zero)?

Exception_execute_handler:exception_continue_search);

}

__try{

y = 0;

x = 4/y;

}

__except (myfilter ()) { //can be changed to the form of passing getexceptioncode as a parameter to Myfilter.

Handling Exceptions

}

(3) Rules for exception error codes

bit

31-30

29

28

27-16

15-0

content

severity

microsoft/

Customer

Reserved bits

Device code

Exception code

0=success

1=informational

2=warning

3 = Error

0=mircosoft defined code

1=customer defined code

Always 0

The first 256 values of

are reserved for micorsoft. (For example, Facility_null (0) indicates that the exception can occur on any device in the system and not just on some specific device)

Code defined by microsoft/

Customer

24.4 GetExceptionInformation

(1) GetExceptionInformation can obtain exception information or CPU-related information in Exception_record, context, and exception_pointers structures that are pressed into the thread stack where the exception occurred.

(2) This function can only be called in the exception filter program (that is, the __except block of parentheses), because Except_record, context and exception_pointer data structures are only valid when the system evaluates the exception filter program. Once the control flow is shifted elsewhere, the data structures on those stacks are destroyed. But we can save them ourselves for later use.

 //  method to save exception information in stack  void   Funcskunk () { //  Declare some structures that can hold exception information, declare the   //  note the comma-expression, taking the last expression as the whole The value of an expression.    Savedexceptrec  = * (GetExceptionInformation ())->exceptionrecord, Savedcontext  = * (GetExceptionInformation ())->  Contextrecord, Exception_execute_handler) { //  exception handling   

(3) Exception_record structure--details of the exception that just occurred

Field

Description

DWORD Exceptioncode

The exception code, which is the return value of the GetExceptionCode function

DWORD ExceptionFlags

Exception flags

0-The exception that represents the continuation, exception_noncontinuable-exception that is not allowed to continue, or a exception_noncontinuable_exception exception if the program tries to resume execution after a non-continuation exception.

Pexception_record Pexceptionrecord

A exception_record structure that points to another unhandled exception. (That is, when a nested exception occurs, an exception chain is formed)

PVOID exceptionaddress

The address of the CPU instruction that caused the exception

DWORD numberparameters

The number of elements in the exceptioninformation array. For most exceptions, this value is 0.

Ulong_ptr ExceptionInformation

[Exception_maximum_parameters]

An array of additional parameters that describe the exception, for most exceptions, the array element is undefined.

24.5 software Exceptions-- RaiseException function

Parameters

Description

DWORD Dwexceptioncode

To throw an exception identifier, refer to the exception error code rule to write

DWORD Dwexceptionflags

Must be one of the following

0:

Exception_noncontinuable: Exception is not allowed to continue, that is, you can no longer return Exception_continue_execute in the exception filter program, or re-execute the CPU instruction that caused the error will continue to throw a new exception_ Noncontinuable_exception exception.

DWORD nnumberofarguments

Used to pass additional information about throwing an exception. Generally not required. The nnumberofargument can be set to 0. Parguments is set to null.

Const ulong_ptr* parguments

return value

void

"RaiseException Program"--demonstrates a software exception thrown by itself

#include <tchar.h>#include<windows.h>DWORD filterfunction () {_tprintf (_t ("1"));//the 1th sentence is the output statement    returnException_execute_handler;}intMain () {__try{__try{raiseexception (1,0,0, NULL); } __finally{_tprintf (_t ("2"));//the 2nd sentence is the output statement}} __except (FilterFunction ()) {_tprintf (_t ("3\n"));//the 3rd sentence is the output statement} _tsystem (_t ("PAUSE"));
return 0;}

24th SEH Structured Exception handling-exception handling and software exceptions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.