简体   繁体   中英

How do I resume execution after using ud2 with vectored exception handling?

I want to trigger an exception using ud2 , record information about the exception, then continue execution from there. Right now my code is stuck in an infinite loop of repeatedly reexecuting ud2


#include <Windows.h>
#include <iostream>

void resumeFromUD2()
{
    PVOID handler = AddVectoredExceptionHandler(1, [](struct _EXCEPTION_POINTERS* ExceptionInfo)->LONG
        {
            std::cout << "vectored exception handled\n";
            std::cout << "exception code: " << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << std::dec << "\n";
            return EXCEPTION_CONTINUE_EXECUTION;
        });
    int testValue = 0;

    testValue++;
    __ud2();
    testValue++;

    //should be 2
    std::cout << "testValue: " << testValue << '\n';
    RemoveVectoredExceptionHandler(handler);
}

The problem is that the ud2 instruction doesn't increment the instruction pointer, meaning that it triggers the exception, then resumes right where it left off, executing ud2 again and triggering the exception again.

You can fix this by manually moving the instruction pointer forward by two bytes (the size of the ud2 instruction), thus resuming execution.

This can be done by modifying the instruction pointer via the _EXCEPTION_POINTERS structure that gets passed to the exception handler.

That code looks like this:

#include <Windows.h>
#include <iostream>

void resumeFromUD2()
{
    PVOID handler = AddVectoredExceptionHandler(1, [](struct _EXCEPTION_POINTERS* ExceptionInfo)->LONG
        {
            ExceptionInfo->ContextRecord->Rip += 2;
            std::cout << "vectored exception handled\n";
            std::cout << "exception code: " << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << std::dec << "\n";
            return EXCEPTION_CONTINUE_EXECUTION;
        });
    int testValue = 0;

    testValue++;
    __ud2();
    testValue++;

    //should be 2
    std::cout << "testValue: " << testValue << '\n';
    RemoveVectoredExceptionHandler(handler);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM