Search code examples
code-injectiondll-injection

How to generate 0xE8 (call) opcode with C++


Basically, what I have is a game which has a function MyFunc(), and it's called on 4 places in the game. One of the addresses is 0x10002000, and the bytes are E8 0B 83 01 00.

I'm injecting a DLL, and want to patch that 0xE8 (call) to my own address. When I do it with Cheat Engine's Auto Assembler and write call MYADDRESS, it generates the proper opcode, and proper bytes.

However, if I do it with the DLL, this is what I get: Cheat Engine

What I want to achieve is call 74C611CC. So I need to generate the bytes for the opcode to be like I want instead of what is it currently (in the screenshot)

I use this kind of code:

*(BYTE*) dwPatchAddr = 0xE8;
*(DWORD*) (dwPatchAddr + 1) = (DWORD) myFunc;

Solution

  • An e8 instruction is a relative call instruction, not absolute. So the next 4 bytes need to be the difference between the pc when processing this instruction and your target function. So what you want is:

    *(BYTE *)dwPatchAddr = 0xE8;
    *(DWORD *)(dwPatchAddr + 1) = (DWORD)((char *)myFunc - (char *)(dwPatchAddr + 5));
    

    Note that the PC address used to compute the offset is actually the address of the next instruction after the call (what will also be pushed as the return address).