//打印堆栈
#include <stdarg.h>
#include <windows.h>
//#include <dbghelp.h>
#include <stdio.h>
#if _MSC_VER
#define snprintf _snprintf
#endif
#define STACK_INFO_LEN 1024
static int vsnprintf_s(char* buf, size_t len, const char* fmt, va_list arg)
{
return ::vsnprintf_s(buf, len, _TRUNCATE, fmt, arg);
}
static int vsnprintf_s(wchar_t* buf, size_t len, const wchar_t* fmt, va_list arg)
{
return ::_vsnwprintf_s(buf, len, _TRUNCATE, fmt, arg);
}
static int snprintf_s(char* buf, size_t len, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int nRes = vsnprintf_s(buf, len, fmt, args);
va_end(args);
return nRes;
}
void ShowTraceStack(char* szBriefInfo)
{
static const int MAX_STACK_FRAMES = 12;
void* pStack[MAX_STACK_FRAMES];
static char szStackInfo[STACK_INFO_LEN * MAX_STACK_FRAMES];
static char szFrameInfo[STACK_INFO_LEN];
HANDLE process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
WORD frames = CaptureStackBackTrace(0, MAX_STACK_FRAMES, pStack, NULL);
strcpy(szStackInfo, szBriefInfo == NULL ? "stack traceback:\n" : szBriefInfo);
strcat(szStackInfo, " ");
for (WORD i = 0; i < frames; ++i) {
DWORD64 address = (DWORD64)pStack[i];
DWORD64 displacementSym = 0;
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
DWORD displacementLine = 0;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (SymFromAddr(process, address, &displacementSym, pSymbol) &&
SymGetLineFromAddr64(process, address, &displacementLine, &line))
{
snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\t%s() at %s:%d(0x%x)\n",
pSymbol->Name, line.FileName, line.LineNumber, pSymbol->Address);
}
else
{
snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\terror: %d\n", GetLastError());
}
strcat(szStackInfo, szFrameInfo);
}
MyLog(L"%s", CString(szStackInfo));
}