Skip to content

Implement SEH (Structured Exception Handling) #3

Description

@AlexMacocian

VC++ supports handling terminating exceptions such as memory access violation with a special syntax

__try {
    // Code that might throw an exception
} __except (EXCEPTION_EXECUTE_HANDLER) {
    // Exception handling code
}

We can then retrieve the stacktrace

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

void LogStackTrace() {
    // Initialize stack walking
    HANDLE process = GetCurrentProcess();
    HANDLE thread = GetCurrentThread();

    CONTEXT context = {};
    context.ContextFlags = CONTEXT_FULL;
    RtlCaptureContext(&context);

    STACKFRAME64 stack = {};
    stack.AddrPC.Offset = context.Rip;
    stack.AddrPC.Mode = AddrModeFlat;
    stack.AddrFrame.Offset = context.Rbp;
    stack.AddrFrame.Mode = AddrModeFlat;
    stack.AddrStack.Offset = context.Rsp;
    stack.AddrStack.Mode = AddrModeFlat;

    while (StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &stack, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) {
        std::cout << "Address: " << stack.AddrPC.Offset << std::endl;
        // Additional code to resolve symbols
    }
}

Finally, before crashing the process, we could show a MessageBox with the name of the error and we could log the stacktrace somewhere

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingenhancementNew feature or request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions