Created
January 22, 2013 09:53
-
-
Save akihiroy/4593421 to your computer and use it in GitHub Desktop.
Stack trace function for windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#define DBGHELP_TRANSLATE_TCHAR | |
#include <DbgHelp.h> | |
void StackTrace() | |
{ | |
CONTEXT context = {0}; | |
#if defined(_M_X64) | |
RtlCaptureContext(&context); | |
#else | |
__asm call(x); | |
__asm x: pop eax; | |
__asm mov context.Eip, eax; | |
__asm mov context.Ebp, ebp; | |
__asm mov context.Esp, esp; | |
#endif | |
const HANDLE hProcess = ::GetCurrentProcess(); | |
const HANDLE hThread = ::GetCurrentThread(); | |
STACKFRAME64 stack = {0}; | |
stack.AddrPC.Offset = context.Eip; | |
stack.AddrPC.Mode = AddrModeFlat; | |
stack.AddrStack.Offset = context.Esp; | |
stack.AddrStack.Mode = AddrModeFlat; | |
stack.AddrFrame.Offset = context.Ebp; | |
stack.AddrFrame.Mode = AddrModeFlat; | |
SymSetOptions(SymGetOptions() | SYMOPT_UNDNAME); | |
SYMBOL_INFO *pSymbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + sizeof(TCHAR) * 255, 1); | |
std::wstring stack_trace; | |
for (int frame = 0; ; ++frame) | |
{ | |
BOOL result = StackWalk64(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &stack, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL); | |
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); | |
pSymbol->MaxNameLen = 256; | |
DWORD64 displacement; | |
SymFromAddr(hProcess, stack.AddrPC.Offset, &displacement, pSymbol); | |
if (!stack_trace.empty()) stack_trace.append(1, L'\n'); | |
stack_trace.append(pSymbol->Name); | |
if (!result) { | |
break; | |
} | |
} | |
free(pSymbol); | |
wprintf(L"%s", stack_trace.c_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment