赞
踩
windows程序在运行时有时候会发生未知的异常错误,有时候调试也不太好定位,此时就需要加载调试dump文件来查找异常,因此需要生成dump异常文件。
namespace DumpError
{
void DbgDumpErrorFile(struct _EXCEPTION_POINTERS* excpInfo, const char* szDmpFile);
void DbgDumpErrorFileEx(struct _EXCEPTION_POINTERS* excpInfo, const char* szDmpFilePrex);
};
void DumpError::DbgDumpErrorFileEx(struct _EXCEPTION_POINTERS* excpInfo, const char* szDmpFilePrex)
{
char szDumpPath[2 * _MAX_PATH] = {0};
char szDumpFile[_MAX_PATH] = {0};
GetModuleFileNameA(nullptr, szDumpPath, _MAX_PATH);
char* szPos = strrchr(szDumpPath, _T('\\'));
if (szPos == nullptr)
return;
szPos[1] = 0;
strcat(szDumpPath, "log"); // NOLINT
_mkdir(szDumpPath);
time_t timeCurrent = time(nullptr);
const struct tm* tmc = localtime(&timeCurrent);
if (tmc)
sprintf_s(szDumpFile, _MAX_PATH, "\\%s%d_%d_%d_%d_%d(0x%p).dmp", szDmpFilePrex, tmc->tm_mon + 1, tmc->tm_mday, tmc->tm_hour, tmc->tm_min, tmc->tm_sec, excpInfo);
else
strcpy_s(szDumpFile, _MAX_PATH, "\\error.dmp");
strcat(szDumpPath, szDumpFile); // NOLINT
DbgDumpErrorFile(excpInfo, szDumpPath);
}
void DumpError::DbgDumpErrorFile(struct _EXCEPTION_POINTERS* excpInfo, const char* szDmpFile)
{
HMODULE hDll = ::LoadLibraryA("DBGHELP.DLL");
MINIDUMPWRITEDUMP pDump = nullptr;
if (hDll)
pDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump");
if (pDump)
{
// create the file
HANDLE hFile = ::CreateFileA(szDmpFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile != INVALID_HANDLE_VALUE)
{
if (excpInfo == nullptr) // 如果没有传入异常, 比如是在程序里面调用的, 生成一个异常
{
// Generate exception to get proper context in dump
DWORD dwSize = 0;
const char* sz = "_EXCEPTION_POINTERS is null";
::WriteFile(hFile, sz, static_cast<int>(strlen(sz)), &dwSize, nullptr);
}
else
{
MINIDUMP_EXCEPTION_INFORMATION eInfo{};
eInfo.ThreadId = GetCurrentThreadId(); // 把需要的信息添进去
eInfo.ExceptionPointers = excpInfo;
eInfo.ClientPointers = FALSE;
// Dump的类型是小型的, 节省空间. 可以参考MSDN生成更详细的Dump.
pDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hFile,
MiniDumpNormal,
excpInfo ? &eInfo : nullptr,
nullptr,
nullptr);
}
::CloseHandle(hFile);
}
}
if (hDll)
::FreeLibrary(hDll);
}
int ExceptFilterFunc(EXCEPTION_POINTERS* pExp)
{
HRDErrorUtils::DbgDumpErrorFileEx(pExp, "main");
return EXCEPTION_EXECUTE_HANDLER;
}
int main(int argc, char* argv[])
{
int nRet = 0;
__try
{
nRet = DoSomething(argc, argv);
}
__except (ExceptFilterFunc(GetExceptionInformation()))
{
OutputDebugString(L"DoSomething Except");
nRet = 0;
}
OutputDebugString(L"ain return ");
return nRet;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。