diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index fca299989..191d7d1c7 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -257,6 +257,10 @@ fn is_writable(va: usize, bytes: usize) -> bool { const ILLEGAL_INSTRUCTION: u32 = 0xC000_001D; +/// The most lines (64 bytes each, 256 MiB) a `ClzeroLoop` fault zeroes: a longer loop goes on +/// from its clzero at the next fault. +const CLZERO_LOOP_LINES: u64 = (256 << 20) / 64; + /// The first 16 code bytes at `rip`, as hex (as far as they are readable). unsafe fn code_at(rip: usize) -> String { let n = (1..=16).rev().find(|&n| crate::gpu::shader::readable(rip, n)).unwrap_or(0); @@ -320,17 +324,24 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics &ctx.Rax, &ctx.Rcx, &ctx.Rdx, &ctx.Rbx, &ctx.Rsp, &ctx.Rbp, &ctx.Rsi, &ctx.Rdi, &ctx.R8, &ctx.R9, &ctx.R10, &ctx.R11, &ctx.R12, &ctx.R13, &ctx.R14, &ctx.R15, ]; - let end = *regs[end_reg as usize & 15] as usize; - let start = ctx.Rax as usize; - if end > start && (end - start) < 2 * 1024 * 1024 * 1024 { - let bytes = end - start; - if is_writable(start, bytes) { - std::ptr::write_bytes(start as *mut u8, 0, bytes); - } else { + let end = *regs[end_reg as usize & 15]; + let Some(mut run) = crate::insn::clzero_loop(ctx.Rax, end, CLZERO_LOOP_LINES) else { + return 0; // rAX wraps: the real loop faults + }; + if !is_writable(run.line as usize, (run.lines * 64) as usize) { + // not one writable region: a line a fault, so the loop stops at the line the CPU + // would fault on + run = crate::insn::clzero_loop(ctx.Rax, end, 1).expect("one line fits where more did"); + if !is_writable(run.line as usize, 64) { return 0; } } - ctx.Rax = end as u64; + std::ptr::write_bytes(run.line as *mut u8, 0, (run.lines * 64) as usize); + ctx.Rax = run.rax; + ctx.EFlags = (ctx.EFlags & !crate::insn::ARITH_FLAGS) | run.flags; + if !run.done { + return -1; // the jb is taken: back at the clzero, which faults again and goes on + } } ConsoleOnly::Rdpru => { let mut v = 0i64; @@ -971,4 +982,68 @@ mod tests { } modules::unregister_mapped(code); } + + /// The CLZERO loop (#278): whole lines from the one rAX is in, rAX advanced by whole lines, + /// one line when the end is at or below rAX, the cmp's flags, and a span over two regions + /// zeroed a line a fault, back at the clzero until the loop ends. + #[test] + fn clzero_loop_zeroes_whole_lines_as_the_cpu() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; + let code = unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize }; + // two pages, two regions (different protections, both writable) + let buf = unsafe { VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize }; + assert!(code != 0 && buf != 0); + unsafe { + assert_ne!(VirtualAlloc(buf as *const _, 0x1000, MEM_COMMIT, PAGE_READWRITE) as usize, 0); + assert_ne!(VirtualAlloc((buf + 0x1000) as *const _, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize, 0); + } + modules::register_mapped(Arc::new(modules::MappedModule { + name: "clzero_loop.exe".into(), path: "clzero_loop.exe".into(), base: code, 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, + })); + // clzero; add rax, 0x40; cmp rax, rdx; jb back + let bytes = [0x0Fu8, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]; + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), code as *mut u8, bytes.len()) }; + let run = |rax: usize, rdx: usize| unsafe { + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x2000); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, rax as u64, rdx as u64, 0x202 | crate::insn::ARITH_FLAGS); + let mut faults = 0; + while ctx.Rip == code as u64 { + assert_eq!(emulate_console_only(&mut ctx), -1); + faults += 1; + assert!(faults <= 0x2000 / 64, "the loop ends"); + } + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.EFlags, 0x202 | crate::insn::cmp_flags(ctx.Rax, rdx as u64), "the last cmp's flags"); + let zeroed: Vec = (0..0x2000).filter(|&i| *((buf + i) as *const u8) == 0).collect(); + let span = zeroed.first().map_or(0..0, |&a| a..zeroed.last().unwrap() + 1); + assert_eq!(zeroed.len(), span.len(), "one span"); + (span, ctx.Rax as usize - buf, faults) + }; + // unaligned start and an end in the middle of a line: whole lines, rAX keeps its offset + assert_eq!(run(buf + 0x110, buf + 0x1C1), (0x100..0x1C0, 0x1D0, 1)); + // end at or below rAX: one line, rAX one line on + assert_eq!(run(buf + 0x200, buf + 0x200), (0x200..0x240, 0x240, 1)); + assert_eq!(run(buf + 0x220, buf), (0x200..0x240, 0x260, 1)); + // across the two regions: a line a fault until the rest is in one region (0xF80, 0xFC0, + // then 0x1000..0x1080 at once) + assert_eq!(run(buf + 0xF80, buf + 0x1080), (0xF80..0x1080, 0x1080, 3)); + // into memory that is not there: what was zeroed stays, and the fault is the title's + unsafe { + VirtualFree((buf + 0x1000) as *mut _, 0x1000, windows_sys::Win32::System::Memory::MEM_DECOMMIT); + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x1000); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx) = (code as u64, (buf + 0xFC0) as u64, (buf + 0x1080) as u64); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!((ctx.Rip, ctx.Rax), (code as u64, (buf + 0x1000) as u64)); + assert_eq!(emulate_console_only(&mut ctx), 0); + assert!((0xFC0..0x1000).all(|i| *((buf + i) as *const u8) == 0)); + VirtualFree(buf as *mut _, 0, MEM_RELEASE); + } + modules::unregister_mapped(code); + unsafe { VirtualFree(code as *mut _, 0, MEM_RELEASE) }; + } } diff --git a/crates/xcl/src/insn.rs b/crates/xcl/src/insn.rs index 5b8488e08..520d77b0e 100644 --- a/crates/xcl/src/insn.rs +++ b/crates/xcl/src/insn.rs @@ -11,7 +11,8 @@ pub enum ConsoleOnly { Clwb, /// `clzero`: zero the 64-byte cache line at rAX Clzero, - /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero `[rax..reg)` + /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero the lines from rAX + /// on until rAX reaches the register (`clzero_loop`; `end_reg` is never rax) ClzeroLoop { end_reg: u8 }, /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) Rdpru, @@ -61,6 +62,47 @@ pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) } +/// The arithmetic flags in EFLAGS: CF, PF, AF, ZF, SF and OF. +pub const ARITH_FLAGS: u32 = 0x8D5; + +/// The arithmetic flags `cmp a, b` (64-bit) leaves. +pub fn cmp_flags(a: u64, b: u64) -> u32 { + let r = a.wrapping_sub(b); + let cf = (a < b) as u32; + let pf = (r as u8).count_ones() % 2 == 0; + let af = (a ^ b ^ r) & 0x10 != 0; + let zf = r == 0; + let sf = r >> 63 != 0; + let of = ((a ^ b) & (a ^ r)) >> 63 != 0; + cf | (pf as u32) << 2 | (af as u32) << 4 | (zf as u32) << 6 | (sf as u32) << 7 | (of as u32) << 11 +} + +/// What the `ClzeroLoop` emulation does on one fault: zero `lines` 64-byte lines from `line`, +/// leave rAX and the flags as the last `add` / `cmp` did and, when the loop is not `done`, stay +/// at the clzero (the next fault goes on from there). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ClzeroRun { + pub line: u64, + pub lines: u64, + pub rax: u64, + pub flags: u32, + pub done: bool, +} + +/// The `clzero; add rax, 0x40; cmp rax, end; jb` loop from `rax`, at most `max_lines` (at least +/// one) of its iterations. As the CPU runs it: the body runs at least once (an `end` at or below +/// rAX zeroes one line), each clzero zeroes the line rAX is in (an unaligned rAX zeroes the line +/// below it; rAX moves by whole lines), and the loop ends at the first rAX not below `end` +/// (unsigned). None when rAX would wrap past the top of the address space, where the real loop +/// faults anyway. +pub fn clzero_loop(rax: u64, end: u64, max_lines: u64) -> Option { + let after_one = rax.checked_add(64)?; + let total = if end <= after_one { 1 } else { (end - rax).div_ceil(64) }; + let lines = total.min(max_lines.max(1)); + let rax_after = rax.checked_add(lines.checked_mul(64)?)?; + Some(ClzeroRun { line: rax & !63, lines, rax: rax_after, flags: cmp_flags(rax_after, end), done: lines == total }) +} + /// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the /// bytes run out. fn modrm_len(b: &[u8]) -> Option { @@ -116,12 +158,16 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { (0x01, Some(0xFC)) => { // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, ([48|4C] 39 modrm); jb -12 (72 F4) // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the - // prefix – it is stepped alone, the loop is taken from the next one) + // prefix – it is stepped alone, the loop is taken from the next one). The ModRM must be + // mod 3 with rax in r/m – anything else compares another register or memory – and the + // register is not rax itself (`cmp rax, rax` never loops: the clzero is stepped alone). if code.len() >= i + 12 && !code[..i].contains(&0x67) && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) && code[i + 8] == 0x39 + && code[i + 9] & 0xC7 == 0xC0 + && (code[i + 7], code[i + 9]) != (0x48, 0xC0) && code[i + 10..i + 12] == [0x72, 0xF4] { let rex_r = code[i + 7] == 0x4C; @@ -182,6 +228,99 @@ mod tests { } } + /// The loop's tail with `cmp` bytes `rex 39 modrm`. + fn loop_with(rex: u8, modrm: u8) -> [u8; 12] { + [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, rex, 0x39, modrm, 0x72, 0xF4] + } + + /// Only `cmp rax, ` (ModRM mod 3, r/m 0, no REX.B) ends a CLZERO loop (#278). + #[test] + fn clzero_loop_needs_cmp_rax_with_a_register() { + for (reg, modrm) in [(1u8, 0xC8u8), (2, 0xD0), (3, 0xD8), (4, 0xE0), (5, 0xE8), (6, 0xF0), (7, 0xF8)] { + assert_eq!(decode(&loop_with(0x48, modrm)), Some((ConsoleOnly::ClzeroLoop { end_reg: reg }, 12)), "{modrm:02x}"); + assert_eq!(decode(&loop_with(0x4C, modrm)), Some((ConsoleOnly::ClzeroLoop { end_reg: reg + 8 }, 12)), "{modrm:02x}"); + } + assert_eq!(decode(&loop_with(0x4C, 0xC0)), Some((ConsoleOnly::ClzeroLoop { end_reg: 8 }, 12)), "cmp rax, r8"); + // not the loop: the clzero alone + for (rex, modrm, what) in [ + (0x48, 0xC0, "cmp rax, rax: never loops"), + (0x48, 0xD1, "cmp rcx, rdx"), + (0x48, 0xCA, "cmp rdx, rcx"), + (0x48, 0x10, "cmp [rax], rdx"), + (0x48, 0x50, "cmp [rax+disp8], rdx"), + (0x48, 0x90, "cmp [rax+disp32], rdx"), + (0x49, 0xD0, "cmp r8, rdx (REX.B)"), + (0x4D, 0xD0, "cmp r8, r10 (REX.B)"), + ] { + assert_eq!(decode(&loop_with(rex, modrm)), Some((ConsoleOnly::Clzero, 3)), "{what}"); + } + } + + #[test] + fn cmp_flags_match_the_cpu() { + const CF: u32 = 1; + const PF: u32 = 4; + const AF: u32 = 0x10; + const ZF: u32 = 0x40; + const SF: u32 = 0x80; + const OF: u32 = 0x800; + assert_eq!(cmp_flags(5, 5), ZF | PF); + assert_eq!(cmp_flags(0x40, 0x80), CF | SF | PF); // r = 0xFFFF_FFFF_FFFF_FFC0 + assert_eq!(cmp_flags(0x80, 0x40), 0); // r = 0x40: one bit, odd parity + assert_eq!(cmp_flags(0x10, 0x01), AF | PF); // r = 0x0F: four bits, borrow out of bit 3 + assert_eq!(cmp_flags(0x8000_0000_0000_0000, 1), OF | AF | PF); // r = 0x7FFF..FF + assert_eq!(cmp_flags(0, 1), CF | SF | AF | PF); + assert_eq!(cmp_flags(1, 0) & !ARITH_FLAGS, 0); + } + + /// The loop as the CPU runs it (#278): whole lines from rAX's, rAX by whole lines, at least + /// one iteration, and the flags of the last cmp. + #[test] + fn clzero_loop_runs_like_the_cpu() { + /// The loop stepped one iteration at a time, as the CPU does it. + fn reference(mut rax: u64, end: u64) -> (u64, u64, u64, u32) { + let (line, mut lines) = (rax & !63, 0); + loop { + lines += 1; + rax += 64; + if rax >= end { + return (line, lines, rax, cmp_flags(rax, end)); + } + } + } + let full = |rax, end| clzero_loop(rax, end, u64::MAX).unwrap(); + // aligned, and a whole number of lines: [0x1000, 0x1100) + assert_eq!(full(0x1000, 0x1100), ClzeroRun { line: 0x1000, lines: 4, rax: 0x1100, flags: cmp_flags(0x1100, 0x1100), done: true }); + // an unaligned start: the line below it, and rAX keeps its offset + assert_eq!(full(0x1010, 0x1100), ClzeroRun { line: 0x1000, lines: 4, rax: 0x1110, flags: cmp_flags(0x1110, 0x1100), done: true }); + // an end that is not a whole number of lines away: the last line is zeroed whole + assert_eq!(full(0x1000, 0x1081), ClzeroRun { line: 0x1000, lines: 3, rax: 0x10C0, flags: cmp_flags(0x10C0, 0x1081), done: true }); + // end at or below rAX: the body still runs once + for end in [0x1000, 0x0FFF, 0, 0x1040] { + let r = full(0x1000, end); + assert_eq!((r.line, r.lines, r.rax, r.done), (0x1000, 1, 0x1040, true), "end {end:#x}"); + } + // a run cut to max_lines leaves rAX below end (CF set: the jb is taken) and is not done + let r = clzero_loop(0x1000, 0x2000, 16).unwrap(); + assert_eq!((r.line, r.lines, r.rax, r.done), (0x1000, 16, 0x1400, false)); + assert_eq!(r.flags & 1, 1); + let rest = full(r.rax, 0x2000); + assert_eq!((rest.line, rest.lines, rest.rax), (0x1400, 48, 0x2000)); + assert_eq!(clzero_loop(0x1000, 0x2000, 0).unwrap().lines, 1, "at least one line a fault"); + // rAX wrapping past the top of the address space: left to fault + assert_eq!(clzero_loop(u64::MAX - 0x20, 0, u64::MAX), None); + assert_eq!(clzero_loop(u64::MAX - 0x1010, u64::MAX, u64::MAX), None, "the last add wraps"); + assert_eq!(clzero_loop(u64::MAX - 0x1000, u64::MAX, u64::MAX).map(|r| (r.lines, r.rax)), Some((64, u64::MAX)), "it just reaches the top"); + // against the stepped loop + for rax in [0x1_0000u64, 0x1_0001, 0x1_003F, 0x1_0040, 0x1_0077] { + for end in [0u64, 0x1_0000, 0x1_0001, 0x1_0040, 0x1_0041, 0x1_00C0, 0x1_00FF, 0x1_1000, 0x1_1001] { + let r = full(rax, end); + assert_eq!((r.line, r.lines, r.rax, r.flags), reference(rax, end), "rax {rax:#x} end {end:#x}"); + assert!(r.done); + } + } + } + #[test] fn decodes_the_console_only_instructions() { assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3)));