From 85b8f5b7f098223a02267667b391ff3d7e984c14 Mon Sep 17 00:00:00 2001 From: ImLele69 Date: Wed, 25 Nov 2026 01:58:20 +0100 Subject: [PATCH 1/2] cpu_emulation: rewrite CLWB in place at its first #UD (RT-CLWB-PATCH) On a host without CLWB every execution of the instruction raised #UD and the vectored handler emulated it. The retail title's GPU upload worker flushes whole buffers with CLWB in a 64-byte loop (exe+0x532f1b0 on 1.0.2.1), so a buffer cost one exception per cache line; under Wine that kept the worker busy for minutes and the main thread polling its event in session 0xd, so the boot never left the first-run pages. The handler now rewrites the instruction at its first #UD: 66 0F AE /6 becomes 66 0F AE /7 (CLFLUSHOPT), the same operand and length, which also writes the line back; a host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length. LEONIDA_CLWB_PATCH=0 keeps the old per-execution emulation. Tested: cpu_emulation_test under Wine 11.21 on an i9-9900KF (no CLWB, has CLFLUSHOPT): both sites rewritten, SIB and displacement kept, the code runs again. Retail boot on the same machine with #984 + #968 (RTX 2070 SUPER, Fedora 44): the worker that sat in the CLWB loop at 420, 540 and 660 s now moves on, and the title gets past the first-run pages into the story load. AI-assisted: yes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RBZntAmGCDe3LdLjbzZzuc --- runtime/src/cpu_emulation.h | 35 +++++++++++++++++++++++++++++ runtime/test/cpu_emulation_test.cpp | 11 +++++++++ 2 files changed, 46 insertions(+) diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index 8df3b55d0a..777a536bd7 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h @@ -350,6 +350,40 @@ inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, return ClzeroLoopResult::ok; } +// CLWB is rewritten in place at its first #UD, so a loop over a buffer faults once instead of once per cache line. +// The retail title's GPU upload worker flushes whole buffers that way (exe+0x532f1b0 on 1.0.2.1); under Wine a #UD +// costs tens of microseconds, which kept that worker busy for minutes per buffer and the boot waiting on it. +// 66 0F AE /6 (CLWB) becomes 66 0F AE /7 (CLFLUSHOPT): the same operand and length, and it writes the line back too +// (then evicts it). A host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length that touches no memory. +// LEONIDA_CLWB_PATCH=0 keeps emulating every execution instead. +inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { + static const int mode = [] { + char value[4]{}; + if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') return 0; + int r[4]; + __cpuidex(r, 7, 0); + return ((r[1] >> 23) & 1) ? 1 : 2; // EBX bit 23: CLFLUSHOPT + }(); + if (!mode) return false; + std::size_t at = 0; + while (at + 2 < length && !(code[at] == 0x0F && code[at + 1] == 0xAE)) ++at; + if (at + 2 >= length) return false; + uint8_t patched[3] = {0x0F, 0xAE, uint8_t(code[at + 2] | 0x08)}; // reg field 6 -> 7 + if (mode == 2) patched[1] = 0x1F, patched[2] = uint8_t(code[at + 2] & ~0x38); // reg field 0 + void* const where = reinterpret_cast(rip + at); + DWORD old = 0; + if (!VirtualProtect(where, sizeof patched, PAGE_EXECUTE_READWRITE, &old)) return false; + std::memcpy(where, patched, sizeof patched); + VirtualProtect(where, sizeof patched, old, &old); + FlushInstructionCache(GetCurrentProcess(), where, sizeof patched); + static std::atomic sites{0}; + const unsigned n = ++sites; + if (n <= 4 || !(n & (n - 1))) + std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n", reinterpret_cast(rip), + mode == 1 ? "CLFLUSHOPT" : "a NOP", n); + return true; +} + inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; CONTEXT* c = info->ContextRecord; @@ -358,6 +392,7 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { std::memcpy(code, reinterpret_cast(c->Rip), avail); const Decoded d = decode(code, avail); if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; + if (d.op == Op::clwb && patch_clwb(c->Rip, code, d.length)) return EXCEPTION_CONTINUE_EXECUTION; EXCEPTION_RECORD fault; if (d.op == Op::clzero && !d.addr32 && d.length == 3) { const uint64_t fault_rip = c->Rip; diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index f94f080443..824c387183 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp @@ -334,6 +334,17 @@ void test_live(const ce::Host& host) { uint32_t marker = 0; check(run(wb, lines, &marker, &ex) && marker == 1, "clwb ran and execution continued after it"); std::printf("clwb: %s\n", path(host.clwb)); + if (!host.clwb) { + // Both sites were rewritten at their first #UD: CLFLUSHOPT (reg field 7) or the same-length NOP. + const auto rewritten = [&](int at) { + return (wb.mem[at] == 0xAE && (wb.mem[at + 1] & 0x38) == 0x38) || + (wb.mem[at] == 0x1F && (wb.mem[at + 1] & 0x38) == 0); + }; + check(rewritten(4) && rewritten(8), "clwb sites rewritten in place"); + check(wb.mem[10] == 0x01 && wb.mem[11] == 0x08, "the rewritten clwb keeps its SIB and displacement"); + marker = 0; + check(run(wb, lines, &marker, &ex) && marker == 1, "the rewritten code runs again"); + } // A #UD the handler does not know stays an illegal-instruction exception: ud2; ret Code ud({0x0F, 0x0B, 0xC3}); From 5d677b7ba2b2dd5b128455edf2b92bea6da4dcc2 Mon Sep 17 00:00:00 2001 From: OreoFR Date: Sat, 28 Nov 2026 05:28:00 +0100 Subject: [PATCH 2/2] cpu_emulation: a CLWB #UD on a site another thread rewrote continues at it (RT-CLWB-PATCH) Threads that fault on the same CLWB site together lost the race: a #UD handled after another thread rewrote the site decoded CLFLUSHOPT (or the NOP), did not know it and returned EXCEPTION_CONTINUE_SEARCH, which ends the title. - The handler continues at a site that already holds the form written on this host (or the NOP's halfway state): the CPU runs it. - One lock around unprotect, re-check, write and protect again, so two threads never interleave on a page; a site found rewritten under it is not written. - The NOP is written opcode first (66 0F 1F /6 in between is a NOP too). - The sites counter counts each site once, by the thread that wrote it. cpu_emulation_test calls the handler with a made-up #UD, so it runs on hosts with CLWB: first #UD, a second one on the rewritten site, and 16 threads on 2048 fresh execute-read sites. Before the fix 27958 of 32768 concurrent #UDs were passed on, 4810 rewrites were counted for 2048 sites and pages were left writable; with it all checks pass. Co-Authored-By: Claude Opus 5.5 --- runtime/src/cpu_emulation.h | 79 ++++++++++++++++---- runtime/test/cpu_emulation_test.cpp | 112 ++++++++++++++++++++++++++++ 2 files changed, 177 insertions(+), 14 deletions(-) diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index 777a536bd7..4f9565dccb 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h @@ -356,7 +356,11 @@ inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, // 66 0F AE /6 (CLWB) becomes 66 0F AE /7 (CLFLUSHOPT): the same operand and length, and it writes the line back too // (then evicts it). A host without CLFLUSHOPT gets 66 0F 1F /0, a NOP of the same length that touches no memory. // LEONIDA_CLWB_PATCH=0 keeps emulating every execution instead. -inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { +// Threads of that worker reach the same site together: a #UD handled after another thread rewrote the site finds +// the new instruction there and continues at it, and the rewrite itself is done once, under a lock. + +// 1: rewrite as CLFLUSHOPT, 2: as the NOP (no CLFLUSHOPT on this host), 0: LEONIDA_CLWB_PATCH=0. +inline int clwb_patch_mode() { static const int mode = [] { char value[4]{}; if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') return 0; @@ -364,24 +368,70 @@ inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { __cpuidex(r, 7, 0); return ((r[1] >> 23) & 1) ? 1 : 2; // EBX bit 23: CLFLUSHOPT }(); + return mode; +} + +// How many CLWB sites were rewritten so far; each counts once, by the thread that wrote it. +inline std::atomic& clwb_sites() { + static std::atomic sites{0}; + return sites; +} + +// True when `code` (`avail` bytes at a #UD) holds the form patch_clwb writes on this host, or the NOP's halfway +// state (66 0F 1F /6): another thread rewrote the site after this thread's #UD. Neither form raises #UD here, so the +// thread continues at the site and the CPU runs it. +inline bool clwb_rewritten(const uint8_t* code, std::size_t avail) { + const int mode = clwb_patch_mode(); + if (!mode) return false; + std::size_t i = 0; + bool p66 = false; + for (; i < avail && i < 14; ++i) { + const uint8_t b = code[i]; + if (b == 0x66) p66 = true; + else if (!((b & 0xF0) == 0x40 || b == 0x67 || b == 0x2E || b == 0x3E || b == 0x26 || b == 0x36 || + b == 0x64 || b == 0x65)) break; + } + if (!p66 || i + 3 > avail || code[i] != 0x0F || (code[i + 2] >> 6) == 3) return false; + const int reg = (code[i + 2] >> 3) & 7; + return mode == 1 ? code[i + 1] == 0xAE && reg == 7 : code[i + 1] == 0x1F && (reg == 0 || reg == 6); +} + +inline bool patch_clwb(uint64_t rip, const uint8_t* code, std::size_t length) { + const int mode = clwb_patch_mode(); if (!mode) return false; std::size_t at = 0; while (at + 2 < length && !(code[at] == 0x0F && code[at + 1] == 0xAE)) ++at; if (at + 2 >= length) return false; - uint8_t patched[3] = {0x0F, 0xAE, uint8_t(code[at + 2] | 0x08)}; // reg field 6 -> 7 - if (mode == 2) patched[1] = 0x1F, patched[2] = uint8_t(code[at + 2] & ~0x38); // reg field 0 + const uint8_t opcode = mode == 1 ? 0xAE : 0x1F; + const uint8_t modrm = mode == 1 ? uint8_t(code[at + 2] | 0x08) : uint8_t(code[at + 2] & ~0x38); // reg 7 or 0 void* const where = reinterpret_cast(rip + at); + volatile uint8_t* const live = static_cast(where); + // One thread at a time unprotects, checks, writes and protects again: without the lock a thread could write into + // a page another one has just set back to read-execute, or set it back to the read-write-execute it found. + static SRWLOCK lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&lock); + bool ok = live[1] == opcode && live[2] == modrm; // another thread rewrote it since this thread's #UD + bool wrote = false; DWORD old = 0; - if (!VirtualProtect(where, sizeof patched, PAGE_EXECUTE_READWRITE, &old)) return false; - std::memcpy(where, patched, sizeof patched); - VirtualProtect(where, sizeof patched, old, &old); - FlushInstructionCache(GetCurrentProcess(), where, sizeof patched); - static std::atomic sites{0}; - const unsigned n = ++sites; - if (n <= 4 || !(n & (n - 1))) - std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n", reinterpret_cast(rip), - mode == 1 ? "CLFLUSHOPT" : "a NOP", n); - return true; + if (!ok && live[0] == 0x0F && live[1] == 0xAE && live[2] == code[at + 2] && + VirtualProtect(where, 3, PAGE_EXECUTE_READWRITE, &old)) { + // Opcode first: between the two stores a thread running the site sees 66 0F 1F /6, a NOP as well. ModRM first + // would show it 66 0F AE /0, FXSAVE's encoding with a 66 the SDM does not allow (a 512-byte store at the + // operand, or a #UD that is no longer CLWB). CLFLUSHOPT only changes ModRM, one store. + if (live[1] != opcode) live[1] = opcode; + live[2] = modrm; + VirtualProtect(where, 3, old, &old); + FlushInstructionCache(GetCurrentProcess(), where, 3); + ok = wrote = true; + } + ReleaseSRWLockExclusive(&lock); + if (wrote) { + const unsigned n = ++clwb_sites(); + if (n <= 4 || !(n & (n - 1))) + std::fprintf(stderr, "[rt] cpu: CLWB at %p rewritten as %s (%u sites so far)\n", + reinterpret_cast(rip), mode == 1 ? "CLFLUSHOPT" : "a NOP", n); + } + return ok; } inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { @@ -391,7 +441,8 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary std::memcpy(code, reinterpret_cast(c->Rip), avail); const Decoded d = decode(code, avail); - if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; + if (d.op == Op::none) + return clwb_rewritten(code, avail) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; if (d.op == Op::clwb && patch_clwb(c->Rip, code, d.length)) return EXCEPTION_CONTINUE_EXECUTION; EXCEPTION_RECORD fault; if (d.op == Op::clzero && !d.addr32 && d.length == 3) { diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index 824c387183..b715320dbf 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp @@ -5,10 +5,12 @@ // The test prints which path each instruction took. No game files. #include +#include #include #include #include #include +#include #include #include "cpu_emulation.h" @@ -350,6 +352,115 @@ void test_live(const ce::Host& host) { Code ud({0x0F, 0x0B, 0xC3}); check(!run(ud, nullptr, nullptr, &ex) && ex == STATUS_ILLEGAL_INSTRUCTION, "ud2 still faults"); } + +// ---- CLWB rewritten in place, with the handler called on a made-up #UD ---- +// The #UD a CPU without CLWB raises is handed to the handler directly, so this runs on a host with CLWB too. A +// thread whose #UD is handled after another thread rewrote the same site reads the new bytes: it must continue at +// the site (the CPU runs the rewritten instruction), never pass the exception on. Each site is rewritten once. + +// The handler's answer to a #UD at `rip`, and the RIP it continues at; -2 when the handler itself faulted. +LONG fake_ud(uint64_t rip, uint64_t* rip_after) { + EXCEPTION_RECORD record{}; + record.ExceptionCode = DWORD(STATUS_ILLEGAL_INSTRUCTION); + record.ExceptionAddress = reinterpret_cast(rip); + CONTEXT context{}; + context.Rip = rip; + EXCEPTION_POINTERS pointers{&record, &context}; + __try { + const LONG r = ce::handler(&pointers); + *rip_after = context.Rip; + return r; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return -2; + } +} + +bool call_at(const uint8_t* code, const void* in) { + __try { + reinterpret_cast(const_cast(code))(in, nullptr); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// clwb [rcx]; ret at `at` became CLFLUSHOPT [rcx] (reg field 7) or the NOP 0F 1F /0 with the same operand. +bool clwb_rewritten(const uint8_t* at) { + return at[0] == 0x66 && at[1] == 0x0F && at[4] == 0xC3 && (at[3] & 0xC7) == 0x01 && + ((at[2] == 0xAE && (at[3] & 0x38) == 0x38) || (at[2] == 0x1F && (at[3] & 0x38) == 0)); +} + +bool executable_read_only(const void* p) { + MEMORY_BASIC_INFORMATION mbi{}; + return VirtualQuery(p, &mbi, sizeof mbi) && mbi.Protect == PAGE_EXECUTE_READ; +} + +void test_clwb_rewrite() { + char value[4]{}; + if (GetEnvironmentVariableA("LEONIDA_CLWB_PATCH", value, sizeof(value)) > 0 && value[0] == '0') { + std::printf("clwb rewrite: skipped (LEONIDA_CLWB_PATCH=0)\n"); + return; + } + constexpr int kSites = 2048, kStride = 8, kThreads = 16; + const std::size_t bytes = std::size_t(kSites + 1) * kStride; + auto* mem = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + check(mem != nullptr, "clwb rewrite: allocate the sites"); + if (!mem) return; + for (int s = 0; s <= kSites; ++s) { // clwb [rcx]; ret; int3 x3 + const uint8_t site[kStride] = {0x66, 0x0F, 0xAE, 0x31, 0xC3, 0xCC, 0xCC, 0xCC}; + std::memcpy(mem + std::size_t(s) * kStride, site, kStride); + } + DWORD old = 0; + VirtualProtect(mem, bytes, PAGE_EXECUTE_READ, &old); // as the game's code: the handler must unprotect it + FlushInstructionCache(GetCurrentProcess(), mem, bytes); + + // (a) The first #UD rewrites the site and continues at it, which then runs on any host. + uint8_t* const one = mem + std::size_t(kSites) * kStride; + const uint64_t rip = reinterpret_cast(one); + const unsigned before = ce::clwb_sites().load(); + uint64_t after = 0; + check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip, + "clwb rewrite: the first #UD continues at the site"); + check(clwb_rewritten(one), "clwb rewrite: the site is rewritten, operand kept"); + check(ce::clwb_sites().load() == before + 1, "clwb rewrite: the site is counted once"); + check(executable_read_only(one), "clwb rewrite: the page is execute-read again"); + alignas(64) static uint8_t line[64]; + check(call_at(one, line), "clwb rewrite: the rewritten site runs"); + + // (b) A #UD handled after the site was rewritten (another thread's, in the game) continues at the site too. + after = 0; + check(fake_ud(rip, &after) == EXCEPTION_CONTINUE_EXECUTION && after == rip, + "clwb rewrite: a #UD on an already rewritten site continues at it"); + check(ce::clwb_sites().load() == before + 1, "clwb rewrite: an already rewritten site is not counted again"); + + // (c) 16 threads take a #UD on each of 2048 fresh sites at once, in the same order so they meet on each site. + std::atomic waiting{kThreads}, bad{0}; + std::vector threads; + for (int t = 0; t < kThreads; ++t) + threads.emplace_back([&] { + waiting.fetch_sub(1); + while (waiting.load()) std::this_thread::yield(); + for (int s = 0; s < kSites; ++s) { + const uint64_t at = reinterpret_cast(mem + std::size_t(s) * kStride); + uint64_t continued = 0; + if (fake_ud(at, &continued) != EXCEPTION_CONTINUE_EXECUTION || continued != at) bad.fetch_add(1); + } + }); + for (auto& t : threads) t.join(); + if (bad.load()) std::fprintf(stderr, "clwb rewrite: %d of %d concurrent #UDs not continued at the site\n", + bad.load(), kThreads * kSites); + check(bad.load() == 0, "clwb rewrite: every concurrent #UD continues at its site"); + const unsigned counted = ce::clwb_sites().load() - before - 1; + if (counted != unsigned(kSites)) std::fprintf(stderr, "clwb rewrite: %u sites counted for %d\n", counted, kSites); + check(counted == unsigned(kSites), "clwb rewrite: each concurrently hit site is counted once"); + bool all = true; + for (int s = 0; s < kSites; ++s) all &= clwb_rewritten(mem + std::size_t(s) * kStride); + check(all, "clwb rewrite: every concurrently hit site is rewritten"); + check(executable_read_only(mem) && executable_read_only(mem + bytes - 1), + "clwb rewrite: the pages are execute-read again"); + std::printf("clwb rewrite: %d threads x %d sites\n", kThreads, kSites); + VirtualFree(mem, 0, MEM_RELEASE); +} } // namespace int main() { @@ -361,6 +472,7 @@ int main() { host.clwb); check(ce::install(), "install the handler"); test_live(host); + test_clwb_rewrite(); if (failures) { std::fprintf(stderr, "%d failure(s)\n", failures); return 1;