Custom detour code x64 for Windows 10 (newest versions)

  64-bit, api-hook, c++, windows

I always used this following custom code to api hook (inline hook method), and is working fine in pratically all Windows versions x64, except in newest Windows 10 versions like build 18362 and highter.

What’s necessary to fix it?

void* DetourFunction64(void* pSource, void* pDestination, int dwLen)
{
    DWORD MinLen = 14;

    if (dwLen < MinLen)
        return NULL;

    BYTE stub[] = { 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    PVOID pTrampoline = VirtualAlloc(0, dwLen + sizeof(stub), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

    DWORD dwOld = 0;

    VirtualProtect(pSource, dwLen, PAGE_EXECUTE_READWRITE, &dwOld);

    DWORD64 retto = (DWORD64)pSource + dwLen;

    memcpy(stub + 6, &retto, 8);
    memcpy((PVOID)((DWORD_PTR)pTrampoline), pSource, dwLen);
    memcpy((PVOID)((DWORD_PTR)pTrampoline + dwLen), stub, sizeof(stub));

    memcpy(stub + 6, &pDestination, 8);
    memcpy(pSource, stub, sizeof(stub));

    for (int i = MinLen; i < dwLen; i++)
        *(BYTE*)((DWORD_PTR)pSource + i) = 0x90;

    VirtualProtect(pSource, dwLen, dwOld, &dwOld);

    return (PVOID)((DWORD_PTR)pTrampoline);
}

Source: Windows Questions

LEAVE A COMMENT