1、注册自定义的UnhandledExceptionFilter,C/C++ Runtime Library下需要注意自定义handler被移除(hook kernel32.dll的SetUnhandledExceptionFilter使它返回一个空指针即可)。
PTOP_LEVEL_EXCEPTION_FILTER v_prevUnhandledExceptionFilter;LONG WINAPI UnhandledExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo);v_prevUnhandledExceptionFilter = ::SetUnhandledExceptionFilter(UnhandledExceptionHandler);LONG WINAPI UnhandledExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo) {GenerateCrashDump(ExceptionInfo);if (v_prevUnhandledExceptionFilter != nullptr)return v_prevUnhandledExceptionFilter(ExceptionInfo);return EXCEPTION_CONTINUE_SEARCH; }
2、调用DbgHelp.dll的MiniDumpWriteDump函数。
void GenerateCrashDump(EXCEPTION_POINTERS* ExceptionInfo) {SYSTEMTIME st = { 0 };GetSystemTime(&st);auto path = String::Format(L"%s%04u-%02u-%02u_%02u-%02u-%02u.dmp", v_logsDir.c_str(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);auto dumpType = (MINIDUMP_TYPE) (MiniDumpNormal | MiniDumpWithHandleData | MiniDumpWithUnloadedModules);auto hFile = ::CreateFile(path.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);if (hFile == INVALID_HANDLE_VALUE)return;auto hProcess = ::GetCurrentProcess();auto processId = ::GetCurrentProcessId();MINIDUMP_EXCEPTION_INFORMATION mei = { 0 };mei.ThreadId = GetCurrentThreadId();mei.ClientPointers = FALSE;mei.ExceptionPointers = ExceptionInfo;::MiniDumpWriteDump(hProcess, processId, hFile, dumpType, &mei, nullptr, nullptr);::CloseHandle(hFile); }