Repository navigation
Expand file tree
/
Copy pathInjectHook.cpp
More file actions
58 lines (45 loc) · 1.67 KB
/
Copy pathInjectHook.cpp
File metadata and controls
58 lines (45 loc) · 1.67 KB
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
52
53
54
55
56
57
58
#include "InjectHook.h"
#include <Windows.h>
#include <map>
namespace HookLib {
struct HookData {
BYTE originalBytes[5];
void* targetFunction;
};
std::map<void*, HookData> hooks;
bool InstallHook(void* targetFunction, void* hookAddress, HookType type) {
DWORD oldProtect;
HookData data;
// Save the original bytes of the target function.
memcpy(data.originalBytes, targetFunction, 5);
data.targetFunction = targetFunction;
hooks[targetFunction] = data;
// Change memory protection to read/write.
VirtualProtect(targetFunction, 5, PAGE_EXECUTE_READWRITE, &oldProtect);
// Apply the hook based on the specified type.
switch (type) {
case JMP_LONG: {
DWORD relativeAddress = ((DWORD)hookAddress - (DWORD)targetFunction) - 5;
*(BYTE*)targetFunction = 0xE9;
*(DWORD*)((DWORD)targetFunction + 1) = relativeAddress;
break;
}
// Additional jump types can be added here.
default:
break;
}
// Restore the original memory protection.
VirtualProtect(targetFunction, 5, oldProtect, &oldProtect);
return true;
}
bool RemoveHook(void* targetFunction) {
auto it = hooks.find(targetFunction);
if (it == hooks.end()) return false;
DWORD oldProtect;
VirtualProtect(targetFunction, 5, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(targetFunction, it->second.originalBytes, 5);
VirtualProtect(targetFunction, 5, oldProtect, &oldProtect);
hooks.erase(it);
return true;
}
}