I've written code to patch the "Sleep" function for example from Kernel32.dll. The patching works perfectly fine. The removal of the patch works perfectly fine. However, calling the original function does not work at all. It crashes badly.
#include <windows.h>
#include <iostream>
std::uint8_t* Patch(std::uint8_t* OrigFunc, std::uint8_t* HookFunc)
{
DWORD dwProtect = 0;
const static std::uint8_t jmp[] = {0xB8, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xE0};
const static std::int8_t jmp_size = sizeof(jmp) / sizeof(std::uint8_t);
static std::uint8_t HookJump[jmp_size + 1] = {jmp_size};
VirtualProtect(OrigFunc, jmp_size, PAGE_EXECUTE_READWRITE, &dwProtect);
memcpy(&HookJump[1], OrigFunc, jmp_size);
memcpy(OrigFunc, jmp, jmp_size);
memcpy(OrigFunc + 1, &HookFunc, sizeof(void*));
VirtualProtect(OrigFunc, jmp_size, dwProtect, &dwProtect);
return HookJump;
}
void RemovePatch(std::uint8_t* OrigFunc, std::uint8_t* HookJump)
{
DWORD dwProtect = 0;
VirtualProtect(OrigFunc, HookJump[0], PAGE_EXECUTE_READWRITE, &dwProtect);
memcpy(OrigFunc, &HookJump[1], HookJump[0]);
VirtualProtect(OrigFunc, HookJump[0], dwProtect, &dwProtect);
}
typedef void (__stdcall *pSleep)(DWORD);
pSleep oSleep;
void __stdcall hSleep(DWORD MS)
{
std::cout<<"HERE";
oSleep(MS); //Crashes Here.
}
int main()
{
std::uint8_t* OrigFunc = (std::uint8_t*)GetProcAddress(GetModuleHandle("kernel32.dll"), "Sleep");
std::uint8_t* HookFunc = (std::uint8_t*)hSleep;
std::uint8_t* HookJump = Patch(OrigFunc, HookFunc); //Works fine.
oSleep = (pSleep)&HookJump[1];
Sleep(1000); //Prints Here then crashes immediately.
RemovePatch(OrigFunc, HookJump); //Works fine.
Sleep(1000); //Works fine.
}
Any ideas what my code is missing?
In the given code it appears that you store original bytes in a static array called
HookJump, return a pointer to that array, then jump to the start of it as if it were valid machine code. It's not followed by the rest of the original function.A better way to hook functions in Windows is to use Microsoft Detours.
Here's my (working sketch of a)
Hookclass, using Detours:And here's the
Transactionclass that it uses, which in turn calls the Detours API:The Detours wrapper header:
I then use a cpp file to bring in a specific Detours implementation, e.g. for x86: