File size: 2,822 Bytes
b27bfb3 | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "cpp-debug-002", "name": "C++ debug stack traces on Windows"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "How to get debug stack traces on Windows"}}
{"type": "message", "message": {"role": "assistant", "content": "**Windows Stack Trace Methods:**\n\n**1. Windows API (dbghelp.h):**\n```cpp\n#include <windows.h>\n#include <dbghelp.h>\n#include <iostream>\n\n#pragma comment(lib, \"dbghelp.lib\")\n\nvoid capture_stack_trace() {\n SymInitialize(GetCurrentProcess(), NULL, TRUE);\n\n void* stack[100];\n USHORT frames = CaptureStackBackTrace(0, 100, stack, NULL);\n\n SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(\n sizeof(SYMBOL_INFO) + 256, 1\n );\n symbol->MaxNameLen = 255;\n symbol->SizeOfStruct = sizeof(SYMBOL_INFO);\n\n IMAGEHLP_LINE64 line = {};\n line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);\n\n for (USHORT i = 0; i < frames; ++i) {\n SymFromAddr(GetCurrentProcess(), (DWORD64)stack[i], 0, symbol);\n DWORD displacement;\n SymGetLineFromAddr64(GetCurrentProcess(), (DWORD64)stack[i], &displacement, &line);\n\n std::cout << i << \": \"\n << symbol->Name << \" at \"\n << line.FileName << \":\" << line.LineNumber << \"\\n\";\n }\n free(symbol);\n}\n```\n\n**2. cpptrace (Cross-platform):**\n```cpp\n#include <cpptrace/cpptrace.hpp>\n\nvoid foo() {\n auto trace = cpptrace::generate_trace();\n trace.print();\n // Works on Windows, Linux, macOS\n}\n```\n\n**3. MiniDump (Crash dumps):**\n```cpp\n#include <minidumpapiset.h>\n\nLONG WINAPI crash_handler(EXCEPTION_POINTERS* info) {\n HANDLE hFile = CreateFile(\n L\"crash.dmp\", GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL\n );\n MiniDumpWriteDump(\n GetCurrentProcess(), GetCurrentProcessId(),\n hFile, MiniDumpNormal, &info->ExceptionRecord, NULL, NULL\n );\n CloseHandle(hFile);\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\n// Install:\nSetUnhandledExceptionFilter(crash_handler);\n```\n\n**4. Visual Studio Debugger:**\n```\n# In Visual Studio\nDebug -> Windows -> Call Stack\n# Or use Autos/Locals windows\n\n# Command window\n> .exr -1 # show exception\n> kb # stack trace\n> dv # dump local variables\n```"}}
|