im trying to create a sort of overlay of a game i play in order to display my ping in realtime as there has been a lot of issues and people blaming the ping so i just wanted an easy solution and add a realtime ping display in game :)
Anyways hooks has always been something that i have been strugling alot with, i get how it works but it just never works out for me, this is the code that i have seen in countless of places but after going through the trampoline it crashes:
void* detour::Hook(BYTE* src, BYTE* dst, int len) {
BYTE *jmp = (BYTE*)malloc(len+5);
DWORD dwback;
VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &dwback);
memcpy(jmp, src, len);
jmp += len;
jmp[0] = 0xE9;
*(DWORD*)(jmp + 1) = (DWORD)(src + len - jmp) - 5;
src[0] = 0xE9;
*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
VirtualProtect(src, len, dwback, &dwback);
return (src + 6);
}
and i can see that it is really messy and its using malloc instead of VirtualAlloc etc.. but for some reason it works half the way :S anyways this was just something that i used in order to try and gain a better understanding of hooks, in the meantime i was working on some code of my own which is this:
DWORD detour::SetHook(DWORD src, DWORD dst, int len) {
BYTE* backup;
DWORD oldProtection;
DWORD trampolineAddr;
VirtualProtectEx(GetModuleHandle(NULL), (void*) dst, 5, PAGE_READWRITE, &oldProtection);
//Create trampoline backup
trampolineAddr = (DWORD) VirtualAllocEx(GetModuleHandle(NULL), NULL, 10, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
memcpy((void*) trampolineAddr, (void*) dst, 5);
memcpy((void*)(trampolineAddr + 5), (void*) 0xE9, 1);
memcpy((void*)(trampolineAddr + 6), (void*) dst, 4);
//set API hook
memcpy((void*)dst, (void*) 0xE9, 1);
memcpy((void*)(dst + 1), (void*)src, 4);
VirtualProtectEx(GetModuleHandle(NULL), (void*) dst, 5, oldProtection, &oldProtection);
return trampolineAddr;
}
and what this does is that it returns the address of where the trampoline has been created and i just make a jump to that address after the function that has replaced the hooked function has been called, allthought none of this works :/
so my questions in essense is really, why does the first hook only work half-way ? and what is so wrong about my hook ? it created the jump to the address, backs up the overwritten bytes and saves them in a trampoline which i jump to after my custom function but none of it works :(
would really appreciate some constructive feedback as this is something i have wanted to master for quite some time now :) Thanks in advance!