-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetours.hpp
More file actions
103 lines (85 loc) · 2.32 KB
/
Copy pathdetours.hpp
File metadata and controls
103 lines (85 loc) · 2.32 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
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
#pragma once
namespace my::hook
{
struct detours
{
detours()
{
DetourTransactionBegin();
DetourUpdateThread(::GetCurrentThread());
}
~detours()
{
DetourTransactionCommit();
}
};
template <typename T>
LONG attach(T& hooker)
{
return DetourAttach(&(PVOID&)hooker.orig_proc, hooker.hook_proc);
}
template <typename T>
LONG detach(T& hooker)
{
return DetourDetach(&(PVOID&)hooker.orig_proc, hooker.hook_proc);
}
template <typename T, typename A>
LONG attach(T& hooker, A address)
{
hooker.orig_proc = reinterpret_cast<decltype(hooker.orig_proc)>(address);
return DetourAttach(&(PVOID&)hooker.orig_proc, hooker.hook_proc);
}
template <typename T, typename A>
void attach_call(T& hooker, A address)
{
hooker.orig_proc = tools::set_call(address, hooker.hook_proc);
}
template <typename T, typename A>
void attach_abs_call(T& hooker, A address)
{
hooker.orig_proc = tools::set_abs_call(address, hooker.hook_proc);
}
template <typename T, typename A>
void attach_abs_addr(T& hooker, A address)
{
hooker.orig_proc = tools::set_abs_addr(address, hooker.hook_proc);
}
template <typename F>
F hook_import(HMODULE module, LPCSTR func_name, F new_func)
{
struct Hooker
{
LPCSTR func_name;
F new_func;
F old_func;
inline static BOOL CALLBACK detour(
_In_opt_ PVOID pContext,
_In_ DWORD nOrdinal,
_In_opt_ LPCSTR pszFunc,
_In_opt_ PVOID* ppvFunc)
{
if (!pszFunc) return TRUE;
MY_TRACE_STR(pszFunc);
auto hooker = (Hooker*)pContext;
if (::lstrcmpA(pszFunc, hooker->func_name) != 0) return TRUE;
auto protect = DWORD { PAGE_READWRITE };
auto result1 = ::VirtualProtect(ppvFunc, sizeof(*ppvFunc), protect, &protect);
hooker->old_func = tools::set_abs_addr((addr_t)ppvFunc, hooker->new_func);
auto result2 = ::VirtualProtect(ppvFunc, sizeof(*ppvFunc), protect, &protect);
return FALSE;
}
} hooker = { func_name, new_func };
DetourEnumerateImportsEx(module, &hooker, nullptr, hooker.detour);
return hooker.old_func;
}
template <typename T>
void attach_import(T& hooker, HMODULE module, LPCSTR func_name)
{
hooker.orig_proc = hook_import(module, func_name, hooker.hook_proc);
}
template <typename T>
void replace(T& hooker, decltype(hooker.orig_proc)& address)
{
hooker.orig_proc = address, address = hooker.hook_proc;
}
}