From 3c29d4bcb7baea22aae59b5893e8aa03b00d276f Mon Sep 17 00:00:00 2001 From: BBareth <179921368+BBareth@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:41:59 +0100 Subject: [PATCH] PE loader: rewrite console waits that cross an 8-byte word A monitorx / mwaitx on a CPU without them (Intel) is rewritten in place at its first fault, but only when it fits in one aligned 8-byte word. GTA 6 has a monitorx at an address ending in 7: its 3 bytes cross two words, rewrite_code refused it, and every poll of that spin loop raised #UD and was emulated. A 10 s WPR trace in the world showed about 2,359 kernel samples on the render thread in that exception path. Such an instruction is now rewritten with one lock cmpxchg16b (the std::arch intrinsic) on its aligned 16-byte block, with the same compare-and-retry and page protection as the 8-byte path. Only one across a 16-byte boundary stays emulated. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/eh.rs | 92 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 073e51d91f..2fc724124f 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -443,25 +443,58 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec } } -/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads -/// executing it observe either the complete old instruction or the complete replacement. +/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead. +unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> { + // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may + // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction) + let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire); + if found == was { Ok(()) } else { Err(found) } +} + +/// `replace_code_word` for an instruction across two words of an aligned 16-byte block. +unsafe fn replace_code_block(cell: *mut u128, off: usize, expected: &[u8], new: &[u8]) -> bool { + // a torn read only fails the first compare, which then reloads the block atomically + let mut was = std::ptr::read_volatile(cell); + loop { + let mut bytes = was.to_le_bytes(); + if bytes[off..off + new.len()] == *new { + return true; + } + if bytes[off..off + expected.len()] != *expected { + return false; + } + bytes[off..off + new.len()].copy_from_slice(new); + match compare_exchange_16(cell, was, u128::from_le_bytes(bytes)) { + Ok(()) => return true, + Err(now) => was = now, + } + } +} + +/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word, or else +/// in an aligned 16-byte block. Threads executing it observe either the complete old instruction +/// or the complete replacement. fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; use windows_sys::Win32::System::Threading::GetCurrentProcess; - let word = at & !7; + let width = if (at & 7) + new.len() <= 8 { 8 } else { 16 }; + let word = at & !(width - 1); let off = at - word; - if expected.is_empty() || expected.len() != new.len() || off + new.len() > 8 { + if expected.is_empty() || expected.len() != new.len() || off + new.len() > width { return false; } let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); let mut old = 0u32; unsafe { - if VirtualProtect(word as *const c_void, 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + if VirtualProtect(word as *const c_void, width, PAGE_EXECUTE_READWRITE, &mut old) == 0 { return false; } - let cell = &*(word as *const std::sync::atomic::AtomicU64); - let replaced = replace_code_word(cell, off, expected, new); + let replaced = if width == 8 { + replace_code_word(&*(word as *const std::sync::atomic::AtomicU64), off, expected, new) + } else { + replace_code_block(word as *mut u128, off, expected, new) + }; // Publish while CODE_REWRITE is still held. A stale exception lookup takes the same lock // first, so it cannot observe the replacement without its registry entry. The bytes have // changed even if restoring protection or flushing the cache below reports failure. @@ -469,8 +502,8 @@ fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { remember_rewritten_wait(at, new); } let mut ignored = 0u32; - let restored = VirtualProtect(word as *const c_void, 8, old, &mut ignored) != 0; - let flushed = FlushInstructionCache(GetCurrentProcess(), word as *const c_void, 8) != 0; + let restored = VirtualProtect(word as *const c_void, width, old, &mut ignored) != 0; + let flushed = FlushInstructionCache(GetCurrentProcess(), word as *const c_void, width) != 0; replaced && restored && flushed } } @@ -1468,15 +1501,42 @@ mod tests { } } + /// A wait across two 8-byte words (GTA 6's monitorx at an address ending in 7) is rewritten + /// in its aligned 16-byte block; only one across a 16-byte boundary stays emulated. #[test] - fn a_rewrite_crossing_an_atomic_word_stays_emulated() { - let mut buf = [0xCCu8; 24]; - let word = (buf.as_mut_ptr() as usize + 7) & !7; - let at = word + 6; + fn a_rewrite_crossing_an_atomic_word_uses_its_16_byte_block() { + #[repr(align(16))] + struct Block([u8; 64]); + let mut buf = Block([0xCC; 64]); + let base = buf.0.as_mut_ptr() as usize; let before = [0x0F, 0x01, 0xFA]; - unsafe { std::ptr::copy_nonoverlapping(before.as_ptr(), at as *mut u8, before.len()) }; - assert!(!rewrite_code(at, &before, &[0x90; 3])); - assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 3) }, &before); + for (at, rewritten) in [(base + 6, true), (base + 16 + 7, true), (base + 32 + 14, false)] { + unsafe { std::ptr::copy_nonoverlapping(before.as_ptr(), at as *mut u8, before.len()) }; + assert_eq!(rewrite_code(at, &before, &[0x90; 3]), rewritten, "at block offset {}", at & 15); + let now = unsafe { std::slice::from_raw_parts(at as *const u8, 3) }; + assert_eq!(now, if rewritten { &[0x90; 3] } else { &before }); + } + // the bytes around each site are untouched + assert!(buf.0[..6].iter().chain(&buf.0[9..23]).chain(&buf.0[26..46]).chain(&buf.0[49..]).all(|&b| b == 0xCC)); + forget_rewritten_waits(base, base + 64); + } + + /// The 16-byte exchange stores on a match and reports what it found on a mismatch; the blocks + /// on either side keep their bytes. + #[test] + fn compare_exchange_16_stores_on_a_match_and_reports_a_mismatch() { + #[repr(align(16))] + struct Blocks([u128; 3]); + let (was, new, other) = (0x0123_4567_89AB_CDEF_0FED_CBA9_8765_4321u128, 0xA5A5_5A5A_1111_2222_3333_4444_5555_6666u128, 7u128); + let mut b = Blocks([u128::MAX, was, u128::MAX]); + let cell = &mut b.0[1] as *mut u128; + unsafe { + assert_eq!(compare_exchange_16(cell, other, new), Err(was), "a mismatch reports the value found"); + assert_eq!(*cell, was, "and stores nothing"); + assert_eq!(compare_exchange_16(cell, was, new), Ok(())); + assert_eq!(*cell, new); + } + assert_eq!((b.0[0], b.0[2]), (u128::MAX, u128::MAX)); } /// `67 0F 01 FC`: CLZERO at EAX. rax's upper half set, and memory mapped at both the 64- and