From 81ad460d7f5eb2f9d662c7a056fd8cfb5da4ab28 Mon Sep 17 00:00:00 2001 From: BBareth <179921368+BBareth@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:13:59 +0100 Subject: [PATCH] PE loader: patch a CLWB with one atomic jump under the rewrite lock A CLWB on a CPU without it is patched out at its first fault. The patch made the bytes writable, filled them with NOPs one at a time and put the protection back, with nothing shared between threads (#278, item 4): - two threads patching on one page could restore each other's protection (also against the wait rewrite, which holds CODE_REWRITE); - another thread could run the half-written bytes (90 0F AE 30 is a nop and xsaveopt [rax]); - a thread that faulted on the CLWB just before the patch found NOPs, which do not decode, and its fault went on to the title's handlers; - the instruction cache was never flushed. The patch now goes through rewrite_code, like the waits: the first two bytes become a short jump over the instruction in one atomic word write under CODE_REWRITE, the protection is restored, the cache is flushed, and a thread that faulted on the old bytes is retried at the jump. The bytes after the jump stay as they were. A site whose first two bytes cross an aligned 8-byte word cannot take the jump in one write. Its opcode and ModRM bytes, which are both in the second word, become those of the NOP with the same operand (0F AE /6 -> 0F 1F /0): the prefixes and the operand bytes stay, so the length is the same and the site is patched once like the others (rewrite_code_within records the site with its unchanged prefix). A visit with TF set still leaves the code alone (#571). Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/eh.rs | 137 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 127 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 073e51d91f..9fe06317c7 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -446,9 +446,16 @@ 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. fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { + rewrite_code_within(at, 0, expected, new) +} + +/// `rewrite_code` for bytes `skip` into the instruction at `site`, whose first `skip` bytes stay: +/// the site is recorded with them, so a thread that faulted on the old instruction is retried. +fn rewrite_code_within(site: usize, skip: 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 at = site + skip; let word = at & !7; let off = at - word; if expected.is_empty() || expected.len() != new.len() || off + new.len() > 8 { @@ -466,7 +473,9 @@ fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { // 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. if replaced { - remember_rewritten_wait(at, new); + let mut now = std::slice::from_raw_parts(site as *const u8, skip).to_vec(); + now.extend_from_slice(new); + remember_rewritten_wait(site, &now); } let mut ignored = 0u32; let restored = VirtualProtect(word as *const c_void, 8, old, &mut ignored) != 0; @@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - // TF requests single-instruction stepping: preserve its boundary on later visits. - if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + // Nothing to emulate. Later visits skip the fault: the first two bytes become a short + // jump over the instruction, through `rewrite_code` like the waits (one atomic word + // write under CODE_REWRITE, the page protection restored, the instruction cache + // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The + // bytes after the jump stay, so no thread can run a half-written instruction. A site + // whose first two bytes cross an aligned word cannot take the jump in one write: its + // opcode and ModRM bytes, which are in the second word, become those of the NOP with + // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay. + // TF requests single-instruction stepping: such a visit leaves the code alone. + if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) { + if (rip & 7) + 2 <= 8 { + rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]); + } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) { + let modrm = code[i + 2]; + rewrite_code_within(rip, i + 1, &[0xAE, modrm], &[0x1F, modrm & 0xC7]); + } } } ConsoleOnly::Monitorx => { @@ -1665,6 +1683,100 @@ mod tests { } } + /// A code page of a registered module holding `bytes` at `at`, read-execute. + fn clwb_test_page(name: &str, sites: &[(usize, &[u8])]) -> usize { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE}; + unsafe { + let page = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(page, 0); + std::ptr::write_bytes(page as *mut u8, 0xCC, 0x1000); + for (at, bytes) in sites { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), (page + at) as *mut u8, bytes.len()); + } + let mut old = 0; + assert_ne!(VirtualProtect(page as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old), 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: name.into(), path: name.into(), base: page, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), + no_thread_calls: AtomicBool::new(false), initialized: AtomicBool::new(true), stack_reserve: 0, + })); + page + } + } + + fn drop_clwb_test_page(page: usize) { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + forget_rewritten_waits(page, page + 0x1000); + modules::unregister_mapped(page); + unsafe { VirtualFree(page as *mut _, 0, MEM_RELEASE) }; + } + + /// A CLWB whose first two bytes cross an aligned word cannot take the two-byte jump in one + /// write: it becomes the NOP with the same operand, patched once like every other site. + #[test] + fn clwb_across_an_atomic_word_becomes_a_nop_with_its_operand() { + for (clwb, nop) in [ + (&[0x66u8, 0x0F, 0xAE, 0x30][..], &[0x66u8, 0x0F, 0x1F, 0x00][..]), + (&[0x66, 0x41, 0x0F, 0xAE, 0x74, 0x24, 0x08][..], &[0x66, 0x41, 0x0F, 0x1F, 0x44, 0x24, 0x08][..]), + ] { + let page = clwb_test_page("clwb_across.exe", &[(7, clwb)]); + unsafe { + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + ctx.Rip = (page + 7) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (page + 7 + clwb.len()) as u64, "the patching visit steps over it"); + assert_eq!(std::slice::from_raw_parts((page + 7) as *const u8, clwb.len()), nop); + assert_eq!(std::slice::from_raw_parts(page as *const u8, 7), &[0xCC; 7], "the bytes before it stay"); + assert_eq!(*((page + 7 + clwb.len()) as *const u8), 0xCC, "the byte after it stays"); + // a thread that faulted on the old bytes finds the NOP and is retried there + ctx.Rip = (page + 7) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (page + 7) as u64); + } + drop_clwb_test_page(page); + } + } + + /// Many threads fault at once on a CLWB and on a wait in the same page (#278): both are + /// patched whole, no fault is passed on to the title, and the page is read-execute again. + #[test] + fn clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection() { + use std::sync::{Arc, Barrier}; + use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ}; + let (clwb, wait) = ([0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08], [0x0F, 0x01, 0xFA]); + let page = clwb_test_page("clwb_and_wait.exe", &[(0x40, &clwb), (0x48, &wait)]); + const THREADS: usize = 32; + let start = Arc::new(Barrier::new(THREADS + 1)); + let workers: Vec<_> = (0..THREADS).map(|n| { + let start = start.clone(); + std::thread::spawn(move || unsafe { + let mut ctx: CONTEXT = std::mem::zeroed(); + let (at, len) = if n & 1 == 0 { (page + 0x40, clwb.len()) } else { (page + 0x48, wait.len()) }; + ctx.Rip = at as u64; + start.wait(); + let handled = emulate_console_only(&mut ctx); + // stepped over by the thread that patched it, retried at the same address by one + // that faulted on the old bytes + (handled, ctx.Rip as usize == at + len || ctx.Rip as usize == at) + }) + }).collect(); + start.wait(); + for worker in workers { + assert_eq!(worker.join().unwrap(), (-1, true)); + } + unsafe { + let code = std::slice::from_raw_parts((page + 0x40) as *const u8, 12); + assert_eq!(code[..clwb.len()], [0xEB, 4, 0xAE, 0x74, 0x24, 0x08]); + assert_eq!(code[8..11], [0x90; 3]); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(page as *const _, &mut m, std::mem::size_of_val(&m)), 0); + assert_eq!(m.Protect, PAGE_EXECUTE_READ, "a concurrent patch must not leave the page writable"); + } + drop_clwb_test_page(page); + } + #[test] fn clwb_single_step_keeps_code_and_normal_faults_still_patch() { use std::sync::{atomic::AtomicBool, Arc}; @@ -1676,6 +1788,7 @@ mod tests { struct Code(usize); impl Drop for Code { fn drop(&mut self) { + forget_rewritten_waits(self.0, self.0 + 0x1000); modules::unregister_mapped(self.0); unsafe { VirtualFree(self.0 as *mut _, 0, MEM_RELEASE); } } @@ -1712,8 +1825,12 @@ mod tests { if flags & 0x100 != 0 { assert_eq!(actual, original, "TF must not replace one CLWB with several instructions on a later visit"); } else { - assert!(actual[..instruction.len()].iter().all(|&b| b == 0x90), "retain normal hot-patching"); - assert_eq!(actual[instruction.len()..], original[instruction.len()..]); + assert_eq!(actual[..2], [0xEB, (instruction.len() - 2) as u8], "a short jump over the instruction"); + assert_eq!(actual[2..], original[2..], "the bytes after the jump stay"); + // a thread that faulted on the old bytes arrives after the patch: retried + ctx.Rip = code.0 as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code.0 as u64, "the stale fault runs the jump"); } let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); assert_ne!(VirtualQuery(code.0 as *const _, &mut m, std::mem::size_of_val(&m)), 0);