-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuwhook.cpp
82 lines (62 loc) · 1.7 KB
/
uwhook.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
#include "uwhook.hpp"
#include <cstring>
#include <cstdint>
#include <windows.h>
#include <memoryapi.h>
#include <processthreadsapi.h>
#ifdef __clang__
__attribute__((used))
#endif
void *uwHookCallerRip;
UWHook::UWHook(void *fnc, void *hook, bool useTrampoline)
: fnc(fnc), hook(hook), useTrampoline(useTrampoline) {
// Back up instructions from original function
memcpy(original.data(), fnc, original_len);
// Initial hook "restore"
restore();
}
void *UWHook::getTrampolineCaller() {
return reinterpret_cast<uint8_t *>(uwHookCallerRip) - 6;
}
bool UWHook::release() {
// Restore original instructions
SIZE_T writ = 0;
WriteProcessMemory(GetCurrentProcess(), fnc, original.data(), original_len, &writ);
if (writ != original_len) {
return false;
}
released = true;
return true;
}
bool UWHook::restore() {
// Generate trampoline instructions
uint8_t test[] = {
0xff, static_cast<uint8_t>(useTrampoline?0x15:0x25), 0x00, 0x00, 0x00, 0x00,
0xef, 0xbe, 0xad, 0xde, 0xef, 0xbe, 0xad, 0xde
};
static_assert(sizeof(hook) == 8);
memcpy(test+sizeof(test)-8, &hook, 8);
// Write new instructions
static_assert(original_len == sizeof(test));
SIZE_T writ = 0;
WriteProcessMemory(GetCurrentProcess(), fnc, test, sizeof(test), &writ);
if (writ != sizeof(test)) {
return false;
}
released = false;
return true;
}
UWHookRelease::UWHookRelease(UWHook& hook)
: hook(hook) {
if (!hook.isActive()) {
active = false;
return;
}
hook.release();
active = !hook.isActive();
}
UWHookRelease::~UWHookRelease() {
if (active)
hook.restore();
}
void UWHook::noop() {}