C++从LPEXCEPTION_POINTERS获取调用堆栈
#pragma once #include <map>
#include <vector> struct FunctionCall
{
DWORD64 Address;
std::string ModuleName;
std::string FunctionName;
std::string FileName;
int LineNumber; public:
FunctionCall() :
Address(0),
ModuleName(""),
FunctionName(""),
FileName(""),
LineNumber(0)
{
} public:
static std::string GetFileName(const std::string& fullpath)
{
size_t index = fullpath.find_last_of('\\');
if (index == std::string::npos)
{
return fullpath;
} return fullpath.substr(index + 1);
}
}; class StackTracer
{
public:
static std::string GetExceptionStackTrace(LPEXCEPTION_POINTERS e); private:
// Always return EXCEPTION_EXECUTE_HANDLER after getting the call stack
LONG ExceptionFilter(LPEXCEPTION_POINTERS e); // return the exception message along with call stacks
std::string GetExceptionMsg(); // Return exception code and call stack data structure so that
// user could customize their own message format
DWORD GetExceptionCode();
std::vector<FunctionCall> GetExceptionCallStack(); private:
StackTracer(void);
~StackTracer(void); // The main function to handle exception
LONG __stdcall HandleException(LPEXCEPTION_POINTERS e); // Work through the stack upwards to get the entire call stack
void TraceCallStack(CONTEXT* pContext); private:
DWORD m_dwExceptionCode; std::vector<FunctionCall> m_vecCallStack; typedef std::map<DWORD, const char*> CodeDescMap;
CodeDescMap m_mapCodeDesc; DWORD m_dwMachineType; // Machine type matters when trace the call stack (StackWalk64) };
#include "stdafx.h"
#include "StackTracer.h"
#include <sstream>
#include <tchar.h> #pragma warning(push)
#pragma warning(disable : 4091)
#include <DbgHelp.h>
#pragma warning(pop) #pragma comment(lib, "Dbghelp.lib") const int CALLSTACK_DEPTH = 24; // Translate exception code to description
#define CODE_DESCR(code) CodeDescMap::value_type(code, #code) StackTracer::StackTracer(void)
:m_dwExceptionCode(0)
{
// Get machine type
m_dwMachineType = 0;
size_t Count = 256;
TCHAR wszProcessor[256] = { 0 };
::_tgetenv_s(&Count, wszProcessor, _T("PROCESSOR_ARCHITECTURE")); if (wszProcessor)
{
if ((!wcscmp(_T("EM64T"), wszProcessor)) || !wcscmp(_T("AMD64"), wszProcessor))
{
m_dwMachineType = IMAGE_FILE_MACHINE_AMD64;
}
else if (!wcscmp(_T("x86"), wszProcessor))
{
m_dwMachineType = IMAGE_FILE_MACHINE_I386;
}
} // Exception code description
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_ACCESS_VIOLATION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_DATATYPE_MISALIGNMENT));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_BREAKPOINT));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_SINGLE_STEP));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_ARRAY_BOUNDS_EXCEEDED));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_DENORMAL_OPERAND));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_DIVIDE_BY_ZERO));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_INEXACT_RESULT));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_INVALID_OPERATION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_OVERFLOW));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_STACK_CHECK));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_FLT_UNDERFLOW));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_INT_DIVIDE_BY_ZERO));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_INT_OVERFLOW));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_PRIV_INSTRUCTION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_IN_PAGE_ERROR));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_ILLEGAL_INSTRUCTION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_NONCONTINUABLE_EXCEPTION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_STACK_OVERFLOW));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_INVALID_DISPOSITION));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_GUARD_PAGE));
m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_INVALID_HANDLE));
//m_mapCodeDesc.insert(CODE_DESCR(EXCEPTION_POSSIBLE_DEADLOCK));
// Any other exception code???
} StackTracer::~StackTracer(void)
{
} std::string StackTracer::GetExceptionStackTrace(LPEXCEPTION_POINTERS e)
{
StackTracer tracer;
tracer.HandleException(e); return tracer.GetExceptionMsg();
} LONG StackTracer::ExceptionFilter(LPEXCEPTION_POINTERS e)
{
return HandleException(e);
} std::string StackTracer::GetExceptionMsg()
{
std::ostringstream m_ostringstream; // Exception Code
CodeDescMap::iterator itc = m_mapCodeDesc.find(m_dwExceptionCode); char Code[72];
sprintf_s(Code, "0x%x", m_dwExceptionCode); m_ostringstream << "Exception Code: " << Code << "\r\n"; if (itc != m_mapCodeDesc.end())
{
m_ostringstream << "Exception: " << itc->second << "\r\n";
} // m_ostringstream << "------------------------------------------------------------------\r\n"; // Call Stack
std::vector<FunctionCall>::iterator itbegin = m_vecCallStack.begin();
std::vector<FunctionCall>::iterator itend = m_vecCallStack.end();
std::vector<FunctionCall>::iterator it;
for (it = itbegin; it < itend; it++)
{
std::string strModule = it->ModuleName.empty() ? "UnknownModule" : it->ModuleName; m_ostringstream << strModule << " ";
char Addrs[128];
sprintf_s(Addrs, "0x%llx", it->Address);
m_ostringstream << Addrs; if (!it->FunctionName.empty())
{
m_ostringstream << " " << it->FunctionName;
} if (!it->FileName.empty())
{
m_ostringstream << " " << it->FileName << "[" << it->LineNumber << "]";
} m_ostringstream << "\r\n";
} return m_ostringstream.str();
} DWORD StackTracer::GetExceptionCode()
{
return m_dwExceptionCode;
} std::vector<FunctionCall> StackTracer::GetExceptionCallStack()
{
return m_vecCallStack;
} LONG __stdcall StackTracer::HandleException(LPEXCEPTION_POINTERS e)
{
m_dwExceptionCode = e->ExceptionRecord->ExceptionCode;
m_vecCallStack.clear(); HANDLE hProcess = INVALID_HANDLE_VALUE; // Initializes the symbol handler
if (!SymInitialize(GetCurrentProcess(), NULL, TRUE))
{
SymCleanup(hProcess);
return EXCEPTION_EXECUTE_HANDLER;
} // Work through the call stack upwards.
TraceCallStack(e->ContextRecord); // ...
SymCleanup(hProcess); return(EXCEPTION_EXECUTE_HANDLER);
} // Work through the stack to get the entire call stack
void StackTracer::TraceCallStack(CONTEXT* pContext)
{
// Initialize stack frame
STACKFRAME64 sf;
memset(&sf, 0, sizeof(STACKFRAME)); #if defined(_WIN64)
sf.AddrPC.Offset = pContext->Rip;
sf.AddrStack.Offset = pContext->Rsp;
sf.AddrFrame.Offset = pContext->Rbp;
#elif defined(WIN32)
sf.AddrPC.Offset = pContext->Eip;
sf.AddrStack.Offset = pContext->Esp;
sf.AddrFrame.Offset = pContext->Ebp;
#endif
sf.AddrPC.Mode = AddrModeFlat;
sf.AddrStack.Mode = AddrModeFlat;
sf.AddrFrame.Mode = AddrModeFlat; if (0 == m_dwMachineType)
return; // Walk through the stack frames.
HANDLE hProcess = GetCurrentProcess();
HANDLE hThread = GetCurrentThread();
while (StackWalk64(m_dwMachineType, hProcess, hThread, &sf, pContext, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0))
{
if (sf.AddrFrame.Offset == 0 || m_vecCallStack.size() >= CALLSTACK_DEPTH)
break; // 1. Get function name at the address
const int nBuffSize = (sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64);
ULONG64 symbolBuffer[nBuffSize];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbolBuffer; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME; FunctionCall curCall;
curCall.Address = sf.AddrPC.Offset; DWORD64 moduleBase = SymGetModuleBase64(hProcess, sf.AddrPC.Offset);
char ModuleName[MAX_PATH];
if (moduleBase && GetModuleFileNameA((HINSTANCE)moduleBase, ModuleName, MAX_PATH))
{
curCall.ModuleName = FunctionCall::GetFileName(ModuleName);
} DWORD64 dwSymDisplacement = 0;
if (SymFromAddr(hProcess, sf.AddrPC.Offset, &dwSymDisplacement, pSymbol))
{
curCall.FunctionName = std::string(pSymbol->Name);
} //2. get line and file name at the address
IMAGEHLP_LINE64 lineInfo = { sizeof(IMAGEHLP_LINE64) };
DWORD dwLineDisplacement = 0; if (SymGetLineFromAddr64(hProcess, sf.AddrPC.Offset, &dwLineDisplacement, &lineInfo))
{
curCall.FileName = FunctionCall::GetFileName(std::string(lineInfo.FileName));
curCall.LineNumber = lineInfo.LineNumber;
} // Call stack stored
m_vecCallStack.push_back(curCall);
}
}
参考并优化自:https://www.codeproject.com/Articles/41923/Get-the-call-stack-when-an-exception-is-being-caug
C++从LPEXCEPTION_POINTERS获取调用堆栈的更多相关文章
- C/C++中手动获取调用堆栈【转】
转自:http://blog.csdn.net/kevinlynx/article/details/39269507 版权声明:本文为博主原创文章,未经博主允许不得转载. 当我们的程序core掉之后, ...
- delphi中获取调用堆栈信息
异常堆栈有利于分析程序的错误,Delphi的Exception有StackTrace属性,但是值为空,因为StackTrace的信息收集Delphi委托给了第三方组件来完成,真是脑子有毛病! 借助于m ...
- VC++ 崩溃处理以及打印调用堆栈
title: VC++ 崩溃处理以及打印调用堆栈 tags: [VC++, 结构化异常处理, 崩溃日志记录] date: 2018-08-28 20:59:54 categories: windows ...
- C#获取当前堆栈的各调用方法列表
在使用.NET编写的代码在debug时很容易进行排查和定位问题,一旦项目上线并出现问题的话那么只能依靠系统日志来进行问题排查和定位,但当项目复杂时,即各种方法间相互调用将导致要获取具体的出错方法或调用 ...
- c# 如何获取当前方法的调用堆栈
c# 调试程序时常常需要借助 call stack 查看调用堆栈,实际上通过code也可以获取: class Program { static void Main(string[] args) { T ...
- 在 Visual Studio 中调试时映射调用堆栈上的方法
本文转自:https://msdn.microsoft.com/zh-cn/library/dn194476.aspx 1.创建代码图,以便在调试时对调用堆栈进行可视化跟踪. 你可以在图中进行标注以跟 ...
- .NET 中获取调用方法名
在写记录日志功能时,需要记录日志调用方所在的模块名.命名空间名.类名以及方法名,想到使用的是反射(涉及到反射请注意性能),但具体是哪一块儿还不了解,于是搜索,整理如下: 需要添加相应的命名空间: us ...
- Windbg查看调用堆栈(k*)
无论是分析程序崩溃原因,还是解决程序hang问题,我们最常查看的就是程序调用堆栈.学会windbg调用堆栈命令,以及理解堆栈中的各个参数的意义就显得至关重要. 上图就是一个典型的Win ...
- 怎样重建一个损坏的调用堆栈(callstack)
原文作者:Aaron Ballman原文时间:2011年07月04日原文地址:http://blog.aaronballman.com/2011/07/reconstructing-a-corrupt ...
随机推荐
- LeetCode 164. Maximum Gap[翻译]
164. Maximum Gap 164. 最大间隔 Given an unsorted array, find the maximum difference between the successi ...
- 面试:Java基础知识(一)
1.面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节.抽 ...
- android基本操作
1.页面跳转 activity_main.xml <?xml version="1.0" encoding="utf-8"?> <androi ...
- jQuery 多库共存
多库共存 问题概述 jQuery使用$作为标识符,随着jQuery的流行,其他js的库也会用$作为标识符,这样就会引起冲突 需要一个解决方案 让jQuery和其他的JS ...
- C# ASP JS引用路径不正确导致的错误
假设JS包放在根目录下的Scripts文件夹下 当前页的路径在另一个文件夹下,那么他引用JS应该:<script src="../Scripts/jquery-1.4.1.min.js ...
- 2020-04-24:Object obj = new Object()这句话在内存里占用了多少内存
福哥答案2020-04-25:这道题最好把对象和变量分开说明,否则容易产生误解.以下都是64位环境下.针对对象:压缩状态:MarkWord 8+klass 4+数据0+对齐4=16非压缩状态:Mark ...
- Visual Studio 2019预览,净生产力
本文章为机器翻译. https://blogs.msdn.microsoft.com/dotnet/2018/12/13/visual-studio-2019-net-productivity/ 该文 ...
- C#LeetCode刷题之#409-最长回文串(Longest Palindrome)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3788 访问. 给定一个包含大写字母和小写字母的字符串,找到通过这 ...
- HTTP PUT/POST/PATCH的区别
幂等 idempotent 幂等操作的特定就是其任意多次执行所产生的影响与一次执行的影响相同 POST POST 用来创建一个新的数据 POST 不是幂等的, 意味着多次操作的结果是不同的, 多次操作 ...
- .net Core使用sql语句实现批量修改数据状态
上图为查出的所有满足条件的数据,要选中若干条数据将其状态设置为作废 一共选中6条数据,当点击确认后修改数据状态. 前端代码 1.安装NuGet包 [Abp.Dapper]于EFCore中, 2.创建文 ...