Toribio
Toribio

Reputation: 4078

Call a function twice with Assembly and C++

I have a code that changes the function that would be called, to my new function, but I don't want to call only my new function, I also want to call the old one. This is an example, so you can understand what I'm saying:

If I disassemble my .exe, I will look at this part:

L00123456:
      mov   eax, [L00654321] //doesn't matter
      mov   ecx, [eax+1Ch]   //doesn't matter
      push  esi              //the only parameter
0x123 call  SUB_L00999999    //this is the function I wanna overwrite
      //...

(0x123 is the address of that line) So, I used this code:

DWORD old;
DWORD from = 0x123;
DWORD to   = MyNewFunction;
VirtualProtect(from, 5, PAGE_EXECUTE_READWRITE, &old);

DWORD disp = to - (from + 5);
*(BYTE *)(from) = 0xE8;
*(DWORD *)(from + 1) = (DWORD)disp;

Now, instead of calling SUB_L00999999, it calls MyNewFunction...

So... any ideas on how can I still call the old function?

I tried things like this (in many ways), but it crashes my application:

int MyNewFunction(int parameter)
{
    DWORD oldfunction = 0x00999999;
    _asm push parameter
    _asm call oldfunction
}

Notes: I use Visual Studio C++ 2010 and these codes are in a .dll loaded in an .exe.

Thanks.

Upvotes: 4

Views: 1364

Answers (2)

user388225
user388225

Reputation:

I had a problem like this a while back. Anyway, _asm call dword ptr [oldfunction] worked for me.

Upvotes: 2

Mark H
Mark H

Reputation: 13897

ret expects the top stack argument to be the address to return to. You can exploit this by pushing the oldfunction address onto the stack immediately before your ret instruction in your new function. As the call returns (or rather, branches to the oldfunction), the stack pointer will shift to leave the original return address (0x128 here) on top, so the stack will appear undamaged. (same as it should have been had you not taken a detour).

Upvotes: 2

Related Questions