GenerateMiniDump.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef GENERATEMINIDUMP_H
  2. #define GENERATEMINIDUMP_H
  3. #include <QtGlobal>
  4. #include <QDebug>
  5. #ifdef Q_CC_MSVC
  6. #include <Windows.h>
  7. #include <DbgHelp.h>
  8. #include <tchar.h>
  9. #pragma comment(lib, "user32.lib")
  10. int GenerateMiniDump(PEXCEPTION_POINTERS pExceptionPointers)
  11. {
  12. qDebug() << "GenerateMiniDump";
  13. // 定义函数指针
  14. typedef BOOL(WINAPI * MiniDumpWriteDumpT)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION,
  15. PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION);
  16. // 从 "DbgHelp.dll" 库中获取 "MiniDumpWriteDump" 函数
  17. MiniDumpWriteDumpT pfnMiniDumpWriteDump = NULL;
  18. HMODULE hDbgHelp = LoadLibrary(_T("DbgHelp.dll"));
  19. if (NULL == hDbgHelp) { return EXCEPTION_CONTINUE_EXECUTION; }
  20. pfnMiniDumpWriteDump = (MiniDumpWriteDumpT)GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
  21. if (NULL == pfnMiniDumpWriteDump) {
  22. FreeLibrary(hDbgHelp);
  23. return EXCEPTION_CONTINUE_EXECUTION;
  24. }
  25. // 创建 dmp 文件
  26. TCHAR szFileName[MAX_PATH] = { 0 };
  27. TCHAR szVersion[] = L"DumpFile";
  28. SYSTEMTIME stLocalTime;
  29. GetLocalTime(&stLocalTime);
  30. wsprintf(szFileName, L"%s-%04d%02d%02d-%02d%02d%02d.dmp", szVersion, stLocalTime.wYear, stLocalTime.wMonth,
  31. stLocalTime.wDay, stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond);
  32. HANDLE hDumpFile = CreateFile(szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, 0,
  33. CREATE_ALWAYS, 0, 0);
  34. if (INVALID_HANDLE_VALUE == hDumpFile) {
  35. FreeLibrary(hDbgHelp);
  36. return EXCEPTION_CONTINUE_EXECUTION;
  37. }
  38. // 写入 dmp 文件
  39. MINIDUMP_EXCEPTION_INFORMATION expParam;
  40. expParam.ThreadId = GetCurrentThreadId();
  41. expParam.ExceptionPointers = pExceptionPointers;
  42. expParam.ClientPointers = FALSE;
  43. pfnMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpWithDataSegs,
  44. (pExceptionPointers ? &expParam : NULL), NULL, NULL);
  45. // 释放文件
  46. CloseHandle(hDumpFile);
  47. FreeLibrary(hDbgHelp);
  48. return EXCEPTION_EXECUTE_HANDLER;
  49. }
  50. LONG WINAPI ExceptionFilter(LPEXCEPTION_POINTERS lpExceptionInfo)
  51. {
  52. // 这里做一些异常的过滤或提示
  53. if (IsDebuggerPresent()) { return EXCEPTION_CONTINUE_SEARCH; }
  54. return GenerateMiniDump(lpExceptionInfo);
  55. }
  56. #define DUMP_FILE_HOOK_HANLE SetUnhandledExceptionFilter(ExceptionFilter)
  57. #else
  58. #define DUMP_FILE_HOOK_HANLE
  59. #endif
  60. #endif // GENERATEMINIDUMP_H