This repository has been archived by the owner on Sep 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HookManager.h
107 lines (87 loc) · 2.4 KB
/
HookManager.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
#pragma once
#include <map>
#include <detours.h>
#include <Windows.h>
#include "Utils.h"
#define CALL_ORIGIN(function, ...) \
HookManager::call(function, __func__, __VA_ARGS__)
class HookManager
{
public:
template <typename Fn>
static void install(Fn func, Fn handler)
{
enable(func, handler);
holderMap[reinterpret_cast<void*>(handler)] = reinterpret_cast<void*>(func);
}
template <typename Fn>
static Fn getOrigin(Fn handler, const char* callerName = nullptr) noexcept
{
if (holderMap.count(reinterpret_cast<void*>(handler)) == 0) {
LOG("Origin not found for handler: %s. Maybe racing bug.", callerName == nullptr ? "<Unknown>" : callerName);
return nullptr;
}
return reinterpret_cast<Fn>(holderMap[reinterpret_cast<void*>(handler)]);
}
template <typename Fn>
static void detach(Fn handler) noexcept
{
disable(handler);
holderMap.erase(reinterpret_cast<void*>(handler));
}
// I don't know why
#ifdef _WIN64
template <typename RType, typename... Params>
static RType call(RType(*handler)(Params...), const char* callerName = nullptr, Params... params)
{
auto origin = getOrigin(handler, callerName);
if (origin != nullptr)
return origin(params...);
return RType();
}
#else
template <typename RType, typename... Params>
static RType call(RType(__cdecl *handler)(Params...), const char* callerName = nullptr, Params... params)
{
auto origin = getOrigin(handler, callerName);
if (origin != nullptr)
return origin(params...);
return RType();
}
template <typename RType, typename... Params>
static RType call(RType(__stdcall *handler)(Params...), const char* callerName = nullptr, Params... params)
{
auto origin = getOrigin(handler, callerName);
if (origin != nullptr)
return origin(params...);
return RType();
}
#endif
static void detachAll() noexcept
{
for (const auto &[key, value] : holderMap)
{
disable(key);
}
holderMap.clear();
}
private:
inline static std::map<void*, void*> holderMap{};
template <typename Fn>
static void disable(Fn handler)
{
Fn origin = getOrigin(handler);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)origin, handler);
DetourTransactionCommit();
}
template <typename Fn>
static void enable(Fn& func, Fn handler)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)func, handler);
DetourTransactionCommit();
}
};