C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Interceptor Function (preserve stack and all registers)

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 30 Jul 2024 11:45:55 +0100
On Tue, Jul 30, 2024 at 12:36 AM Frederick Virchanza Gotham wrote:
>
>
> Here's your recursive interceptor function running on MS-Windows
> x86_32 with the VC++ compiler:
>
> https://godbolt.org/z/f3rfhdshx


In the above GodBolt posted yesterday, I don't preserve the return
value from the original function, as I need to use the EAX register
for other stuff.

I have corrected this. Furthermore I save and restore all registers
(general purpose, flags, segment/special, floating point). At one
point I had it so that the only registers I bulldozed were EAX and
EDX, which was reasonable enough, but then I was able to further
reduce it down to just EAX by changing the following code snippet:

        lea edx, come_back_here // load new return address into temp register
        push edx // set new return address at top of stack
        jmp eax // jump to original function

into:

        // Here comes a sneaky trick to not need another register:
        // We put something at the top of the stack but we don't
        // decrement the stack pointer (so it's hidden there)
        mov [esp-4], eax // address of original function now hidden
        add esp, 4 // remove return address from top of stack
        lea eax, come_back_here // load new return address into temp register
        push eax // set new return address at top of stack
        mov eax, 0 // not needed but less confusing for debugger
        jmp DWORD PTR[esp-4] // jump to original function

Here's the GodBolt for a recursive interceptor function running on
MS-Windows x86_32 with the VC++ compiler, preserving every single
register except for EAX:

    https://godbolt.org/z/z1cdMovjv

Received on 2024-07-30 10:46:10