1

I want to use an exception/trap handler from assembly, but I don't know how to actually modify the context of the offending frame.

My code:

_TEXT segment para 'CODE'
    MyHandler proc
        call printout
        ret
    MyHandler endp

    public SyntaxTest
    SyntaxTest proc frame:MyHandler
        .endprolog
        ud2
        .beginepilog
        ret
    SyntaxTest endp
_TEXT ends

Right now, when ud2 is executed, the code jumps to MyHandler, calls the printout function (implemented elsewhere), then resumes execution in the exact same spot, creating an infinite loop. How do I fix this?

Badasahog
  • 579
  • 2
  • 19

1 Answers1

3

MyHandler (function in FRAME :ehandler-address ) this is so called Language-specific handler . so it must have signature:

EXCEPTION_DISPOSITION __cdecl MyHandler(
    _In_ PEXCEPTION_RECORD ExceptionRecord,
    _In_ void * EstablisherFrame,
    _Inout_ PCONTEXT ContextRecord,
    _Inout_ PDISPATCHER_CONTEXT DispatcherContext
    );

if you want continue execution - you must return ExceptionContinueExecution and modify ContextRecord - the Rip ( say Rip += 2 for skip ud2 ). the printout probably return 0, but you not fix Rip as result the ud2 executed again. the absolute minimum, demo only code

CONTEXT STRUCT 16
    _P1Home DQ ?;
    _P2Home DQ ?;
    _P3Home DQ ?;
    _P4Home DQ ?;
    _P5Home DQ ?;
    _P6Home DQ ?;

    ;
    ; Control flags.
    ;

    _ContextFlags DD ?;
    _MxCsr DD ?;

    ;
    ; Segment Registers and processor flags.
    ;

    _SegCs DW ?;
    _SegDs DW ?;
    _SegEs DW ?;
    _SegFs DW ?;
    _SegGs DW ?;
    _SegSs DW ?;
    _EFlags DD ?;

    ;
    ; Debug registers
    ;

    _Dr0 DQ ?;
    _Dr1 DQ ?;
    _Dr2 DQ ?;
    _Dr3 DQ ?;
    _Dr6 DQ ?;
    _Dr7 DQ ?;

    ;
    ; Integer registers.
    ;

    _Rax DQ ?;
    _Rcx DQ ?;
    _Rdx DQ ?;
    _Rbx DQ ?;
    _Rsp DQ ?;
    _Rbp DQ ?;
    _Rsi DQ ?;
    _Rdi DQ ?;
    _R8 DQ ?;
    _R9 DQ ?;
    _R10 DQ ?;
    _R11 DQ ?;
    _R12 DQ ?;
    _R13 DQ ?;
    _R14 DQ ?;
    _R15 DQ ?;

    ;
    ; Program counter.
    ;

    _Rip DQ ?;
CONTEXT ENDS

.code
MyHandler proc
    add [r8][CONTEXT._Rip],2
    xor eax,eax
    ret
MyHandler endp


SyntaxTest proc frame:MyHandler
    .endprolog
    ud2
    .beginepilog
    ret
SyntaxTest endp
end

of course in real code need analyze source of exeption, and select what need todo based on this. but not hardcode rip += 2 and continue.

RbMm
  • 31,280
  • 3
  • 35
  • 56