How the C + + compiler implements exception handling

Source: Internet
Author: User
Tags error handling exception handling preg prev

Translator Note: This article has several translations on the internet, but not complete, so I decided to translate it myself. Although strive to believe, ya, Tatsu, but in view of this is my first translation experience, deficiencies please understand and point out.

One of the revolutionary innovations of C + +, compared with traditional languages, is that it supports exception handling. Traditional error handling often does not meet the requirements, and exception handling is an excellent alternative to the solution. It separates the normal code and the error handling code clearly, and the program becomes very clean and easy to maintain. This article discusses how the compiler implements exception handling. I will assume that you are already familiar with the syntax and mechanism of exception handling. This article also provides a VC + + for the exception processing library, to use the library's handler to replace the one provided by VC + +, you only need to call the following function:
Install_my_handler ();

After that, all the exceptions in the program, from being thrown to the stack unwinding, to the call catch block, and finally to the program's return to normal operation, are managed by my exception-handling library.

As with other C + + features, the C + + standard does not specify how the compiler should implement exception handling. This means that each compiler provider can implement it in a way that they think is appropriate. Below I will describe how VC + + is done, but even if you use other compilers or operating system ①, this article should be a good learning material. VC + + implementation is based on the structure of the Windows system exception handling (SEH) ②.

Structured Exception Handling-Overview

In the discussion in this article, I think that the exception was either explicitly thrown or caused by a 0 overflow, null pointer access, and so on. When it happens, an interruption occurs, and then control is passed to the operating system's hands. The operating system invokes the exception handler to check the sequence of function calls starting at the location where the exception occurred, for stack expansion and control transfer. Windows defines the structure "exception_registration", allowing us to register our own exception handlers with the operating system.
struct exception_registration
{
exception_registration* prev;
DWORD handler;
};
When registering, just create such a structure, and then put its address to the FS segment offset 0 in the position of the line. The following assembly code illustrates this operation:

mov fs:[0], EXC_REGP
The Prev field is used to create a list of exception_registration structures, and each time a new exception_registration is registered, we have to save the address of the original registered one to the prev.

So, what does that exception callback function look like? In Excpt.h, Windows defines its prototype:

Exception_disposition (*handler) (
_exception_record *excrecord,
void* Establisherframe,
_context *contextrecord,
void* dispatchercontext);
Leave out the arguments and return values, let's look at a simple example. The following program registers an exception handler and then creates an exception by dividing by 0. The exception handler captures it, prints a message and Bob and exits.

#include <iostream>
#include <windows.h>
using Std::cout;
Using Std::endl;  
struct exception_registration
{
exception_registration* prev;
DWORD handler;
};
Exception_disposition MyHandler (
_exception_record *excrecord,
void * establisherframe,
_context *Cont  Extrecord,
Void * dispatchercontext)
{
cout << "In the exception handler" << Endl;
cout << "Just a demo." Exiting << Endl;
Exit (0);
return exceptioncontinueexecution;//will not run to this

int g_div = 0;
void Bar ()
{
//initialization of a exception_registration structure
Exception_registration Reg, *preg =®
Reg.handler = (DWORD ) MyHandler;  
//Gets the "header"
DWORD prev of the current exception-handling chain;
  _asm
{
mov EAX, fs:[0]
mov prev, EAX
}
Reg.prev = (exception_registration*) prev;
Registered!
_asm
{
mov EAX, preg
mov fs:[0], EAX
}
//Generate an exception
Int j = 10/g_div;//exception, except 0 overflow
}
INT Main ()
{
Bar ();
return 0;
}
/*-------Output-------------------
In the exception handler
Just a demo ... exiting ...
---------------------------------*/
Note that exception_registration must be defined on the stack and must be located on a lower memory address than the previous node, which Windows has strict requirements , it will terminate the process immediately.
Functions and stacks

A stack is a contiguous memory area that is used to hold a local object. More specifically, each function has an associated stack frame to hold all of its local objects and the temporary objects used in the calculation of expressions, at least in theory. In reality, however, compilers often put objects in registers so that they can be accessed at a faster rate. The stack is a processor (CPU) level concept, in order to manipulate it, the processor provides some dedicated registers and instructions.

Figure 1 is a typical stack that shows the scenario when function Foo invokes Bar,bar and invokes the widget. Note that the stack is growing downward, which means the address of the newly pressed item is less than the address of the original item.

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.