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:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 22:53:19 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 22:53:19 -0500
commit9e6444fadb93c9b800ed403f91fcfee1a88d3560 (patch)
treebe1cf4a298295b74268c5a652210ca34b5069b7e /runtime/src/code_hooks.h
parent2d3369a4c82e6f36c5190c4c534d3df600e135ec (diff)
Mods: the archetype hook, --archetype-lookup RVA[,ARG]
code_hooks.h hooks a function of the mapped game image without patching it: every direct call/jmp rel32 to it in the image's executable sections is pointed at a thunk that saves rcx/rdx/r8/r9 and xmm0-3, passes the hash (argument 0 or 1) through leonida::mods::active().remap() and jumps on to the original. gta6rt installs it right after mapping, before any image code runs, and logs how many call sites it redirected, so a --dry-run with a candidate RVA tells whether it is the archetype lookup. ctest code_hooks runs the thunk on x64 functions written into memory (call and tail jump remapped, r8 preserved, a branch elsewhere left byte for byte). With the executable's lookup RVA this applies mods/mandy_prison_intro; docs/modding.md says how to find it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/code_hooks.h')
-rw-r--r--runtime/src/code_hooks.h138
1 files changed, 138 insertions, 0 deletions
diff --git a/runtime/src/code_hooks.h b/runtime/src/code_hooks.h
new file mode 100644
index 000000000..6b661b2d1
--- /dev/null
+++ b/runtime/src/code_hooks.h
@@ -0,0 +1,138 @@
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
77// Points every E8/E9 rel32 in [begin, begin + size) whose target is `target` at `thunk`. The range must be writable.
78// Returns how many were rewritten.
79inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target,
80 const uint8_t* thunk) {
81 std::size_t n = 0;
82 for (std::size_t i = 0; i + 5 <= size; ++i) {
83 if (begin[i] != 0xE8 && begin[i] != 0xE9) continue;
84 int32_t rel;
85 std::memcpy(&rel, begin + i + 1, 4);
86 const uint8_t* next = begin + i + 5;
87 if (next + rel != target) continue;
88 const intptr_t to = thunk - next;
89 if (to < INT32_MIN || to > INT32_MAX) continue;
90 const int32_t rel2 = static_cast<int32_t>(to);
91 std::memcpy(begin + i + 1, &rel2, 4);
92 ++n;
93 i += 4;
94 }
95 return n;
96}
97
98struct HookResult {
99 bool ok = false;
100 std::size_t redirected = 0;
101 const char* error = "";
102};
103
104// Hooks the function at `target_rva` of the mapped image at `base`: one thunk, then every direct call or jump to it
105// in the image's executable sections. Runs before any image code (main.cpp), so no thread is executing the bytes.
106inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) {
107 HookResult r;
108 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
109 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return r.error = "not a mapped PE image", r;
110 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
111 if (nt->Signature != IMAGE_NT_SIGNATURE || target_rva >= nt->OptionalHeader.SizeOfImage)
112 return r.error = "the RVA is outside the image", r;
113 const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
114 bool in_code = false;
115 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i)
116 if ((sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && target_rva >= sec[i].VirtualAddress &&
117 target_rva < sec[i].VirtualAddress + sec[i].Misc.VirtualSize)
118 in_code = true;
119 if (!in_code) return r.error = "the RVA is not in an executable section", r;
120 uint8_t* target = base + target_rva;
121 uint8_t* thunk = make_remap_thunk(target, arg, fn, target);
122 if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r;
123 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
124 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue;
125 uint8_t* begin = base + sec[i].VirtualAddress;
126 const std::size_t size = sec[i].Misc.VirtualSize;
127 DWORD old = 0;
128 if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) return r.error = "VirtualProtect failed", r;
129 r.redirected += redirect_direct_branches(begin, size, target, thunk);
130 DWORD ignored = 0;
131 VirtualProtect(begin, size, old, &ignored);
132 FlushInstructionCache(GetCurrentProcess(), begin, size);
133 }
134 r.ok = true;
135 return r;
136}
137
138} // namespace leonida::hooks