Created
December 8, 2023 14:23
-
-
Save gwaldron/53a18cf7aebee9f95be51cd161bfdae4 to your computer and use it in GitHub Desktop.
Call stack printer (win/linux)
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
#ifdef WIN32 | |
#include <Windows.h> | |
#include <iostream> | |
#include <dbghelp.h> | |
#pragma comment(lib, "dbghelp.lib") | |
void printStackTrace() | |
{ | |
HANDLE process = GetCurrentProcess(); | |
SymInitialize(process, NULL, TRUE); | |
void* stack[100]; | |
WORD frames = CaptureStackBackTrace(0, 100, stack, NULL); | |
SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1); | |
symbol->MaxNameLen = 255; | |
symbol->SizeOfStruct = sizeof(SYMBOL_INFO); | |
for (int i = 0; i < frames; i++) | |
{ | |
SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol); | |
std::cout << i << ": " << symbol->Name << std::endl; | |
} | |
free(symbol); | |
} | |
#elif defined(__GNUC__) | |
#include <execinfo.h> | |
#include <iostream> | |
#include <cstdlib> | |
#include <cstring> | |
#include <cxxabi.h> | |
void printStackTrace() | |
{ | |
auto trim = [](const char* in, std::string& out) { | |
out = {}; | |
std::string temp(in); | |
auto start = temp.find_first_of('('); | |
auto end = temp.find_first_of('+', start); | |
out = temp.substr(start + 1, end - 1 - start); | |
}; | |
void* stack[100]; | |
int frames = backtrace(stack, 100); | |
char** symbols = backtrace_symbols(stack, frames); | |
for (int i = 0; i < frames; ++i) { | |
std::string buf; | |
int status = -1; | |
trim(symbols[i], buf); | |
char* demangled = abi::__cxa_demangle(buf.c_str(), nullptr, nullptr, &status); | |
if (status == 0) { | |
buf = demangled; | |
free(demangled); | |
} | |
std::cout << i << ": " << buf << std::endl; | |
if (buf == "main") | |
break; | |
} | |
free(symbols); | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment