From ea2f4356e1d63808cb0ecb94ccda13509bb3e1d5 Mon Sep 17 00:00:00 2001 From: Madhyn Date: Wed, 25 Nov 2026 01:44:35 -0300 Subject: [PATCH 1/2] cpu_emulation: rewrite bare MONITORX/MWAITX in place at first #UD (RT-MONITORX-PATCH) On Intel hosts, AMD-only MONITORX (0F 01 FA) and MWAITX (0F 01 FB) spin-wait sites raise #UD on every loop iteration. Rewrite bare 3-byte sites in place at their first #UD via a page-bounded atomic 32-bit compare-exchange under SRWLOCK: MONITORX -> 3-byte NOP (0F 1F 00) and MWAITX -> PAUSE; NOP (F3 90 90). Prefixed and page-straddling forms fall back to per-fault emulation. Opt out with LEONIDA_MONITORX_PATCH=0. --- runtime/src/cpu_emulation.h | 63 +++++++++++++++++++++++++ runtime/test/cpu_emulation_test.cpp | 71 +++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+) diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index 8df3b55d0a..5d6ca27ff2 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h @@ -272,6 +272,65 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt return true; } +// MONITORX (0F 01 FA) and MWAITX (0F 01 FB) are AMD-only spin-wait instructions. On Intel hosts every execution +// raises #UD; under Wine each #UD costs tens of microseconds. Rewrite bare 3-byte sites in place at their first +// #UD: MONITORX becomes a 3-byte NOP (0F 1F 00) and MWAITX becomes PAUSE; NOP (F3 90 90). The 3 bytes are swapped +// via an atomic 32-bit compare-exchange kept strictly within the instruction's 4 KiB page so concurrent threads +// executing the same site never observe a torn intermediate encoding. Prefixed and page-straddling forms fall back +// to per-fault emulation. LEONIDA_MONITORX_PATCH=0 keeps emulating every execution instead. +inline bool patch_monitorx_mwaitx(uint64_t rip, Op op, const uint8_t* code, std::size_t length) { + static const bool enabled = [] { + char value[4]{}; + return !(GetEnvironmentVariableA("LEONIDA_MONITORX_PATCH", value, sizeof(value)) > 0 && value[0] == '0'); + }(); + if (!enabled || length != 3) return false; + const uint8_t modrm = (op == Op::monitorx) ? 0xFA : 0xFB; + if (code[0] != 0x0F || code[1] != 0x01 || code[2] != modrm) return false; + // Keep the 4-byte atomic window inside one 4 KiB page; straddling sites (>= 0xFFE) stay on per-fault emulation. + if ((rip & 0xFFFu) > 0xFFDu) return false; + const bool shift_back = (rip & 0xFFFu) == 0xFFDu; + const uint64_t window_addr = shift_back ? rip - 1 : rip; + const std::size_t off = shift_back ? 1 : 0; + const uint8_t target[3] = {uint8_t(op == Op::monitorx ? 0x0F : 0xF3), + uint8_t(op == Op::monitorx ? 0x1F : 0x90), + uint8_t(op == Op::monitorx ? 0x00 : 0x90)}; + static SRWLOCK patch_lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&patch_lock); + bool ok = false; + const auto* live = reinterpret_cast(rip); + if (live[0] == target[0] && live[1] == target[1] && live[2] == target[2]) { + ok = true; + } else if (live[0] == 0x0F && live[1] == 0x01 && live[2] == modrm) { + DWORD old = 0; + if (VirtualProtect(reinterpret_cast(window_addr), 4, PAGE_EXECUTE_READWRITE, &old)) { + uint8_t before[4]{}, after[4]{}; + std::memcpy(before, reinterpret_cast(window_addr), 4); + std::memcpy(after, before, 4); + after[off] = target[0]; + after[off + 1] = target[1]; + after[off + 2] = target[2]; + LONG expected = 0, desired = 0; + std::memcpy(&expected, before, 4); + std::memcpy(&desired, after, 4); + const LONG observed = InterlockedCompareExchange( + reinterpret_cast(window_addr), desired, expected); + DWORD unused = 0; + VirtualProtect(reinterpret_cast(window_addr), 4, old, &unused); + FlushInstructionCache(GetCurrentProcess(), reinterpret_cast(rip), 3); + if (observed == expected) { + ok = true; + static std::atomic sites{0}; + const unsigned n = ++sites; + if (n <= 8 || !(n & (n - 1))) + std::fprintf(stderr, "[rt] cpu: %s at %p rewritten as %s (%u sites so far)\n", name(op), + reinterpret_cast(rip), op == Op::monitorx ? "3-byte NOP" : "PAUSE; NOP", n); + } + } + } + ReleaseSRWLockExclusive(&patch_lock); + return ok; +} + inline uint64_t gpr_read(const CONTEXT* c, int r) { switch (r) { case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx; @@ -378,6 +437,10 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; } } + if ((d.op == Op::monitorx || d.op == Op::mwaitx) && patch_monitorx_mwaitx(c->Rip, d.op, code, d.length)) { + count(d.op).fetch_add(1, std::memory_order_relaxed); + return EXCEPTION_CONTINUE_EXECUTION; + } if (!apply(d, c, &fault)) { // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers // see it instead of the #UD (RIP still points at the instruction). diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index f94f080443..f203c8c851 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp @@ -327,6 +327,77 @@ void test_live(const ce::Host& host) { 0xC3}); check(run(mon, lines, nullptr, &ex), "monitorx/mwaitx ran"); std::printf("monitorx/mwaitx: %s\n", path(host.monitorx)); + char mon_patch_env[4]{}; + const bool mon_patch_on = + !(GetEnvironmentVariableA("LEONIDA_MONITORX_PATCH", mon_patch_env, sizeof(mon_patch_env)) > 0 && + mon_patch_env[0] == '0'); + if (!host.monitorx && !mon_patch_on) { + check(mon.mem[7] == 0x0F && mon.mem[8] == 0x01 && mon.mem[9] == 0xFA && mon.mem[14] == 0x0F && + mon.mem[15] == 0x01 && mon.mem[16] == 0xFB, + "LEONIDA_MONITORX_PATCH=0 leaves monitorx/mwaitx bytes untouched"); + } else if (!host.monitorx) { + check(mon.mem[7] == 0x0F && mon.mem[8] == 0x1F && mon.mem[9] == 0x00, + "monitorx rewritten in place as 3-byte NOP"); + check(mon.mem[14] == 0xF3 && mon.mem[15] == 0x90 && mon.mem[16] == 0x90, + "mwaitx rewritten in place as pause; nop"); + const uint64_t mon_before = ce::count(ce::Op::monitorx).load(); + const uint64_t mwait_before = ce::count(ce::Op::mwaitx).load(); + check(run(mon, lines, nullptr, &ex), "rewritten monitorx/mwaitx code runs again"); + check(ce::count(ce::Op::monitorx).load() == mon_before && ce::count(ce::Op::mwaitx).load() == mwait_before, + "rewritten monitorx/mwaitx runs without faulting again"); + + // Prefixed forms (length 4) stay unpatched and fall back to per-fault emulation. + Code mon_pref({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x66, 0x0F, 0x01, 0xFA, + 0x31, 0xC0, 0x31, 0xC9, 0x66, 0x0F, 0x01, 0xFB, 0xC3}); + check(run(mon_pref, lines, nullptr, &ex), "prefixed monitorx/mwaitx ran via emulation"); + check(mon_pref.mem[7] == 0x66 && mon_pref.mem[8] == 0x0F && mon_pref.mem[9] == 0x01 && + mon_pref.mem[10] == 0xFA && mon_pref.mem[15] == 0x66 && mon_pref.mem[16] == 0x0F && + mon_pref.mem[17] == 0x01 && mon_pref.mem[18] == 0xFB, + "prefixed monitorx/mwaitx bytes stay untouched"); + + // Page-end (0xFFD, shift-back atomic window) and page-straddling (0xFFE, emulated fallback). + auto* two_pages = static_cast( + VirtualAlloc(nullptr, 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + check(two_pages != nullptr, "allocate two pages for page-boundary monitorx/mwaitx checks"); + if (two_pages) { + // Case 1: 0xFFC: nop; 0xFFD..0xFFF: mwaitx; 0x1000: ret + two_pages[0xFFC] = 0x90; + two_pages[0xFFD] = 0x0F; + two_pages[0xFFE] = 0x01; + two_pages[0xFFF] = 0xFB; + two_pages[0x1000] = 0xC3; + DWORD old = 0; + VirtualProtect(two_pages, 0x2000, PAGE_EXECUTE_READ, &old); + const auto run_at = [&](uint8_t* entry) { + __try { + reinterpret_cast(entry)(lines, nullptr); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } + }; + check(run_at(two_pages + 0xFFC), "page-end mwaitx at 0xFFD ran"); + check(two_pages[0xFFC] == 0x90 && two_pages[0xFFD] == 0xF3 && two_pages[0xFFE] == 0x90 && + two_pages[0xFFF] == 0x90 && two_pages[0x1000] == 0xC3, + "page-end mwaitx at 0xFFD patched without touching adjacent bytes"); + const uint64_t mwait_edge = ce::count(ce::Op::mwaitx).load(); + check(run_at(two_pages + 0xFFC) && ce::count(ce::Op::mwaitx).load() == mwait_edge, + "page-end rewritten mwaitx runs again without faulting"); + + // Case 2: 0xFFE..0x1000: monitorx straddling page boundary; 0x1001: ret + VirtualProtect(two_pages, 0x2000, PAGE_READWRITE, &old); + two_pages[0xFFE] = 0x0F; + two_pages[0xFFF] = 0x01; + two_pages[0x1000] = 0xFA; + two_pages[0x1001] = 0xC3; + VirtualProtect(two_pages, 0x2000, PAGE_EXECUTE_READ, &old); + check(run_at(two_pages + 0xFFE), "page-straddling monitorx at 0xFFE ran via emulation"); + check(two_pages[0xFFE] == 0x0F && two_pages[0xFFF] == 0x01 && two_pages[0x1000] == 0xFA && + two_pages[0x1001] == 0xC3, + "page-straddling monitorx stays untouched"); + VirtualFree(two_pages, 0, MEM_RELEASE); + } + } // xor eax,eax; clwb [rcx]; clwb [rcx+rax+8]; mov dword [rdx],1; ret Code wb({0x31, 0xC0, 0x66, 0x0F, 0xAE, 0x31, 0x66, 0x0F, 0xAE, 0x74, 0x01, 0x08, 0xC7, 0x02, 0x01, 0, 0, 0, From 44e437bda46bbb426c88c41c5ead6247f0cd7819 Mon Sep 17 00:00:00 2001 From: Madhyn Date: Wed, 25 Nov 2026 10:33:35 -0300 Subject: [PATCH 2/2] cpu_emulation_test: initialize EAX/ECX/EDX before page-boundary MONITORX/MWAITX --- runtime/test/cpu_emulation_test.cpp | 41 ++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index f203c8c851..628c542edf 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp @@ -222,6 +222,16 @@ bool run(const Code& code, const void* in, void* out, DWORD* exception) { } } +bool run_ptr(uint8_t* entry, const void* in, void* out, DWORD* exception) { + *exception = 0; + __try { + reinterpret_cast(entry)(in, out); + return true; + } __except (*exception = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + const char* path(bool host_has) { return host_has ? "native" : "emulated"; } void test_live(const ce::Host& host) { @@ -360,7 +370,11 @@ void test_live(const ce::Host& host) { VirtualAlloc(nullptr, 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); check(two_pages != nullptr, "allocate two pages for page-boundary monitorx/mwaitx checks"); if (two_pages) { - // Case 1: 0xFFC: nop; 0xFFD..0xFFF: mwaitx; 0x1000: ret + // Case 1: 0xFF8: xor eax,eax; 0xFFA: xor ecx,ecx; 0xFFC: nop; 0xFFD..0xFFF: mwaitx; 0x1000: ret + two_pages[0xFF8] = 0x31; + two_pages[0xFF9] = 0xC0; + two_pages[0xFFA] = 0x31; + two_pages[0xFFB] = 0xC9; two_pages[0xFFC] = 0x90; two_pages[0xFFD] = 0x0F; two_pages[0xFFE] = 0x01; @@ -368,30 +382,31 @@ void test_live(const ce::Host& host) { two_pages[0x1000] = 0xC3; DWORD old = 0; VirtualProtect(two_pages, 0x2000, PAGE_EXECUTE_READ, &old); - const auto run_at = [&](uint8_t* entry) { - __try { - reinterpret_cast(entry)(lines, nullptr); - return true; - } __except (EXCEPTION_EXECUTE_HANDLER) { - return false; - } - }; - check(run_at(two_pages + 0xFFC), "page-end mwaitx at 0xFFD ran"); + FlushInstructionCache(GetCurrentProcess(), two_pages, 0x2000); + check(run_ptr(two_pages + 0xFF8, lines, nullptr, &ex), "page-end mwaitx at 0xFFD ran"); check(two_pages[0xFFC] == 0x90 && two_pages[0xFFD] == 0xF3 && two_pages[0xFFE] == 0x90 && two_pages[0xFFF] == 0x90 && two_pages[0x1000] == 0xC3, "page-end mwaitx at 0xFFD patched without touching adjacent bytes"); const uint64_t mwait_edge = ce::count(ce::Op::mwaitx).load(); - check(run_at(two_pages + 0xFFC) && ce::count(ce::Op::mwaitx).load() == mwait_edge, + check(run_ptr(two_pages + 0xFF8, lines, nullptr, &ex) && ce::count(ce::Op::mwaitx).load() == mwait_edge, "page-end rewritten mwaitx runs again without faulting"); - // Case 2: 0xFFE..0x1000: monitorx straddling page boundary; 0x1001: ret + // Case 2: 0xFF7: mov rax,rcx; 0xFFA: xor ecx,ecx; 0xFFC: xor edx,edx; 0xFFE..0x1000: monitorx; 0x1001: ret VirtualProtect(two_pages, 0x2000, PAGE_READWRITE, &old); + two_pages[0xFF7] = 0x48; + two_pages[0xFF8] = 0x89; + two_pages[0xFF9] = 0xC8; + two_pages[0xFFA] = 0x31; + two_pages[0xFFB] = 0xC9; + two_pages[0xFFC] = 0x31; + two_pages[0xFFD] = 0xD2; two_pages[0xFFE] = 0x0F; two_pages[0xFFF] = 0x01; two_pages[0x1000] = 0xFA; two_pages[0x1001] = 0xC3; VirtualProtect(two_pages, 0x2000, PAGE_EXECUTE_READ, &old); - check(run_at(two_pages + 0xFFE), "page-straddling monitorx at 0xFFE ran via emulation"); + FlushInstructionCache(GetCurrentProcess(), two_pages, 0x2000); + check(run_ptr(two_pages + 0xFF7, lines, nullptr, &ex), "page-straddling monitorx at 0xFFE ran via emulation"); check(two_pages[0xFFE] == 0x0F && two_pages[0xFFF] == 0x01 && two_pages[0x1000] == 0xFA && two_pages[0x1001] == 0xC3, "page-straddling monitorx stays untouched");