-
Notifications
You must be signed in to change notification settings - Fork 7
/
hook.h
113 lines (92 loc) · 2.25 KB
/
hook.h
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#ifndef _HOOK
#define _HOOK
#include "pch.h"
#include "log.h"
#include "memory.h"
class Hook
{
protected:
LPVOID hookFunction;
LPVOID _target{};
LPVOID _original{};
bool _enabled{};
public:
const std::string name{};
public:
Hook(const std::string name, LPVOID hookFunction)
: name(name), hookFunction(hookFunction)
{}
bool enabled() const
{
return _enabled;
}
virtual bool enable() = 0;
virtual bool disable() = 0;
template <typename T>
T original() const
{
return (T)_original;
}
};
class DetourHook : public Hook
{
public:
DetourHook(const std::string name, LPVOID target, LPVOID hookFunction)
: Hook(name, hookFunction)
{
_target = target;
}
bool enable() override
{
if (_enabled)
{
//err("Hook \"%s\": Already enabled", this->name.c_str());
return false;
}
auto result = MH_Initialize();
if (result != MH_OK && result != MH_ERROR_ALREADY_INITIALIZED)
{
err("Hook \"%s\": MH_Initialize failed: %s", this->name.c_str(), MH_StatusToString(result));
return false;
}
result = MH_CreateHook(_target, (LPVOID)this->hookFunction, &_original);
if (result != MH_OK && result != MH_ERROR_ALREADY_CREATED)
{
err("Hook \"%s\": MH_CreateHook failed: %s", this->name.c_str(), MH_StatusToString(result));
return false;
}
result = MH_EnableHook(_target);
if (result != MH_OK && result != MH_ERROR_ENABLED)
{
err("Hook \"%s\": MH_EnableHook failed: %s", this->name.c_str(), MH_StatusToString(result));
return false;
}
//info("Hook \"%s\": Enabled", this->name.c_str());
_enabled = true;
return true;
}
bool disable() override
{
if (!_enabled)
{
//err("Hook \"%s\": Already disabled", this->name.c_str());
return false;
}
auto result = MH_Initialize();
if (result != MH_OK && result != MH_ERROR_ALREADY_INITIALIZED)
{
err("Hook \"%s\": MH_Initialize failed: %s", this->name.c_str(), MH_StatusToString(result));
return false;
}
result = MH_DisableHook(_target);
if (result != MH_OK && result != MH_ERROR_DISABLED && result != MH_ERROR_NOT_CREATED)
{
err("Hook \"%s\": MH_DisableHook failed: %s", this->name.c_str(), MH_StatusToString(result));
return false;
}
//info("Hook \"%s\": Disabled", this->name.c_str());
_enabled = false;
return true;
}
};
#endif