forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.cpp
126 lines (101 loc) · 2.13 KB
/
hook.cpp
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
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "hook.hpp"
#include <assert.h>
#include <MinHook.h>
namespace reshade
{
static unsigned long s_reference_count = 0;
hook::hook() : target(nullptr), replacement(nullptr), trampoline(nullptr)
{
}
hook::hook(address target, address replacement) : target(target), replacement(replacement), trampoline(nullptr)
{
}
bool hook::valid() const
{
return target != nullptr && replacement != nullptr && target != replacement;
}
bool hook::enabled() const
{
if (!valid())
{
return false;
}
const MH_STATUS statuscode = MH_EnableHook(target);
if (statuscode == MH_ERROR_ENABLED)
{
return true;
}
MH_DisableHook(target);
return false;
}
bool hook::installed() const
{
return trampoline != nullptr;
}
bool hook::enable(bool enable) const
{
if (enable)
{
const MH_STATUS statuscode = MH_EnableHook(target);
return statuscode == MH_OK || statuscode == MH_ERROR_ENABLED;
}
else
{
const MH_STATUS statuscode = MH_DisableHook(target);
return statuscode == MH_OK || statuscode == MH_ERROR_DISABLED;
}
}
hook::status hook::install()
{
if (!valid())
{
return status::unsupported_function;
}
if (s_reference_count++ == 0)
{
MH_Initialize();
}
const MH_STATUS statuscode = MH_CreateHook(target, replacement, &trampoline);
if (statuscode == MH_OK || statuscode == MH_ERROR_ALREADY_CREATED)
{
enable();
return status::success;
}
if (--s_reference_count == 0)
{
MH_Uninitialize();
}
return static_cast<status>(statuscode);
}
hook::status hook::uninstall()
{
if (!valid())
{
return status::unsupported_function;
}
const MH_STATUS statuscode = MH_RemoveHook(target);
if (statuscode == MH_ERROR_NOT_CREATED)
{
return status::success;
}
else if (statuscode != MH_OK)
{
return static_cast<status>(statuscode);
}
trampoline = nullptr;
if (--s_reference_count == 0)
{
MH_Uninitialize();
}
return status::success;
}
hook::address hook::call() const
{
assert(installed());
return trampoline;
}
}