#include        "defs.h"

//performs inline hooking of a function...
void    Hook(__in PVOID lpOriginal, __in PVOID HookDestination, __out PVOID *HookDetour){
        DWORD   dwOldProt;
        PUCHAR  pDetourBuffer;
        PUCHAR  p;
        ULONG   ilen, len = 0;
        ULONG_PTR       orig;
        
        p = lpOriginal;
        
        while (len < 5){
                ilen = decodeLen(p);
                len += ilen;
                p   += ilen;
        }
        
        pDetourBuffer = dlmalloc(len + 5);
        memcpy(pDetourBuffer, lpOriginal, len);
        
        ntVirtualProtect(lpOriginal, 5, PAGE_EXECUTE_READWRITE, &dwOldProt);
        
        make_jmp(lpOriginal, HookDestination);
        if (HookDetour != NULL)
                *HookDetour = pDetourBuffer;
        
        make_jmp((void *)((ULONG_PTR)pDetourBuffer + len), (void *)((ULONG_PTR)lpOriginal+len));
        ntVirtualProtect(lpOriginal, 5, dwOldProt, &dwOldProt);
}

void    make_jmp(__in void *here, __in void *where){    
        unsigned char *p = here;
        
        p[0] = 0xE9;
        *(ULONG_PTR *)&p[1] = (ULONG_PTR)where - (ULONG_PTR)here - 5;       
}