upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/clzero_patch.h
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src/clzero_patch.h')
-rw-r--r--runtime/src/clzero_patch.h200
1 files changed, 200 insertions, 0 deletions
diff --git a/runtime/src/clzero_patch.h b/runtime/src/clzero_patch.h
new file mode 100644
index 000000000..7ab90e303
--- /dev/null
+++ b/runtime/src/clzero_patch.h
@@ -0,0 +1,200 @@
1// Moves the title's CLZERO loops off the #UD path on a CPU without CLZERO (docs/cpu_features.md).
2//
3// The executable's 10 CLZERO sites are one leaf routine that zeroes buffers a 64-byte line at a time. Emulated on #UD
4// (cpu_emulation.h), every line costs an exception dispatch and two VirtualQuery calls: measured on an i9-13900K,
5// the routine took ~99% of one thread for the whole boot and the title presented at ~3 frames a second. Each site sits
6// in one of two loop shapes, which are matched exactly (register forms only, nothing that refers to RIP):
7//
8// A (12 bytes) clzero; add rax, 40h; cmp rax, END; jb A (END: rdx or r8-r15)
9// B (15 bytes) mov rax, CUR; add CUR, 40h; clzero; cmp CUR, END; jb B (CUR, END: rdx or r8-r15)
10//
11// The loop's first instruction becomes a `jmp rel32` to a copy of the loop in a stub page within 2 GiB of the image,
12// and the rest of the loop becomes int3 (nothing branches into a loop's middle: its jb targets its first byte). In the
13// copy, CLZERO is eight 8-byte stores of zero to the line rAX points into, with RCX saved around them; the loop's own
14// instructions are copied unchanged, so the registers and flags the loop leaves are the ones the original leaves. The
15// copy ends with a jmp to the instruction after the original jb. A line the title cannot write faults in the stub, as
16// the original would fault at its CLZERO; the stub page is logged so such an address can be placed.
17//
18// Run before any of the image's code and before its sections are protected. LEONIDA_CLZERO_PATCH=0 keeps the #UD path.
19#pragma once
20
21#ifdef _WIN32
22#include <windows.h>
23
24#include <cstddef>
25#include <cstdint>
26#include <cstdlib>
27#include <cstring>
28#include <utility>
29#include <vector>
30
31namespace rt::clzero_patch {
32
33struct Site {
34 uint32_t head; // offset of the loop's first byte from the scanned code's start
35 uint32_t length; // 12 (shape A) or 15 (shape B)
36 uint32_t clzero; // offset of the CLZERO within the loop
37};
38
39// `cmp r/m64, r64` (REX.W 39 /r, register form) or `mov`/`add` with the given register as ModRM r/m, for rdx or
40// r8-r15: the registers the routine uses. rcx is excluded because the stub saves it around its stores.
41inline bool is_cmp_rr(const uint8_t* p) {
42 return (p[0] == 0x48 || p[0] == 0x49 || p[0] == 0x4C || p[0] == 0x4D) && p[1] == 0x39 && (p[2] & 0xC0) == 0xC0;
43}
44
45inline bool clzero_at(const uint8_t* p) { return p[0] == 0x0F && p[1] == 0x01 && p[2] == 0xFC; }
46
47// Register number (0-15) of ModRM.rm / ModRM.reg with REX.
48inline unsigned rm_reg(uint8_t rex, uint8_t modrm) { return (modrm & 7) | ((rex & 1) << 3); }
49inline unsigned reg_reg(uint8_t rex, uint8_t modrm) { return ((modrm >> 3) & 7) | ((rex & 4) << 1); }
50
51// Finds the loops in `code[0, size)`. A CLZERO that is in neither shape is left to the #UD path.
52inline std::vector<Site> find(const uint8_t* code, size_t size) {
53 std::vector<Site> sites;
54 for (size_t k = 0; k + 3 <= size; ++k) {
55 if (!clzero_at(code + k)) continue;
56 // Shape A: the CLZERO is the loop's first instruction.
57 if (k + 12 <= size) {
58 const uint8_t* p = code + k;
59 const bool add = p[3] == 0x48 && p[4] == 0x83 && p[5] == 0xC0 && p[6] == 0x40; // add rax, 40h
60 // cmp rax, END: REX.W (+R for r8-r15) 39 /r with rm = rax.
61 const bool cmp = is_cmp_rr(p + 7) && rm_reg(p[7], p[9]) == 0 && (p[7] & 1) == 0;
62 const unsigned end = cmp ? reg_reg(p[7], p[9]) : 0;
63 const bool jb = p[10] == 0x72 && int8_t(p[11]) == -12;
64 if (add && cmp && jb && end != 0 && end != 1 && end != 4) {
65 sites.push_back({uint32_t(k), 12, 0});
66 k += 2;
67 continue;
68 }
69 }
70 // Shape B: mov rax, CUR; add CUR, 40h before the CLZERO; cmp CUR, END; jb after it.
71 if (k >= 7 && k + 8 <= size) {
72 const uint8_t* p = code + k - 7;
73 // mov rax, CUR: REX.W(+R) 89 /r, rm = rax, reg = CUR.
74 const bool mov = (p[0] == 0x48 || p[0] == 0x4C) && p[1] == 0x89 && (p[2] & 0xC7) == 0xC0;
75 const unsigned cur = mov ? reg_reg(p[0], p[2]) : 0;
76 // add CUR, 40h: REX.W(+B) 83 /0 ib with rm = CUR.
77 const bool add = (p[3] == 0x48 || p[3] == 0x49) && p[4] == 0x83 && (p[5] & 0xF8) == 0xC0 &&
78 rm_reg(p[3], p[5]) == cur && p[6] == 0x40;
79 // cmp CUR, END: REX.W 39 /r with rm = CUR, reg = END.
80 const bool cmp = is_cmp_rr(p + 10) && rm_reg(p[10], p[12]) == cur;
81 const unsigned end = cmp ? reg_reg(p[10], p[12]) : 0;
82 const bool jb = p[13] == 0x72 && int8_t(p[14]) == -15;
83 const auto ok = [](unsigned r) { return r == 2 || r >= 8; };
84 if (mov && add && cmp && jb && ok(cur) && ok(end) && cur != end) {
85 sites.push_back({uint32_t(k - 7), 15, 7});
86 k += 7;
87 continue;
88 }
89 }
90 }
91 return sites;
92}
93
94// The stub for one loop: its instructions before the CLZERO, the zeroing block, its instructions after the CLZERO up
95// to the jb, a jb back to the stub's start, then a jmp to `resume` (the instruction after the original jb).
96inline std::vector<uint8_t> stub(const uint8_t* loop, const Site& s, uint64_t stub_at, uint64_t resume) {
97 std::vector<uint8_t> out(loop, loop + s.clzero); // shape B: mov rax, CUR; add CUR, 40h
98 const uint8_t zero_line[] = {
99 0x51, // push rcx
100 0x48, 0x89, 0xC1, // mov rcx, rax
101 0x48, 0x83, 0xE1, 0xC0, // and rcx, -64
102 0x48, 0xC7, 0x01, 0, 0, 0, 0, // mov qword [rcx], 0
103 0x48, 0xC7, 0x41, 0x08, 0, 0, 0, 0, // mov qword [rcx+8], 0
104 0x48, 0xC7, 0x41, 0x10, 0, 0, 0, 0,
105 0x48, 0xC7, 0x41, 0x18, 0, 0, 0, 0,
106 0x48, 0xC7, 0x41, 0x20, 0, 0, 0, 0,
107 0x48, 0xC7, 0x41, 0x28, 0, 0, 0, 0,
108 0x48, 0xC7, 0x41, 0x30, 0, 0, 0, 0,
109 0x48, 0xC7, 0x41, 0x38, 0, 0, 0, 0,
110 0x59, // pop rcx
111 };
112 out.insert(out.end(), std::begin(zero_line), std::end(zero_line));
113 // The instructions between the CLZERO and the jb (shape A: add rax, 40h; cmp; shape B: cmp).
114 out.insert(out.end(), loop + s.clzero + 3, loop + s.length - 2);
115 const int back = -int(out.size() + 2);
116 out.push_back(0x72);
117 out.push_back(uint8_t(int8_t(back)));
118 out.push_back(0xE9);
119 const int64_t rel = int64_t(resume) - int64_t(stub_at + out.size() + 4);
120 const int32_t rel32 = int32_t(rel);
121 const auto* b = reinterpret_cast<const uint8_t*>(&rel32);
122 out.insert(out.end(), b, b + 4);
123 return out;
124}
125
126// Reserves a page within 2 GiB above or below [lo, hi) for the stubs (the image does not move after this).
127inline uint8_t* stub_page(uint64_t lo, uint64_t hi, size_t size) {
128 SYSTEM_INFO si;
129 GetSystemInfo(&si);
130 const uint64_t gran = si.dwAllocationGranularity;
131 const uint64_t limit = uint64_t(1) << 31;
132 for (uint64_t at = (hi + gran - 1) & ~(gran - 1); at + size < lo + limit - 0x1000; at += gran) {
133 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))
134 return static_cast<uint8_t*>(p);
135 }
136 for (uint64_t at = (lo - size) & ~(gran - 1); at > gran && hi - at < limit - 0x1000; at -= gran) {
137 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))
138 return static_cast<uint8_t*>(p);
139 }
140 return nullptr;
141}
142
143inline bool enabled() {
144 char v[8] = {};
145 size_t n = 0;
146 return !(getenv_s(&n, v, "LEONIDA_CLZERO_PATCH") == 0 && n == 2 && v[0] == '0');
147}
148
149struct Result {
150 size_t sites = 0;
151 uint8_t* stubs = nullptr;
152 size_t stub_bytes = 0;
153};
154
155// Patches every loop found in the executable ranges `ranges` (pairs of start address and size, all inside
156// [image_lo, image_hi)). The ranges must be writable. On any failure nothing is patched.
157inline Result patch(const std::vector<std::pair<uint8_t*, size_t>>& ranges, uint64_t image_lo, uint64_t image_hi) {
158 Result r;
159 std::vector<std::pair<uint8_t*, Site>> all;
160 for (const auto& [code, size] : ranges)
161 for (const Site& s : find(code, size)) all.push_back({code, s});
162 if (all.empty()) return r;
163 const size_t page = 0x10000;
164 uint8_t* const stubs = stub_page(image_lo, image_hi, page);
165 if (!stubs) return r;
166 size_t used = 0;
167 std::vector<std::vector<uint8_t>> bodies;
168 for (const auto& [code, s] : all) {
169 uint8_t* const loop = code + s.head;
170 const uint64_t at = uint64_t(stubs + used);
171 bodies.push_back(stub(loop, s, at, uint64_t(loop + s.length)));
172 used += (bodies.back().size() + 15) & ~size_t(15);
173 if (used > page) {
174 VirtualFree(stubs, 0, MEM_RELEASE);
175 return r;
176 }
177 }
178 used = 0;
179 for (size_t i = 0; i < all.size(); ++i) {
180 const auto& [code, s] = all[i];
181 uint8_t* const loop = code + s.head;
182 uint8_t* const at = stubs + used;
183 std::memcpy(at, bodies[i].data(), bodies[i].size());
184 used += (bodies[i].size() + 15) & ~size_t(15);
185 const int32_t rel = int32_t(int64_t(at) - int64_t(loop + 5));
186 loop[0] = 0xE9;
187 std::memcpy(loop + 1, &rel, 4);
188 std::memset(loop + 5, 0xCC, s.length - 5);
189 }
190 DWORD old = 0;
191 VirtualProtect(stubs, page, PAGE_EXECUTE_READ, &old);
192 FlushInstructionCache(GetCurrentProcess(), stubs, page);
193 r.sites = all.size();
194 r.stubs = stubs;
195 r.stub_bytes = used;
196 return r;
197}
198
199} // namespace rt::clzero_patch
200#endif