hook.h
Code:
#include <windows.h>
#include <iostream>
using namespace std;
class hook
{
public:
DWORD m_Function_Start;
DWORD m_Offset;
DWORD m_Hook_Func;
DWORD m_size;
DWORD m_ret;
hook(DWORD Function_Start,DWORD Offset,DWORD Hook_Func,DWORD size);
hook();
~hook();
void UnHook();
void ApplyHook();
private:
DWORD m_addr;
BYTE* bOrig;
BYTE* bHooked;
};
hook.cpp
Code:
#include "hook.h"
hook::hook(DWORD Function_Start,DWORD Offset,DWORD Hook_Func,DWORD size)
{
this->m_size = size;
this->m_Function_Start = Function_Start;
this->m_Hook_Func = Hook_Func;
this->m_Offset = Offset;
this->bOrig = (BYTE*)malloc(size);
this->bHooked = (BYTE*)malloc(size);
this->m_addr = Function_Start+Offset;
this->m_ret = this->m_addr + this->m_size;
DWORD dwRelAddr;
dwRelAddr = (DWORD) (this->m_Hook_Func - this->m_addr) - 5;
this->bHooked[0] = 0xE9;
*(DWORD*)(this->bHooked+1) = dwRelAddr;
for(int x = 5; x < this->m_size; x++)
*(BYTE*)(this->bHooked+x) = 0x90;
memcpy(this->bOrig,(void*)this->m_addr,this->m_size);
}
hook::hook()
{
this->m_size = 0;
this->m_Function_Start = 0;
this->m_Hook_Func = 0;
this->m_Offset = 0;
this->bOrig = 0;
this->bHooked = 0;
this->m_addr = 0;
this->m_ret = 0;
}
void hook::UnHook()
{
DWORD dwOldProtect;
VirtualProtect((LPVOID)this->m_addr, this->m_size, PAGE_EXECUTE_READWRITE, &dwOldProtect);
memcpy((void*)this->m_addr,this->bOrig,this->m_size);
VirtualProtect((LPVOID)this->m_addr, this->m_size, dwOldProtect, 0);
}
void hook::ApplyHook()
{
DWORD dwOldProtect;
VirtualProtect((LPVOID)this->m_addr, this->m_size, PAGE_EXECUTE_READWRITE, &dwOldProtect);
memcpy((void*)this->m_addr,this->bHooked,this->m_size);
VirtualProtect((LPVOID)this->m_addr, this->m_size, dwOldProtect, 0);
}
hook::~hook()
{
free(bOrig);
free(bHooked);
}
How to use:
Code:
__declspec(naked) void nReset()
{
_asm{
pushad
pushfd
}
if(pFont)
pFont->OnLostDevice();
hkReset.UnHook(); //Unhook to call orig function without a loop
_asm{
mov eax, [ebp+8d]
push eax
mov eax, [ebp+12d]
push eax
call hkReset.m_Function_Start
}
if(pFont)
pFont->OnResetDevice();
hkReset.ApplyHook();
_asm{
popfd
popad
mov edi, edi
push ebp
mov ebp, esp
jmp hkReset.m_ret
}
}
Code:
hkReset = hook(D3D9_VTABLE[16],0,(DWORD)nReset,5);
hkReset.ApplyHook();