How to create a trampoline function for hook

前端 未结 2 1561
广开言路
广开言路 2021-02-19 21:25

I\'m interested in hooking and I decided to see if I could hook some functions. I wasn\'t interested in using a library like detours because I want to have the experience of doi

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 22:09

    The defacto standard hooking tutorial is from jbremer and available here

    Here is a simple x86 detour and trampoline hook based on this tutorial using Direct3D's EndScene() function as a example:

    bool Detour32(char* src, char* dst, const intptr_t len)
    {
        if (len < 5) return false;
    
        DWORD  curProtection;
        VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &curProtection);
    
        intptr_t  relativeAddress = (intptr_t)(dst - (intptr_t)src) - 5;
    
        *src = (char)'\xE9';
        *(intptr_t*)((intptr_t)src + 1) = relativeAddress;
    
        VirtualProtect(src, len, curProtection, &curProtection);
        return true;
    }
    
    char* TrampHook32(char* src, char* dst, const intptr_t len)
    {
        // Make sure the length is greater than 5
        if (len < 5) return 0;
    
        // Create the gateway (len + 5 for the overwritten bytes + the jmp)
        void* gateway = VirtualAlloc(0, len + 5, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    
        //Write the stolen bytes into the gateway
        memcpy(gateway, src, len);
    
        // Get the gateway to destination addy
        intptr_t  gatewayRelativeAddr = ((intptr_t)src - (intptr_t)gateway) - 5;
    
        // Add the jmp opcode to the end of the gateway
        *(char*)((intptr_t)gateway + len) = 0xE9;
    
        // Add the address to the jmp
        *(intptr_t*)((intptr_t)gateway + len + 1) = gatewayRelativeAddr;
    
        // Perform the detour
        Detour32(src, dst, len);
    
        return (char*)gateway;
    }
    
    typedef HRESULT(APIENTRY* tEndScene)(LPDIRECT3DDEVICE9 pDevice);
    tEndScene oEndScene = nullptr;
    
    HRESULT APIENTRY hkEndScene(LPDIRECT3DDEVICE9 pDevice)
    {
        //do stuff in here
        return oEndScene(pDevice);
    }
    
    //just an example
    int main()
    {
        oEndScene = (tEndScene)TrampHook32((char*)d3d9Device[42], (char*)hkEndScene, 7);
    }
    

提交回复
热议问题