【翻譯】異常和異常處理(windows平臺)
翻譯的不好,莫怪。
原文地址: http://crashrpt.sourceforge.net/docs/html/exception_handling.html#getting_exception_context
About Exceptions and Exception Handling
About Exception
當程序遇到一個異?;蛞粋€嚴重的錯誤時,通常意味著它不能繼續正常運行并且需要停止執行。
例如,當遇到下列情況時,程序會出現異常:
程序訪問一個不可用的內存地址(例如,NULL指針);
l 無限遞歸導致的棧溢出;
l 向一個較小的緩沖區寫入較大塊的數據;
l 類的純虛函數被調用;
l 申請內存失敗(內存空間不足);
l 一個非法的參數被傳遞給C++函數;
l C運行時庫檢測到一個錯誤并且需要程序終止執行。
有兩種不同性質的異常:結構化異常(Structured Exception Handling, SEH)和類型化的C++異常。
SEH是為C語言設計的,但是他們也能夠被用于C++。SEH異常由__try{}__except(){}結構來處理。SEH是VC++編譯器特有的,因此如果你想要編寫可移植的代碼,就不應當使用SEH。
C++中類型化的異常是由try{}catch(){}結構處理的。例如(例子來自這里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;
}
結構化異常處理
當發生一個SEH異常時,你通常會看到一個意圖向微軟發送錯誤報告的彈出窗口。
你可以使用RaiseException()函數自己產生一個SEH異常。
你可以在你的代碼中使用__try{}__except(Expression){}結構來捕獲SEH異常。程序中的main()函數被這樣的結構保護,因此默認地,所有未被處理的SEH異常都會被捕獲。
例如:
#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;
}
每一個SEH異常都有一個與其相關聯的異常碼(exception code)。你可以使用GetExceptionCode()函數來獲取異常碼。你可以通過GetExceptionInformation()來獲取異常信息。為了使用這些函數,你通常會像下面示例中一樣定制自己的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(){}結構是面向C語言的,但是,你可以將一個SEH異常重定向到C++異常,并且你可以像處理C++異常一樣處理它。我們可以使用C++運行時庫中的_set_se_translator()函數來實現。
看一個MSDN中的例子(譯者注:運行此例子需打開/EHa編譯選項):
#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();
}
你可能忘記對一些潛在的錯誤代碼使用__try{}__catch(Expression){}結構進行保護,而這些代碼可能會產生異常,但是這個異常卻沒有被你的程序所處理。不用擔心,這個未被處理的SEH異常能夠被unhandled Exception filter所捕獲,我們可以使用SetUnhandledExceptionFilter()函數設置top-levelunhandled exception filter。
異常信息(異常發生時的CPU狀態)通過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對進程中的每個線程都起作用,因此在你的main()函數開頭調用一次就夠了。
top-level SEH exception handler在發生異常的線程的上下文中被調用。這會影響異常處理函數從異常中恢復的能力。
如果你的異常處理函數位于一個DLL中,那么在使用SetUnhandledExceptionFilter()函數時就要小心了。如果你的函數在程序崩潰時還未被加載,這種行為是不可預測的。
向量化異常處理(Vectored Exception Handling)
向量化異常處理(VEH)是結構化異常處理的一個擴展,它在Windows XP中被引入。
你可以使用AddVectoredExceptionHandler()函數添加一個向量化異常處理器,VEH的缺點是它只能用在WinXP及其以后的版本,因此需要在運行時檢查AddVectoredExceptionHandler()函數是否存在。
要移除先前安裝的異常處理器,可以使用RemoveVectoredExceptionHandler()函數。
VEH允許查看或處理應用程序中所有的異常。為了保持后向兼容,當程序中的某些部分發生SEH異常時,系統依次調用已安裝的VEH處理器,直到它找到有用的SEH處理器。
VEH的一個優點是能夠鏈接異常處理器(chain exception handlers),因此如果有人在你之前安裝了向量化異常處理器,你仍然能截獲這些異常。
當你需要像調試器一樣監事所有的異常時,使用VEH是很合適的。問題是你需要決定哪個異常需要處理,哪個異常需要跳過。 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()更加適用,因為它是top-level SEH處理器。如果沒有人處理異常,top-level SEH處理器就會被調用,并且你不用決定是否要處理這個異常。
CRT 錯誤處理
除了SEH異常和C++類型化異常,C運行庫(C runtime libraries, CRT)也提供它自己的錯誤處理機制,在你的程序中也應該考慮使用它。
當CRT遇到一個未被處理的C++類型化異常時,它會調用terminate()函數。如果你想攔截這個調用并提供合適的行為,你應該使用set_terminate()函數設置錯誤處理器(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:在多線程環境中,每個線程維護各自的unexpected和terminate函數。每個新線程需要安裝自己的unexpected和terminate函數。因此,每個線程負責自己的unexpected和terminate處理器。
使用_set_purecall_handler()函數來處理純虛函數調用。這個函數可以用于VC++2003及其后續版本。這個函數可以用于一個進程中的所有線程。例如(來源于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()函數處理內存分配失敗。這個函數能夠用于VC++2003及其后續版本。這個函數可以用于一個進程中的所有線程。也可以考慮使用_set_new_mode()函數來為malloc()函數定義錯誤時的行為。例如(來自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()函數來處理緩沖區溢出錯誤。這個函數已經被廢棄,并且從之后VC++版本的CRT中移除。
當系統函數調用檢測到非法的參數時,會使用_set_invalid_parameter_handler()函數來處理這種情況。這個函數能夠用于VC++2005及其以后的版本。這個函數可用于進程中的所有線程。
例子(來源于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++信號處理C++ Singal Handling
C++提供了被稱為信號的中斷機制。你可以使用signal()函數處理信號。
Visual C++提供了6中類型的信號:
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相兼容。但是,如果你在主線程中設置SIGSEGV signal handler,CRT將會調用它,而不是調用SetUnhandledExceptionFilter()函數設置的SHE exception handler,全局變量_pxcptinfoptrs中包含了指向異常信息的指針。
_pxcptinfoptrs也會被用于SIGFPE handler中,而在所有其他的signal handlers中,它將會被設為NULL。
當一個floating point 錯誤發生時,例如除零錯,CRT將調用SIGFPE signal handler。然而,默認情況下,不會產生float point 異常,取而代之的是,將會產生一個NaN或無窮大的數作為這種浮點數運算的結果。可以使用_controlfp_s()函數使得編譯器能夠產生floating point異常。
使用raise()函數,你可以人工地產生所有的6中信號。例如:
#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中沒有詳細地說明,但是你應該為你程序中的每個線程都安裝SIGFPE, SIGILL和SIGSEGV signal hanlders。SIGABRT, SIGINT和SIGTERM signal hanlders對程序中的每個線程都起作用,因此你只需要在你的main函數中安裝他們一次就夠了。
獲取異常信息 Retrieving Exception Information
譯者注:這一小節不太懂,以后有時間再翻譯
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++編譯器中有一些編譯選項和異常處理有關。
在Project Properties->Configuration Properties->C/C++ ->Code Generation中可以找到這些選項。
異常處理模型Exception Handling Model
你可以為VC++編譯器選擇異常處理模型。選項/EHs(或者EHsc)用來指定同步異常處理模型,/EHa用來指定異步異常處理模型??梢圆榭聪旅鎱⒖夹」澋?/EH(Exception Handling Model)"以獲取更多的信息。
Floating Point Exceptions
你可以使用/fp:except編譯選項打開float point exceptions。
緩沖區安全檢查Buffer Security Checks
你可以使用/GS(Buffer Security Check)選項來強制編譯器插入代碼以檢查緩沖區溢出。緩沖區溢出指的是一大塊數據被寫入一塊較小的緩沖區中。當檢測到緩沖區溢出,CRT calls internal security handler that invokes Watson directly。
Note:
在VC++(CRT7.1)中,緩沖區溢出被檢測到時,CRT會調用由_set_security_error_handler函數設置的處理器。然而,在之后的VC版本中這個函數被廢棄。
從CRT8.0開始,你在你的代碼中不能截獲安全錯誤。當緩沖區溢出被檢測到時,CRT會直接請求Watson,而不是調用unhandled exception filter。這樣做是由于安全原因并且微軟不打算改變這種行為。
更多的信息請參考如下鏈接
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
你的應用程序中的每個module(EXE, DLL)都需要鏈接CRT。你可以將CRT鏈接為多線程靜態庫(multi-threaded static library)或者多線程動態鏈接庫(multi-threaded dynamic link library)。如果你設置了CRT error handlers,例如你設置了terminate handler, unexcepted handler, pure call handler, invalid parameter handler, new operator error handler or a signal handler,那么他們將只在你鏈接的CRT上運行,并且不會捕獲其他CRT模塊中的異常(如果存在的話),因為每個CRT模塊都有它自己的內部狀態。
多個工程中的module可以共享CRT DLL。這將使得被鏈接的CRT代碼達到最小化,并且CRT DLL中的所有異常都會被立刻處理。這也是推薦使用multi-threaded CRT DLL作為CRT鏈接方式的原因。