aboutsummaryrefslogtreecommitdiff
path: root/VmtHook.cpp
blob: 915e82f6558acb2450c545bf3331eec545ab0247 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "VmtHook.h"



VmtHook::VmtHook(void** vmt)
{
	this->vmt = vmt;
}

void* VmtHook::Hook(int index, void* hookedFunction)
{
	hookedfuncs.insert(std::make_pair(index, vmt[index]));

	//make page writeable
	DWORD pageProtection;
	VirtualProtect(&vmt[index], sizeof(BYTE*), PAGE_EXECUTE_READWRITE, &pageProtection);

	//overwrite function pointer in VMT to hook function
	vmt[index] = hookedFunction;

	//restore page protection
	VirtualProtect(&vmt[index], sizeof(BYTE*), pageProtection, &pageProtection);

	return hookedfuncs[index];
}

//
//Unhook a single hooked function
bool VmtHook::Unhook(int index)
{
	auto entry = hookedfuncs.find(index);
	if (entry != hookedfuncs.end())
	{
		vmt[entry->first] = entry->second;
		return true;
	}
	return false;
}

//
//Unhook the entire Vmt
void VmtHook::Unhook()
{
	for (std::pair<int, void*> pair : hookedfuncs)
	{
		DWORD oldProtection;
		VirtualProtect(&vmt[pair.first], sizeof(BYTE*), PAGE_EXECUTE_READWRITE, &oldProtection);
		vmt[pair.first] = pair.second;
		VirtualProtect(&vmt[pair.first], sizeof(BYTE*), oldProtection, &oldProtection);
	}
}