upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/code_hooks.h
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src/code_hooks.h')
-rw-r--r--runtime/src/code_hooks.h182
1 files changed, 182 insertions, 0 deletions
diff --git a/runtime/src/code_hooks.h b/runtime/src/code_hooks.h
new file mode 100644
index 000000000..a079f95dd
--- /dev/null
+++ b/runtime/src/code_hooks.h
@@ -0,0 +1,182 @@
1// Hooks on a function of the loaded game image, by redirecting its direct callers (docs/modding.md, "Day one").
2//
3// Patching inside a function needs an instruction decoder to move its prologue. Redirecting the callers does not:
4// every `call rel32` (E8) and `jmp rel32` (E9) in the image's executable sections whose target is the function is
5// pointed at a thunk instead. The thunk saves the argument registers (rcx, rdx, r8, r9, xmm0-3), passes one 32-bit
6// argument through a C++ function, restores the rest and jumps to the original. A call through a pointer (vtable,
7// import slot) is not redirected, which suits RAGE's archetype lookup: a static function called directly.
8//
9// A byte pattern can look like E8/E9 + rel32 inside another instruction; it is only rewritten when its target is
10// exactly the hooked function, so a false match must also point there. x64 Windows only.
11#pragma once
12
13#include <windows.h>
14
15#include <cstddef>
16#include <cstdint>
17#include <cstring>
18#include <initializer_list>
19
20namespace leonida::hooks {
21
22using RemapFn = uint32_t (*)(uint32_t);
23
24// Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free.
25inline uint8_t* alloc_near(const void* close_to, std::size_t size) {
26 SYSTEM_INFO si;
27 GetSystemInfo(&si);
28 const uintptr_t gran = si.dwAllocationGranularity;
29 const uintptr_t center = reinterpret_cast<uintptr_t>(close_to) & ~(gran - 1);
30 const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image
31 for (uintptr_t delta = gran; delta < span; delta += gran) {
32 for (int side = 0; side < 2; ++side) {
33 const uintptr_t at = side ? center + delta : center - delta;
34 if (side == 0 && center < delta) continue;
35 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT,
36 PAGE_EXECUTE_READWRITE))
37 return static_cast<uint8_t*>(p);
38 }
39 }
40 return nullptr;
41}
42
43// The thunk: argument `arg` (0 = rcx, 1 = rdx; the low 32 bits) goes through `fn`, then the original runs with every
44// other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and
45// 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3.
46inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) {
47 if (arg != 0 && arg != 1) return nullptr;
48 uint8_t* t = alloc_near(close_to, 4096);
49 if (!t) return nullptr;
50 uint8_t* p = t;
51 auto put = [&](std::initializer_list<uint8_t> bytes) { for (uint8_t b : bytes) *p++ = b; };
52 auto put64 = [&](uint64_t v) { std::memcpy(p, &v, 8); p += 8; };
53 put({0x51, 0x52, 0x41, 0x50, 0x41, 0x51}); // push rcx, rdx, r8, r9
54 put({0x48, 0x83, 0xEC, 0x68}); // sub rsp, 0x68
55 put({0xF3, 0x0F, 0x7F, 0x44, 0x24, 0x20}); // movdqu [rsp+0x20], xmm0
56 put({0xF3, 0x0F, 0x7F, 0x4C, 0x24, 0x30}); // movdqu [rsp+0x30], xmm1
57 put({0xF3, 0x0F, 0x7F, 0x54, 0x24, 0x40}); // movdqu [rsp+0x40], xmm2
58 put({0xF3, 0x0F, 0x7F, 0x5C, 0x24, 0x50}); // movdqu [rsp+0x50], xmm3
59 if (arg == 1) put({0x89, 0xD1}); // mov ecx, edx
60 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(fn)); // mov rax, fn
61 put({0xFF, 0xD0}); // call rax
62 put({0xF3, 0x0F, 0x6F, 0x44, 0x24, 0x20}); // movdqu xmm0, [rsp+0x20]
63 put({0xF3, 0x0F, 0x6F, 0x4C, 0x24, 0x30}); // movdqu xmm1, [rsp+0x30]
64 put({0xF3, 0x0F, 0x6F, 0x54, 0x24, 0x40}); // movdqu xmm2, [rsp+0x40]
65 put({0xF3, 0x0F, 0x6F, 0x5C, 0x24, 0x50}); // movdqu xmm3, [rsp+0x50]
66 put({0x48, 0x83, 0xC4, 0x68}); // add rsp, 0x68
67 put({0x41, 0x59, 0x41, 0x58, 0x5A, 0x59}); // pop r9, r8, rdx, rcx
68 put({0x89, static_cast<uint8_t>(arg == 0 ? 0xC1 : 0xC2)}); // mov ecx|edx, eax (the remapped value)
69 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original
70 put({0xFF, 0xE0}); // jmp rax
71 DWORD old = 0;
72 VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old);
73 FlushInstructionCache(GetCurrentProcess(), t, p - t);
74 return t;
75}
76
77using ResultFn = uint32_t (*)(uint32_t result, uint32_t arg0);
78
79// A thunk that runs the original and then passes (its 32-bit result, its first argument) through `fn`, returning
80// what `fn` returns: for a getter such as "the view mode of context N". Only for functions with at most four
81// register arguments (a stack argument would be one slot off) and an integer result.
82// Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls.
83inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) {
84 uint8_t* t = alloc_near(close_to, 4096);
85 if (!t) return nullptr;
86 uint8_t* p = t;
87 auto put = [&](std::initializer_list<uint8_t> bytes) { for (uint8_t b : bytes) *p++ = b; };
88 auto put64 = [&](uint64_t v) { std::memcpy(p, &v, 8); p += 8; };
89 put({0x51}); // push rcx (the first argument, for fn)
90 put({0x48, 0x83, 0xEC, 0x20}); // sub rsp, 0x20
91 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original
92 put({0xFF, 0xD0}); // call rax (rcx, rdx, r8, r9 still the caller's)
93 put({0x48, 0x8B, 0x54, 0x24, 0x20}); // mov rdx, [rsp+0x20] (the saved first argument)
94 put({0x89, 0xC1}); // mov ecx, eax (the original's result)
95 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(fn)); // mov rax, fn
96 put({0xFF, 0xD0}); // call rax
97 put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20
98 put({0x59, 0xC3}); // pop rcx ; ret
99 DWORD old = 0;
100 VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old);
101 FlushInstructionCache(GetCurrentProcess(), t, p - t);
102 return t;
103}
104
105// Points every E8/E9 rel32 in [begin, begin + size) whose target is `target` at `thunk`. The range must be writable.
106// Returns how many were rewritten.
107inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target,
108 const uint8_t* thunk) {
109 std::size_t n = 0;
110 for (std::size_t i = 0; i + 5 <= size; ++i) {
111 if (begin[i] != 0xE8 && begin[i] != 0xE9) continue;
112 int32_t rel;
113 std::memcpy(&rel, begin + i + 1, 4);
114 const uint8_t* next = begin + i + 5;
115 if (next + rel != target) continue;
116 const intptr_t to = thunk - next;
117 if (to < INT32_MIN || to > INT32_MAX) continue;
118 const int32_t rel2 = static_cast<int32_t>(to);
119 std::memcpy(begin + i + 1, &rel2, 4);
120 ++n;
121 i += 4;
122 }
123 return n;
124}
125
126struct HookResult {
127 bool ok = false;
128 std::size_t redirected = 0;
129 const char* error = "";
130};
131
132// Hooks the function at `target_rva` of the mapped image at `base`: one thunk, then every direct call or jump to it
133// in the image's executable sections. Runs before any image code (main.cpp), so no thread is executing the bytes.
134// Validates `target_rva` as code of the mapped image at `base`, builds the thunk with `make(target)` and points the
135// image's direct calls and jumps to the target at it.
136template <class MakeThunk>
137inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) {
138 HookResult r;
139 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
140 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return r.error = "not a mapped PE image", r;
141 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
142 if (nt->Signature != IMAGE_NT_SIGNATURE || target_rva >= nt->OptionalHeader.SizeOfImage)
143 return r.error = "the RVA is outside the image", r;
144 const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
145 bool in_code = false;
146 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i)
147 if ((sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && target_rva >= sec[i].VirtualAddress &&
148 target_rva < sec[i].VirtualAddress + sec[i].Misc.VirtualSize)
149 in_code = true;
150 if (!in_code) return r.error = "the RVA is not in an executable section", r;
151 uint8_t* target = base + target_rva;
152 uint8_t* thunk = make(target);
153 if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r;
154 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
155 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue;
156 uint8_t* begin = base + sec[i].VirtualAddress;
157 const std::size_t size = sec[i].Misc.VirtualSize;
158 DWORD old = 0;
159 if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) return r.error = "VirtualProtect failed", r;
160 r.redirected += redirect_direct_branches(begin, size, target, thunk);
161 DWORD ignored = 0;
162 VirtualProtect(begin, size, old, &ignored);
163 FlushInstructionCache(GetCurrentProcess(), begin, size);
164 }
165 r.ok = true;
166 return r;
167}
168
169// The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`.
170inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) {
171 if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"};
172 return redirect_image_calls(base, target_rva,
173 [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); });
174}
175
176// The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument.
177inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) {
178 return redirect_image_calls(base, target_rva,
179 [&](uint8_t* target) { return make_result_thunk(target, fn, target); });
180}
181
182} // namespace leonida::hooks