Creating a Detour
First thing you need to understand - to write a jump in binary it is NOT a simple case of doing: JMP <addr> in bytes!
To jump to the right address you must do:
So lets say we want to jump to 0x12345678 and the jump is at 0x55555555:
So, to make our Detour we need a pointer to the original function, the hook, and the length:
Next we allocate a place in memory for the bytes we are going to overwrite in the original, plus the size of a jump <address> instruction:
Next we want to allow read & write access to the memory at the original function, and save the previous access to dwProt:
Now we want to copy the bytes of original + length to the allocated memory place:
Next we want to insert a jump back to the original + length at the end of those intructions we just copied over:
For good practice we want to NOP out all the bytes at the original that we have saved to the memory allocated place:
Now we want to write a jump at the original to the hooked function:
Next we want to put back the old protection flags:
And finally we want to return a pointer to the start of the memory allocated place (we incremented the pointer by length before, so now we do jmp - length)
Usage:
Credits:
Dwar
To jump to the right address you must do:
Code:
address = (place_we_want_to_jump_to + start_of_memory_where_jump_is_at) - size_of_a_jmp_address
Code:
address = (0x12345678 + 0x55555555) - 5; //5 is the size of the JMP instruction
Code:
void *DetourFunction(BYTE *orig, BYTE *hook, int len)
{
DWORD dwProt = 0;
Code:
BYTE *jmp = (BYTE*)malloc(len+5);
Code:
VirtualProtect(orig, len, PAGE_READWRITE, &dwProt);
Code:
memcpy(jmp, orig, len);
Code:
jmp += len; // increment to the end of the copied bytes jmp[0] = JMP; *(DWORD*)(jmp+1) = (DWORD)(orig+len - jmp) - 5;
Code:
memset(orig, 0x90, len);
Code:
orig[0] = JMP; *(DWORD*)(orig+1) = (DWORD)(hook - orig) - 5;
Code:
VirtualProtect(orig, len, dwProt, 0);
Code:
return (jmp-len); }
Code:
typedef int( __cdecl* tDraw2D ) ( int a1 );
tDraw2D oDraw2D = NULL;
void Draw2D(int a1)
{
__asm PUSHAD;
//Do your magic here XD
__asm POPAD;
oDraw2D( a1 );
}
BOOL WINAPI DllMain( HMODULE hMod, DWORD dwReason, LPVOID lpReserved )
{
if( dwReason == DLL_PROCESS_ATTACH )
{
oDraw2D = (tDraw2D) DetourFunction( (BYTE*)Draw2DOffset, (BYTE*)&Draw2D ,5);
}
}
Dwar