【翻譯】異常和異常處理(windows平臺(tái))
翻譯的不好,莫怪。
原文地址: http://crashrpt.sourceforge.net/docs/html/exception_handling.html#getting_exception_context
About Exceptions and Exception Handling
About Exception
當(dāng)程序遇到一個(gè)異常或一個(gè)嚴(yán)重的錯(cuò)誤時(shí),通常意味著它不能繼續(xù)正常運(yùn)行并且需要停止執(zhí)行。
例如,當(dāng)遇到下列情況時(shí),程序會(huì)出現(xiàn)異常:
程序訪問一個(gè)不可用的內(nèi)存地址(例如,NULL指針);
l 無限遞歸導(dǎo)致的棧溢出;
l 向一個(gè)較小的緩沖區(qū)寫入較大塊的數(shù)據(jù);
l 類的純虛函數(shù)被調(diào)用;
l 申請(qǐng)內(nèi)存失敗(內(nèi)存空間不足);
l 一個(gè)非法的參數(shù)被傳遞給C++函數(shù);
l C運(yùn)行時(shí)庫檢測(cè)到一個(gè)錯(cuò)誤并且需要程序終止執(zhí)行。
有兩種不同性質(zhì)的異常:結(jié)構(gòu)化異常(Structured Exception Handling, SEH)和類型化的C++異常。
SEH是為C語言設(shè)計(jì)的,但是他們也能夠被用于C++。SEH異常由__try{}__except(){}結(jié)構(gòu)來處理。SEH是VC++編譯器特有的,因此如果你想要編寫可移植的代碼,就不應(yīng)當(dāng)使用SEH。
C++中類型化的異常是由try{}catch(){}結(jié)構(gòu)處理的。例如(例子來自這里http://www.cplusplus.com/doc/tutorial/exceptions/):
#include <iostream>
using namespace std;
int main(){
try{
throw 20;
}
catch (int e){
cout << "An exception occrred. Exception Nr. " << e << endl;
}
return 0;
}
結(jié)構(gòu)化異常處理
當(dāng)發(fā)生一個(gè)SEH異常時(shí),你通常會(huì)看到一個(gè)意圖向微軟發(fā)送錯(cuò)誤報(bào)告的彈出窗口。
你可以使用RaiseException()函數(shù)自己產(chǎn)生一個(gè)SEH異常。
你可以在你的代碼中使用__try{}__except(Expression){}結(jié)構(gòu)來捕獲SEH異常。程序中的main()函數(shù)被這樣的結(jié)構(gòu)保護(hù),因此默認(rèn)地,所有未被處理的SEH異常都會(huì)被捕獲。
例如:
#include <Windows.h>
int main(){
int *p = NULL; // pointer to NULL
__try{
// Guarded code
*p = 13; // causes an access violation exception;
}
__except(EXCEPTION_EXECUTE_HANDLER){ // Here is exception filter expression
// Here is exception handler
// Terminate program
ExitProcess(1);
}
return 0;
}
每一個(gè)SEH異常都有一個(gè)與其相關(guān)聯(lián)的異常碼(exception code)。你可以使用GetExceptionCode()函數(shù)來獲取異常碼。你可以通過GetExceptionInformation()來獲取異常信息。為了使用這些函數(shù),你通常會(huì)像下面示例中一樣定制自己的exception filter。
下面的例子說明了如何使用SEH exception filter。
int seh_filter(unsigned int code, struct _EXCEPTION_POINTERS *ep){
// Generate error report
// Execute exception handler
return EXCEPTION_EXECUTE_HANDLER;
}
int main(){
__try{
// .. some buggy code here
}
__except(seh_filter(GetExceptionCode(), GetExceptionInformation())){
// Terminate program
ExitProcess(1);
}
return 0;
}
__try{}__exception(){}結(jié)構(gòu)是面向C語言的,但是,你可以將一個(gè)SEH異常重定向到C++異常,并且你可以像處理C++異常一樣處理它。我們可以使用C++運(yùn)行時(shí)庫中的_set_se_translator()函數(shù)來實(shí)現(xiàn)。
看一個(gè)MSDN中的例子(譯者注:運(yùn)行此例子需打開/EHa編譯選項(xiàng)):
#include <cstdio>
#include <windows.h>
#include <eh.h>
void SEFunc();
void trans_func(unsigned int, EXCEPTION_POINTERS *);
class SE_Exception{
private:
unsigned int nSE;
public:
SE_Exception(){}
SE_Exception(unsigned int n) : nSE(n){}
~SE_Exception() {}
unsigned int getSeNumber(){ return nSE; }
};
int main(void){
try{
_set_se_translator(trans_func);
SEFunc();
}
catch(SE_Exception e){
printf("Caught a __try exception with SE_Exception.\n");
}
}
void SEFunc(){
__try{
int x, y=0;
x = 5 / y;
}
__finally{
printf("In finally\n");
}
}
void trans_func(unsigned int u, EXCEPTION_POINTERS* pExp){
printf("In trans_func.\n");
throw SE_Exception();
}
你可能忘記對(duì)一些潛在的錯(cuò)誤代碼使用__try{}__catch(Expression){}結(jié)構(gòu)進(jìn)行保護(hù),而這些代碼可能會(huì)產(chǎn)生異常,但是這個(gè)異常卻沒有被你的程序所處理。不用擔(dān)心,這個(gè)未被處理的SEH異常能夠被unhandled Exception filter所捕獲,我們可以使用SetUnhandledExceptionFilter()函數(shù)設(shè)置top-levelunhandled exception filter。
異常信息(異常發(fā)生時(shí)的CPU狀態(tài))通過EXCEPTION_POINTERS被傳遞給exception handler。
例如:
// crt_settrans.cpp
// compile with: /EHa
LONG WINAPI MyUnhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionPtrs){
// Do something, for example generate error report
//..
// Execute default exception handler next
return EXCEPTION_EXECUTE_HANDLER;
}
void main(){
SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
// .. some unsafe code here
}
top-level SEH exception handler對(duì)進(jìn)程中的每個(gè)線程都起作用,因此在你的main()函數(shù)開頭調(diào)用一次就夠了。
top-level SEH exception handler在發(fā)生異常的線程的上下文中被調(diào)用。這會(huì)影響異常處理函數(shù)從異常中恢復(fù)的能力。
如果你的異常處理函數(shù)位于一個(gè)DLL中,那么在使用SetUnhandledExceptionFilter()函數(shù)時(shí)就要小心了。如果你的函數(shù)在程序崩潰時(shí)還未被加載,這種行為是不可預(yù)測(cè)的。
向量化異常處理(Vectored Exception Handling)
向量化異常處理(VEH)是結(jié)構(gòu)化異常處理的一個(gè)擴(kuò)展,它在Windows XP中被引入。
你可以使用AddVectoredExceptionHandler()函數(shù)添加一個(gè)向量化異常處理器,VEH的缺點(diǎn)是它只能用在WinXP及其以后的版本,因此需要在運(yùn)行時(shí)檢查AddVectoredExceptionHandler()函數(shù)是否存在。
要移除先前安裝的異常處理器,可以使用RemoveVectoredExceptionHandler()函數(shù)。
VEH允許查看或處理應(yīng)用程序中所有的異常。為了保持后向兼容,當(dāng)程序中的某些部分發(fā)生SEH異常時(shí),系統(tǒng)依次調(diào)用已安裝的VEH處理器,直到它找到有用的SEH處理器。
VEH的一個(gè)優(yōu)點(diǎn)是能夠鏈接異常處理器(chain exception handlers),因此如果有人在你之前安裝了向量化異常處理器,你仍然能截獲這些異常。
當(dāng)你需要像調(diào)試器一樣監(jiān)事所有的異常時(shí),使用VEH是很合適的。問題是你需要決定哪個(gè)異常需要處理,哪個(gè)異常需要跳過。 In program's code, some exceptions may be intentionally guarded by __try{}__except(){} construction, and handling such exceptions in VEH and not passing it to frame-based SEH handler, you may introduce bugs into application logics.
VEH目前沒有被CrashRpt所使用。SetUnhandledExceptionFilter()更加適用,因?yàn)樗莟op-level SEH處理器。如果沒有人處理異常,top-level SEH處理器就會(huì)被調(diào)用,并且你不用決定是否要處理這個(gè)異常。
CRT 錯(cuò)誤處理
除了SEH異常和C++類型化異常,C運(yùn)行庫(C runtime libraries, CRT)也提供它自己的錯(cuò)誤處理機(jī)制,在你的程序中也應(yīng)該考慮使用它。
當(dāng)CRT遇到一個(gè)未被處理的C++類型化異常時(shí),它會(huì)調(diào)用terminate()函數(shù)。如果你想攔截這個(gè)調(diào)用并提供合適的行為,你應(yīng)該使用set_terminate()函數(shù)設(shè)置錯(cuò)誤處理器(error hanlder)。例如:
#include <iostream>
void my_terminate_handler()
{
// Abnormal program termination (terminate() function was called)
// Do something here
// Finally, terminate program
std::cout << "terminate.\n";
exit(1);
}
int main()
{
set_terminate(my_terminate_handler);
terminate();
return 0;
}
Note:在多線程環(huán)境中,每個(gè)線程維護(hù)各自的unexpected和terminate函數(shù)。每個(gè)新線程需要安裝自己的unexpected和terminate函數(shù)。因此,每個(gè)線程負(fù)責(zé)自己的unexpected和terminate處理器。
使用_set_purecall_handler()函數(shù)來處理純虛函數(shù)調(diào)用。這個(gè)函數(shù)可以用于VC++2003及其后續(xù)版本。這個(gè)函數(shù)可以用于一個(gè)進(jìn)程中的所有線程。例如(來源于MSDN):
// compile with: /EHa
// _set_purecall_handler.cpp
// compile with: /W1
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
class CDerived;
class CBase{
public:
CBase(CDerived *derived): m_pDerived(derived) {};
~CBase();
virtual void function(void) = 0;
CDerived * m_pDerived;
};
class CDerived : public CBase{
public:
CDerived() : CBase(this) {}; // C4355
virtual void function(void) {};
};
CBase::~CBase(){
m_pDerived -> function();
}
void myPurecallHandler(void){
printf("In _purecall_handler.");
exit(0);
}
int _tmain(int argc, _TCHAR* argv[]){
//_set_purecall_handler(myPurecallHandler);
CDerived myDerived;
}
使用_set_new_handler()函數(shù)處理內(nèi)存分配失敗。這個(gè)函數(shù)能夠用于VC++2003及其后續(xù)版本。這個(gè)函數(shù)可以用于一個(gè)進(jìn)程中的所有線程。也可以考慮使用_set_new_mode()函數(shù)來為malloc()函數(shù)定義錯(cuò)誤時(shí)的行為。例如(來自MSDN):
// crt_settrans.cpp
#include <new.h>
int handle_program_memory_depletion( size_t ){
// Your code
}
int main( void ){
_set_new_handler( handle_program_memory_depletion );
int *pi = new int[BIG_NUMBER];
}
在VC++2003中,你能夠使用_set_security_error_handler()函數(shù)來處理緩沖區(qū)溢出錯(cuò)誤。這個(gè)函數(shù)已經(jīng)被廢棄,并且從之后VC++版本的CRT中移除。
當(dāng)系統(tǒng)函數(shù)調(diào)用檢測(cè)到非法的參數(shù)時(shí),會(huì)使用_set_invalid_parameter_handler()函數(shù)來處理這種情況。這個(gè)函數(shù)能夠用于VC++2005及其以后的版本。這個(gè)函數(shù)可用于進(jìn)程中的所有線程。
例子(來源于MSDN):
// compile with: /Zi /MTd
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h> // For _CrtSetReportMode
void myInvalidParameterHandler(const wchar_t* expression,
const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved){
wprintf(L"Invalid parameter detected in function %s."
L" File: %s Line: %d\n", function, file, line);
wprintf(L"Expression: %s\n", expression);
}
int main( ){
char* formatString;
_invalid_parameter_handler oldHandler, newHandler;
newHandler = myInvalidParameterHandler;
oldHandler = _set_invalid_parameter_handler(newHandler);
// Disable the message box for assertions.
_CrtSetReportMode(_CRT_ASSERT, 0);
// Call printf_s with invalid parameters.
formatString = NULL;
printf(formatString);
return 0;
}
C++信號(hào)處理C++ Singal Handling
C++提供了被稱為信號(hào)的中斷機(jī)制。你可以使用signal()函數(shù)處理信號(hào)。
Visual C++提供了6中類型的信號(hào):
l SIGABRT Abnormal termination
l SIGFPE Floating-point error
l SIGILL Illegal instruction
l SIGINT CTRL+C signal
l SIGSEGV Illegal storage access
l SIGTERM
MSDN中說SIGILL, SIGSEGV,和SIGTERM are not generated under Windows NT并且與ANSI相兼容。但是,如果你在主線程中設(shè)置SIGSEGV signal handler,CRT將會(huì)調(diào)用它,而不是調(diào)用SetUnhandledExceptionFilter()函數(shù)設(shè)置的SHE exception handler,全局變量_pxcptinfoptrs中包含了指向異常信息的指針。
_pxcptinfoptrs也會(huì)被用于SIGFPE handler中,而在所有其他的signal handlers中,它將會(huì)被設(shè)為NULL。
當(dāng)一個(gè)floating point 錯(cuò)誤發(fā)生時(shí),例如除零錯(cuò),CRT將調(diào)用SIGFPE signal handler。然而,默認(rèn)情況下,不會(huì)產(chǎn)生float point 異常,取而代之的是,將會(huì)產(chǎn)生一個(gè)NaN或無窮大的數(shù)作為這種浮點(diǎn)數(shù)運(yùn)算的結(jié)果。可以使用_controlfp_s()函數(shù)使得編譯器能夠產(chǎn)生floating point異常。
使用raise()函數(shù),你可以人工地產(chǎn)生所有的6中信號(hào)。例如:
#include <cstdlib>
#include <csignal>
#include <iostream>
void sigabrt_handler(int){
// Caught SIGABRT C++ signal
// Terminate program
std::cout << "handled.\n";
exit(1);
}
int main(){
signal(SIGABRT, sigabrt_handler);
// Cause abort
abort();
}
Note:
雖然MSDN中沒有詳細(xì)地說明,但是你應(yīng)該為你程序中的每個(gè)線程都安裝SIGFPE, SIGILL和SIGSEGV signal hanlders。SIGABRT, SIGINT和SIGTERM signal hanlders對(duì)程序中的每個(gè)線程都起作用,因此你只需要在你的main函數(shù)中安裝他們一次就夠了。
獲取異常信息 Retrieving Exception Information
譯者注:這一小節(jié)不太懂,以后有時(shí)間再翻譯
When an exception occurs you typically want to get the CPU state to determine the place in your code that caused the problem. You use the information to debug the problem. The way you retrieve the exception information differs depending on the exception handler you use.
In the SEH exception handler set with the SetUnhandledExceptionFilter() function, the exception information is retrieved from EXCEPTION_POINTERS structure passed as function parameter.
In __try{}__catch(Expression){} construction you retrieve exception information using GetExceptionInformation() intrinsic function and pass it to the SEH exception filter function as parameter.
In the SIGFPE and SIGSEGV signal handlers you can retrieve the exception information from the _pxcptinfoptrs global CRT variable that is declared in <signal.h>. This variable is not documented well in MSDN.
In other signal handlers and in CRT error handlers you have no ability to easily extract the exception information. I found a workaround used in CRT code (see CRT 8.0 source files, invarg.c, line 104).
The following code shows how to get current CPU state used as exception information.
#if _MSC_VER>=1300
#include <rtcapi.h>
#endif
#ifndef _AddressOfReturnAddress
// Taken from: http://msdn.microsoft.com/en-us/library/s975zw7k(VS.71).aspx
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
// _ReturnAddress and _AddressOfReturnAddress should be prototyped before use
EXTERNC void * _AddressOfReturnAddress(void);
EXTERNC void * _ReturnAddress(void);
#endif
// The following function retrieves exception info
void GetExceptionPointers(DWORD dwExceptionCode,
EXCEPTION_POINTERS** ppExceptionPointers)
{
// The following code was taken from VC++ 8.0 CRT (invarg.c: line 104)
EXCEPTION_RECORD ExceptionRecord;
CONTEXT ContextRecord;
memset(&ContextRecord, 0, sizeof(CONTEXT));
#ifdef _X86_
__asm {
mov dword ptr [ContextRecord.Eax], eax
mov dword ptr [ContextRecord.Ecx], ecx
mov dword ptr [ContextRecord.Edx], edx
mov dword ptr [ContextRecord.Ebx], ebx
mov dword ptr [ContextRecord.Esi], esi
mov dword ptr [ContextRecord.Edi], edi
mov word ptr [ContextRecord.SegSs], ss
mov word ptr [ContextRecord.SegCs], cs
mov word ptr [ContextRecord.SegDs], ds
mov word ptr [ContextRecord.SegEs], es
mov word ptr [ContextRecord.SegFs], fs
mov word ptr [ContextRecord.SegGs], gs
pushfd
pop [ContextRecord.EFlags]
}
ContextRecord.ContextFlags = CONTEXT_CONTROL;
#pragma warning(push)
#pragma warning(disable:4311)
ContextRecord.Eip = (ULONG)_ReturnAddress();
ContextRecord.Esp = (ULONG)_AddressOfReturnAddress();
#pragma warning(pop)
ContextRecord.Ebp = *((ULONG *)_AddressOfReturnAddress()-1);
#elif defined (_IA64_) || defined (_AMD64_)
/* Need to fill up the Context in IA64 and AMD64. */
RtlCaptureContext(&ContextRecord);
#else /* defined (_IA64_) || defined (_AMD64_) */
ZeroMemory(&ContextRecord, sizeof(ContextRecord));
#endif /* defined (_IA64_) || defined (_AMD64_) */
ZeroMemory(&ExceptionRecord, sizeof(EXCEPTION_RECORD));
ExceptionRecord.ExceptionCode = dwExceptionCode;
ExceptionRecord.ExceptionAddress = _ReturnAddress();
EXCEPTION_RECORD* pExceptionRecord = new EXCEPTION_RECORD;
memcpy(pExceptionRecord, &ExceptionRecord, sizeof(EXCEPTION_RECORD));
CONTEXT* pContextRecord = new CONTEXT;
memcpy(pContextRecord, &ContextRecord, sizeof(CONTEXT));
*ppExceptionPointers = new EXCEPTION_POINTERS;
(*ppExceptionPointers)->ExceptionRecord = pExceptionRecord;
(*ppExceptionPointers)->ContextRecord = pContextRecord;
}
Visual C++ Complier Flags
Visual C++編譯器中有一些編譯選項(xiàng)和異常處理有關(guān)。
在Project Properties->Configuration Properties->C/C++ ->Code Generation中可以找到這些選項(xiàng)。
異常處理模型Exception Handling Model
你可以為VC++編譯器選擇異常處理模型。選項(xiàng)/EHs(或者EHsc)用來指定同步異常處理模型,/EHa用來指定異步異常處理模型。可以查看下面參考小節(jié)的"/EH(Exception Handling Model)"以獲取更多的信息。
Floating Point Exceptions
你可以使用/fp:except編譯選項(xiàng)打開float point exceptions。
緩沖區(qū)安全檢查Buffer Security Checks
你可以使用/GS(Buffer Security Check)選項(xiàng)來強(qiáng)制編譯器插入代碼以檢查緩沖區(qū)溢出。緩沖區(qū)溢出指的是一大塊數(shù)據(jù)被寫入一塊較小的緩沖區(qū)中。當(dāng)檢測(cè)到緩沖區(qū)溢出,CRT calls internal security handler that invokes Watson directly。
Note:
在VC++(CRT7.1)中,緩沖區(qū)溢出被檢測(cè)到時(shí),CRT會(huì)調(diào)用由_set_security_error_handler函數(shù)設(shè)置的處理器。然而,在之后的VC版本中這個(gè)函數(shù)被廢棄。
從CRT8.0開始,你在你的代碼中不能截獲安全錯(cuò)誤。當(dāng)緩沖區(qū)溢出被檢測(cè)到時(shí),CRT會(huì)直接請(qǐng)求Watson,而不是調(diào)用unhandled exception filter。這樣做是由于安全原因并且微軟不打算改變這種行為。
更多的信息請(qǐng)參考如下鏈接
https://connect.microsoft.com/VisualStudio/feedback/details/101337/a-proposal-to-make-dr-watson-invocation-configurable
http://blog.kalmbachnet.de/?postid=75
異常處理和CRT鏈接Exception Handling and CRT Linkage
你的應(yīng)用程序中的每個(gè)module(EXE, DLL)都需要鏈接CRT。你可以將CRT鏈接為多線程靜態(tài)庫(multi-threaded static library)或者多線程動(dòng)態(tài)鏈接庫(multi-threaded dynamic link library)。如果你設(shè)置了CRT error handlers,例如你設(shè)置了terminate handler, unexcepted handler, pure call handler, invalid parameter handler, new operator error handler or a signal handler,那么他們將只在你鏈接的CRT上運(yùn)行,并且不會(huì)捕獲其他CRT模塊中的異常(如果存在的話),因?yàn)槊總€(gè)CRT模塊都有它自己的內(nèi)部狀態(tài)。
多個(gè)工程中的module可以共享CRT DLL。這將使得被鏈接的CRT代碼達(dá)到最小化,并且CRT DLL中的所有異常都會(huì)被立刻處理。這也是推薦使用multi-threaded CRT DLL作為CRT鏈接方式的原因。