1. 程式人生 > >C++程式崩潰解決方案

C++程式崩潰解決方案

C++程式崩潰解決方案


如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流群:129518033

目錄

文章目錄

環境:
QT版本:5.6.2
開發環境:VS2013
系統版本:windows 7 64bit


前言

C++程式崩潰如何進行異常捕獲處理?特別是釋出版本為Release版本,要想保留現場和復現就更加困難。本文較少幾種捕獲程式異常定位問題的方案。

1. SetUnhandledExceptionFilter+ MiniDumpWriteDump + PDB解決方案

1.1 SetUnhandledExceptionFilter簡介

Windows為應用程式提供了一種通過SetUnhandledExceptionFilter函式覆蓋預設應用程式“崩潰”處理功能的方法。

通常,SetUndhandledExceptionFilter函式與崩潰報告一起使用。 能夠精確定位引起崩潰的程式碼行在事後除錯中是非常寶貴的。

引數 要求
最小PC系統 Windows XP
最小伺服器系統 Windows Server 2003
標頭檔案 WinBase.h (包含在Windows.h)
Library Kernel32.lib
DLL Kernel32.dll

語法:


LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
  _In_ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter
);

1.2 MiniDumpWriteDump簡介

MiniDumpWriteDump將使用者模式minidump資訊寫入指定的檔案。

引數 要求
平臺 Windows
標頭檔案 minidumpapiset.h (包含在Dbghelp.h)
Library Dbghelp.lib
DLL Dbghelp.dll; Dbgcore.dll
釋出需求 DbgHelp.dll and Dbgcore.dll

語法:

BOOL MiniDumpWriteDump(
  HANDLE                            hProcess,
  DWORD                             ProcessId,
  HANDLE                            hFile,
  MINIDUMP_TYPE                     DumpType,
  PMINIDUMP_EXCEPTION_INFORMATION   ExceptionParam,
  PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
  PMINIDUMP_CALLBACK_INFORMATION    CallbackParam
);

1.3 PDB簡介

如何使QT的Release模式可除錯(Windows)

MSDN : Program Database Files (C++)

1.4 捕獲異常

1.4.1 pro檔案

win32:LIBS += -lDbgHelp

1.4.2 標頭檔案

    #include "Windows.h"
    #include <dbghelp.h>

1.4.3 異常捕獲函式

//異常捕獲函式
long ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
    {
        // 在程式exe的上級目錄中建立dmp資料夾
        QDir *dmp = new QDir;
        bool exist = dmp->exists("./dmp");
        if(exist == false)
        {
            dmp->mkdir("./dmp");
        }
    }

    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("yyyy_MM_dd_hh_mm_ss");
    QString time =  current_date + ".dmp";
    EXCEPTION_RECORD *record = pException->ExceptionRecord;
    QString errCode(QString::number(record->ExceptionCode, 16));
    QString errAddr(QString::number((uint)record->ExceptionAddress, 16));
    QString errFlag(QString::number(record->ExceptionFlags, 16));
    QString errPara(QString::number(record->NumberParameters, 16));
    qDebug()<< "errCode: "<<errCode;
    qDebug()<< "errAddr: "<<errAddr;
    qDebug()<< "errFlag: "<<errFlag;
    qDebug()<< "errPara: "<<errPara;

    //建立 Dump 檔案
    HANDLE hDumpFile = CreateFile((LPCWSTR)QString("./dmp/" + time).utf16(),
                                  GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if(hDumpFile != INVALID_HANDLE_VALUE)
    {
        //Dump資訊
        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
        dumpInfo.ExceptionPointers = pException;
        dumpInfo.ThreadId = GetCurrentThreadId();
        dumpInfo.ClientPointers = TRUE;
        //寫入Dump檔案內容
        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
        CloseHandle(hDumpFile);
    }
    else
    {
        qDebug()<< "hDumpFile == null";
    }

    //這裡彈出一個錯誤對話方塊並退出程式
    QMessageBox::critical(NULL,QString::fromLocal8Bit("程式崩潰"),
                          QString::fromLocal8Bit("對於發生的錯誤,表示誠摯的歉意\n錯誤程式碼:%1\n錯誤地址:%2").arg(errCode).arg(errAddr),
                          QMessageBox::Ok);

    return EXCEPTION_EXECUTE_HANDLER;
}

1.4.4 主函式呼叫

    int main(int argc, char *argv[])
    {
        //註冊異常捕獲函式
        SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
        ...
    }

1.5 分析異常

經過上面的設定可以生成*.dmp檔案,結合*.pdb(如何使QT的Release模式可除錯(Windows))就可以定位到原始碼中的函式,乃至於行數。

1.5.1 解析dmp

Windows 除錯程式 (WinDbg) 可用於除錯核心和使用者模式程式碼,分析故障轉儲並檢查 CPU 註冊程式碼執行。

1.5.1.1 設定符號檔案路徑

也就是*.pdb的路徑

在這裡插入圖片描述

在這裡插入圖片描述

1.5.1.1 開啟*.dmp檔案
Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.


Loading Dump File [C:\Users\Administrator\Desktop\2018_11_01_19_32_09.dmp]
User Mini Dump File: Only registers, stack and portions of memory are available

Symbol search path is: C:\Users\Administrator\Desktop
Executable search path is: 
Windows 7 Version 7601 (Service Pack 1) MP (4 procs) Free x86 compatible
Product: WinNt, suite: SingleUserTS
Machine Name:
Debug session time: Thu Nov  1 19:32:09.000 2018 (UTC + 8:00)
System Uptime: not available
Process Uptime: 0 days 0:00:01.000
................................................................
.....................................................
This dump file has an exception of interest stored in it.
The stored exception information can be accessed via .ecxr.
(be0.ccc): Integer divide-by-zero - code c0000094 (first/second chance not available)
eax=fffffffd ebx=03331020 ecx=0058eaec edx=77a96c74 esi=03330fe0 edi=0058eb8c
eip=77a96c74 esp=0058e84c ebp=0058e85c iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
Unable to load image C:\Windows\System32\ntdll.dll, Win32 error 0n2
*** WARNING: Unable to verify timestamp for ntdll.dll
*** ERROR: Module load completed but symbols could not be loaded for ntdll.dll
ntdll+0x46c74:
77a96c74 c3              ret

1.5.2 結合PDB定位具體函式

輸入命令,等待幾秒後會打印出錯誤資訊

    !analyze -v

在這裡插入圖片描述

至此,可以準確找到出現問題的函式。

2. Google Breakpad方案

Google breakpad是一個跨平臺的崩潰轉儲和分析框架和工具集合。

預設情況下,當崩潰時breakpad會生成一個minidump檔案,在不同平臺上的實現機制不一樣:
在windows平臺上,使用微軟提供的 SetUnhandledExceptionFilter() 方法來實現。
在OS X平臺上,通過建立一個執行緒來監聽 Mach Exception port 來實現。
在Linux平臺上,通過設定一個訊號處理器來監聽 SIGILL SIGSEGV 等異常訊號。

Source Code:

http://code.google.com/p/google-breakpad/

該方案將在後續文章中詳細介紹。


Reference:
1.MSDN : SetUnhandledExceptionFilter函式
2.MSDN : MiniDumpWriteDump函式

覺得文章對你有幫助,可以用微信掃描二維碼捐贈給博主,謝謝!
微信
如需轉載請標明出處:http://blog.csdn.net/itas109
QQ技術交流群:129518033