tinycodinglm / cpp /cpp-debug-002.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
2.82 kB
opencode trace
System 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 c...

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.

User

How to get debug stack traces on Windows

Assistant

Windows Stack Trace Methods:

1. Windows API (dbghelp.h):

cpp
#include <windows.h>
#include <dbghelp.h>
#include <iostream>

#pragma comment(lib, "dbghelp.lib")

void capture_stack_trace() {
    SymInitialize(GetCurrentProcess(), NULL, TRUE);

    void* stack[100];
    USHORT frames = CaptureStackBackTrace(0, 100, stack, NULL);

    SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(
        sizeof(SYMBOL_INFO) + 256, 1
    );
    symbol->MaxNameLen = 255;
    symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

    IMAGEHLP_LINE64 line = {};
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    for (USHORT i = 0; i < frames; ++i) {
        SymFromAddr(GetCurrentProcess(), (DWORD64)stack[i], 0, symbol);
        DWORD displacement;
        SymGetLineFromAddr64(GetCurrentProcess(), (DWORD64)stack[i], &displacement, &line);

        std::cout << i << ": "
                  << symbol->Name << " at "
                  << line.FileName << ":" << line.LineNumber << "\n";
    }
    free(symbol);
}

2. cpptrace (Cross-platform):

cpp
#include <cpptrace/cpptrace.hpp>

void foo() {
    auto trace = cpptrace::generate_trace();
    trace.print();
    // Works on Windows, Linux, macOS
}

3. MiniDump (Crash dumps):

cpp
#include <minidumpapiset.h>

LONG WINAPI crash_handler(EXCEPTION_POINTERS* info) {
    HANDLE hFile = CreateFile(
        L"crash.dmp", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
    );
    MiniDumpWriteDump(
        GetCurrentProcess(), GetCurrentProcessId(),
        hFile, MiniDumpNormal, &info->ExceptionRecord, NULL, NULL
    );
    CloseHandle(hFile);
    return EXCEPTION_EXECUTE_HANDLER;
}

// Install:
SetUnhandledExceptionFilter(crash_handler);

4. Visual Studio Debugger:

markdown
# In Visual Studio
Debug -> Windows -> Call Stack
# Or use Autos/Locals windows

# Command window
> .exr -1                    # show exception
> kb                         # stack trace
> dv                         # dump local variables