1、简介
程序开发时无法避免碰到各种崩溃问题,记录下出现崩溃问题查找BUG方法,代码如下
2、提示,只测试了该方法在QT msvc编译器的效果,MinWG变一下生成的dmp文件名为乱码
// An highlighted block
#include <Windows.h>
#include <DbgHelp.h>
#include <winnt.h>
#include <time.h>
#include <locale>
#include <codecvt>
#include <tchar.h>
LONG __stdcall ApplicationCrashHandler(EXCEPTION_POINTERS *pException)
{
//程式异常捕获
//创建 Dump 文件
char str_time[100];
memset(str_time, 0, 100);
struct tm *local_time = NULL;
time_t utc_time;
utc_time = time(NULL);
local_time = localtime(&utc_time);
strftime(str_time, 100, "%Y%m%d%H%M%S", local_time);
std::string timeStr(str_time);
std::string dumpFilePath = timeStr + ".dmp";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(dumpFilePath);
HANDLE hDumpFile = CreateFile(wide.c_str(),GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
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);
}
//这里弹出一个错误对话框并退出程序
EXCEPTION_RECORD* record = pException->ExceptionRecord;
fprintf(stderr, "record->ExceptionCode:%lu\n", record->ExceptionCode);
return EXCEPTION_EXECUTE_HANDLER;
}
void DisableSetUnhandledExceptionFilter()
{
HMODULE h_hand = LoadLibrary(TEXT("kernel32.dll"));
void *addr = (void*)GetProcAddress(h_hand,"SetUnhandledExceptionFilter");
if (addr)
{
unsigned char code[16];
int size = 0;
code[size++] = 0x33;
code[size++] = 0xC0;
code[size++] = 0xC2;
code[size++] = 0x04;
code[size++] = 0x00;
DWORD dwOldFlag, dwTempFlag;
VirtualProtect(addr, size, PAGE_READWRITE, &dwOldFlag);
printf("WriteProcessMemory start!\n");
WriteProcessMemory(GetCurrentProcess(), addr, code, size, NULL);
printf("WriteProcessMemory end!\n");
VirtualProtect(addr, size, dwOldFlag, &dwTempFlag);
}
}
void RunCrashHandlerLocal()
{
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);//注册异常捕获函数
}
int main(int argc, char *argv[])
{
RunCrashHandlerLocal();
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}