diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 65f5a32..3bbb9dd 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1210,11 +1210,15 @@ pub(crate) fn log(frames: f64) { "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" ); - let [copies, blocks, opened, stores, unknown, full, stayed, copied_same] = - [0, 1, 2, 3, 4, 5, 6, 7].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "waits for the write trackers' locks per frame, all threads (number, time): {}", + crate::watch::lock_waits(frames as f64) + ); + let [copies, blocks, opened, stores, unknown, full, stayed, copied_same, records] = + [0, 1, 2, 3, 4, 5, 6, 7, 8].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( "the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \ - {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \ + {stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies, {records} copies of descriptors; \ the busiest stores (left out/changed): {}", crate::titlewrite::busiest() ); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 47f9852..a6e74ce 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -301,6 +301,9 @@ pub(crate) fn sync_heaps() { } let started = std::time::Instant::now(); let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64); + let (mut views, mut bytes) = (0u64, 0u64); + let mut spent = [0u64; 4]; + let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); let mut wait: Vec = Vec::new(); @@ -336,7 +339,10 @@ pub(crate) fn sync_heaps() { mirrored += before.len() as u64 - of_tables; // Those of the changed pages, made together at the end. let mut make: Vec = Vec::new(); - for (range_from, range_end) in written.take(start as usize, end as usize) { + let began = std::time::Instant::now(); + let taken = written.take(start as usize, end as usize); + spent[0] += since(began); + for (range_from, range_end) in taken { let mut page = range_from & !(crate::watch::PAGE - 1); while page < range_end { let from = page.max(range_from); @@ -345,8 +351,13 @@ pub(crate) fn sync_heaps() { // copy: a page the title unmaps meanwhile fails the read // where 2,048 reads in place would fault. page_bytes.resize(to - from, 0); - if crate::host::read_into(from as *const u8, &mut page_bytes) { + let began = std::time::Instant::now(); + let there = crate::host::read_into(from as *const u8, &mut page_bytes); + spent[1] += since(began); + if there { pages += 1; + views += u64::from(crate::watch::guarded(from, to)); + bytes += (to - from) as u64; let slots = changed_slots(from, to, start as usize, step, mirrored_count); // A record that straddles the range's ends is left // to the range that holds its first byte. @@ -360,7 +371,9 @@ pub(crate) fn sync_heaps() { // Only the records that are not the ones last seen // there (`HostHeap::copied_changes`). changed.clear(); + let began = std::time::Instant::now(); host.copied_changes(first as u32, &records[..(count * step) as usize], step as usize, &mut changed); + spent[2] += since(began); for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -393,11 +406,13 @@ pub(crate) fn sync_heaps() { page += crate::watch::PAGE; } } + let began = std::time::Instant::now(); crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| { for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() { host.mirror(index, start + u64::from(index) * step, false); } }); + spent[3] += since(began); if !wait.is_empty() { host.copied_wait(frame, std::mem::take(&mut wait)); } @@ -407,6 +422,10 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) { count.fetch_add(n, Relaxed); } + let [taking, reading, comparing, making] = spent; + for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, comparing, making]) { + count.fetch_add(n, Relaxed); + } } /// Records [`sync_heaps`] gives a thread at a time. @@ -422,6 +441,12 @@ const SYNC_AT_A_TIME: usize = 256; #[cfg(windows)] pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; +/// The same, of [`SYNCED`]'s pages: those in view memory that was guarded; +/// bytes read; nanoseconds asking what was written, reading it, comparing it +/// with what was last seen, making views. +#[cfg(windows)] +static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] @@ -436,20 +461,27 @@ pub(crate) fn sync_line(frames: f64) { ); } let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let split = [0, 1, 2, 3, 4, 5].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); if pages == 0 { return; } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ - draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)", + draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, tabled as f64 / frames, later as f64 / frames, micros as f64 / 1000.0 / frames, - waited as f64 / 1000.0 / frames + waited as f64 / 1000.0 / frames, + split[0] / frames, + split[1] / (1 << 20) as f64 / frames, + split[2] / 1e6 / frames, + split[3] / 1e6 / frames, + split[4] / 1e6 / frames, + split[5] / 1e6 / frames ); } @@ -1249,7 +1281,15 @@ pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u6 let len = u64::from(count) * step; if dst != 0 && src != 0 { // SAFETY: both ranges are descriptor slots the title owns. - unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + unsafe { + crate::titlewrite::put(dst as *mut u8, src as *const u8, len as usize) + }; + // SAFETY: as above. + #[cfg(not(windows))] + unsafe { + std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) + }; #[cfg(windows)] for i in 0..u64::from(count) { mirror(dst + i * step); diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs index 1a551c5..946fa88 100644 --- a/crates/victory-gpu/src/titlewrite.rs +++ b/crates/victory-gpu/src/titlewrite.rs @@ -33,8 +33,8 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; /// the guards, blocks they did so in, blocks they opened instead; stores done /// beside the guards, faulting stores not understood, and blocks opened /// because too many came; stores and parts of copies that left the memory as -/// it was, and were not made. -pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// it was, and were not made; descriptors copied onto themselves. +pub(crate) static DONE: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9]; fn add(what: usize) { DONE[what].fetch_add(1, Relaxed); @@ -172,6 +172,28 @@ unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u to } +/// Bytes of the title's that we put into its memory for it (a descriptor it +/// has copied): as a copy of its own, but what is there already is never +/// written (`VICTORY_SAME_RECORDS=0`: always). +/// +/// # Safety +/// `[from, from + n)` and `[to, to + n)` are the title's. +pub(crate) unsafe fn put(to: *mut u8, from: *const u8, n: usize) { + // SAFETY: by the caller. + unsafe { + let there = || std::slice::from_raw_parts(to.cast_const(), n) == std::slice::from_raw_parts(from, n); + if crate::toggled!("VICTORY_SAME_RECORDS") && there() { + add(8); + return; + } + if n == 0 || !copies_on() || !crate::watch::guards_any(to as usize, n) || overlap(to as usize, from as usize, n) { + std::ptr::copy(from, to, n); + return; + } + in_pieces(to as usize, n, |_, _, _| false, |at, offset, len| std::ptr::copy_nonoverlapping(from.add(offset), at as *mut u8, len)); + } +} + /// Whether the two ranges meet, if only in a block (of which only one might /// be written at another address). fn overlap(to: usize, from: usize, n: usize) -> bool { @@ -257,9 +279,9 @@ fn learn(rip: usize, same: bool, can_look: bool) { return; }; use std::io::Write; - let line = format!("{image} {offset:x} or\n"); + let line = format!("{image} {offset:x}\n"); let known = std::fs::read_to_string(&file).unwrap_or_default(); - if known.lines().any(|l| l == line.trim_end()) { + if known.lines().any(|l| l.starts_with(line.trim_end())) { return; } if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) { diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs index e83f5b6..11343c9 100644 --- a/crates/victory-gpu/src/titlewrite/decode.rs +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -1,7 +1,7 @@ //! The stores of x86-64 code that [`super::store`] does in the title's place: //! moves from a register or a constant, arithmetic of those with memory -//! (locked or not), exchanges, and the 4, 8 and 16 byte stores of the vector -//! registers. Everything else is `None`. +//! (locked or not), exchanges, and the 4, 8, 16 and 32 byte stores of the +//! vector registers. Everything else is `None`. use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering::SeqCst}; use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; @@ -18,7 +18,7 @@ enum Alu { #[derive(Clone, Copy, PartialEq, Debug)] enum Op { /// These bytes (the low `size` of them). - Put([u8; 16]), + Put([u8; 32]), /// With a value; `keeps` carry (`inc`, `dec`). Alu { alu: Alu, with: u64, keeps: bool }, /// With a register, which gets what was there. @@ -116,6 +116,27 @@ fn mask(size: usize) -> u64 { if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 } } +/// The upper half of vector register `reg`, where the context has it; nothing +/// in it if the thread used none. +fn upper(c: &CONTEXT, reg: usize) -> Option<[u8; 16]> { + use windows_sys::Win32::System::Diagnostics::Debug::{GetXStateFeaturesMask, LocateXStateFeature}; + const AVX: u32 = 2; + let mut mask = 0; + // SAFETY: a context as the system passes it to a handler (the calls + // change nothing of it). + unsafe { + if GetXStateFeaturesMask(c, &mut mask) == 0 { + return None; + } + if mask >> AVX & 1 == 0 { + return Some([0; 16]); + } + let mut len = 0; + let at = LocateXStateFeature(c, AVX, &mut len) as *const [u8; 16]; + (!at.is_null() && len as usize >= 16 * 16).then(|| at.add(reg).read_unaligned()) + } +} + /// The store at the start of `code`, which the registers are those of. pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { let mut at = 0; @@ -124,7 +145,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { at += 1; byte }; - let (mut locked, mut narrow, mut repeat) = (false, false, 0u8); + let (mut locked, mut narrow, mut repeat, mut long) = (false, false, 0u8, false); let mut byte = next()?; loop { match byte { @@ -160,10 +181,10 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { _ => None, }; if let Some(b) = vector { - // (No 32 byte ones: they fill memory.) - if b & 4 != 0 || narrow || repeat != 0 || locked { + if narrow || repeat != 0 || locked { return None; } + long = b & 4 != 0; // (A store has no third register.) if b >> 3 & 15 != 15 { return None; @@ -223,7 +244,7 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 4 }; let put = |value: u64| { - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&value.to_le_bytes()); Op::Put(bytes) }; @@ -231,9 +252,9 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { let vector_bytes = || { // SAFETY: the registers, whichever way they are named. let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg]; - let mut bytes = [0; 16]; + let mut bytes = [0; 32]; bytes[..8].copy_from_slice(&x.Low.to_le_bytes()); - bytes[8..].copy_from_slice(&x.High.to_le_bytes()); + bytes[8..16].copy_from_slice(&x.High.to_le_bytes()); bytes }; let alu_of = |kind: u8| match kind { @@ -244,14 +265,21 @@ pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option { 6 => Some(Alu::Xor), _ => None, }; - let (op, size) = if two { + let (op, size) = if long { + if !matches!((byte, narrow, repeat), (0x11 | 0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0)) { + return None; + } + let mut bytes = vector_bytes(); + bytes[16..].copy_from_slice(&upper(c, reg)?); + (Op::Put(bytes), 32) + } else if two { match (byte, narrow, repeat) { (0x11, _, 0) | (0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0) => (Op::Put(vector_bytes()), 16), (0x11, false, 0xf3) => (Op::Put(vector_bytes()), 4), (0x11, false, 0xf2) | (0x13, _, 0) | (0xd6, true, 0) => (Op::Put(vector_bytes()), 8), (0x17, _, 0) => { let mut bytes = vector_bytes(); - bytes.copy_within(8.., 0); + bytes.copy_within(8..16, 0); (Op::Put(bytes), 8) } (0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }), @@ -393,7 +421,7 @@ impl Store { return None; } let mut there = [0u8; 32]; - // SAFETY: by the caller. + // SAFETY: by the caller (32 bytes at the most). unsafe { std::ptr::copy_nonoverlapping(self.at as *const u8, there.as_mut_ptr(), self.size) }; match self.op { Op::Put(bytes) => Some((there[..self.size] == bytes[..self.size], c.EFlags)), @@ -406,12 +434,18 @@ impl Store { } } - /// Whether the loader can make it look before it writes - /// (`victory_loader::write_sites`): an `or` of a byte with a constant, of - /// the five bytes a jump needs. + /// Whether the loader may make it look before it writes + /// (`victory_loader::write_sites`, which looks itself): an `or` of a byte + /// with a constant, a move of 4 bytes or more; of the five bytes a jump + /// needs. pub(super) fn can_look(&self, code: &[u8]) -> bool { let at = usize::from(code[0] & 0xf0 == 0x40); - self.len >= 5 && code[at] == 0x80 && matches!(self.op, Op::Alu { alu: Alu::Or, .. }) + self.len >= 5 + && match self.op { + Op::Alu { alu: Alu::Or, .. } => code[at] == 0x80, + Op::Put(_) => matches!(code[0], 0xc4 | 0xc5) && self.size >= 16 || matches!(code[at], 0x89 | 0xc7), + _ => false, + } } /// Does it, with `to` for the address, and gives the registers what the @@ -428,7 +462,7 @@ impl Store { // As one, for those the processor stores as one. // SAFETY (all): by the caller, aligned where it must be. unsafe { - let low = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")); + let low = u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]]); match size { 1 => (to as *mut u8).write_volatile(bytes[0]), 2 if to.is_multiple_of(2) => (to as *mut u16).write_volatile(low as u16), @@ -526,9 +560,8 @@ mod tests { assert_eq!(decoded(&[0x0f, 0x13, 0x00]), Some((0, 8, 3))); assert_eq!(decoded(&[0xc5, 0xf9, 0xd6, 0x00]), Some((0, 8, 4))); assert_eq!(decoded(&[0x66, 0x0f, 0x7e, 0x00]), Some((0, 4, 4))); - // Not stores of these: a 32 byte one, a load, a register's, a string - // instruction, a thread's own memory, a compare, adc. - assert_eq!(decoded(&[0xc5, 0xfc, 0x11, 0x04, 0x31]), None); + // Not stores of these: a load, a register's, a string instruction, a + // thread's own memory, a compare, adc. assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None); assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None); assert_eq!(decoded(&[0xf3, 0xa4]), None); diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 62fb034..d08825a 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -151,11 +151,48 @@ static JOURNAL: RwLock = RwLock::new(Journal { }); fn journal() -> std::sync::RwLockReadGuard<'static, Journal> { - JOURNAL.read().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_read() { + return j; + } + waited(1, || JOURNAL.read().unwrap_or_else(|e| e.into_inner())) } fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> { - JOURNAL.write().unwrap_or_else(|e| e.into_inner()) + if let Ok(j) = JOURNAL.try_write() { + return j; + } + waited(2, || JOURNAL.write().unwrap_or_else(|e| e.into_inner())) +} + +/// Since the last line: waits and nanoseconds of waiting, of all threads, for +/// the ranges held ([`ASKING`]), the journal to read it, the journal to note +/// in it, and the guards (faults of the title's among them). +#[cfg(feature = "diagnostics")] +static WAITS: [[std::sync::atomic::AtomicU64; 2]; 4] = [const { [const { std::sync::atomic::AtomicU64::new(0) }; 2] }; 4]; + +#[cfg(feature = "diagnostics")] +fn waited(what: usize, f: impl FnOnce() -> T) -> T { + use std::sync::atomic::Ordering::Relaxed; + let began = std::time::Instant::now(); + let got = f(); + WAITS[what][0].fetch_add(1, Relaxed); + WAITS[what][1].fetch_add(began.elapsed().as_nanos() as u64, Relaxed); + got +} + +#[cfg(not(feature = "diagnostics"))] +fn waited(_: usize, f: impl FnOnce() -> T) -> T { + f() +} + +/// [`WAITS`], taken, for the log: per frame. +#[cfg(feature = "diagnostics")] +pub(crate) fn lock_waits(frames: f64) -> String { + let of = |what: usize| { + let [n, ns] = [0, 1].map(|i| WAITS[what][i].swap(0, std::sync::atomic::Ordering::Relaxed)); + format!("{:.0} {:.2} ms", n as f64 / frames, ns as f64 / 1e6 / frames) + }; + format!("ranges held {}, journal read {}, journal noted in {}, guards {}", of(0), of(1), of(2), of(3)) } /// The page ranges some thread is asking about: asking forgets what it @@ -170,8 +207,14 @@ struct Asking(usize, usize); impl Asking { fn hold(first: usize, last: usize) -> Asking { let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); - while held.iter().any(|&(a, b)| a < last && first < b) { - held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + if held.iter().any(|&(a, b)| a < last && first < b) { + held = waited(0, || { + let mut held = held; + while held.iter().any(|&(a, b)| a < last && first < b) { + held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + } + held + }); } held.push((first, last)); Asking(first, last) @@ -725,13 +768,10 @@ impl Tracked { return Vec::new(); }; let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); - let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut new: Vec<(usize, u64)> = Vec::new(); for (page, write) in pages { - if seen.get(&page).is_some_and(|&last| last >= write) { - continue; - } - let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); - if start >= end { + let last = seen.get(&page).copied(); + if last.is_some_and(|last| last >= write) || (page * PAGE).max(from) >= ((page + 1) * PAGE).min(to) { continue; } // Keep partial pages dirty: the caller has not taken the rest. @@ -740,9 +780,26 @@ impl Tracked { { seen.insert(page, write); } - match ranges.last_mut() { - Some((_, last)) if *last == start => *last = end, - _ => ranges.push((start, end)), + new.push((page, last.unwrap_or(0))); + } + // Of a page taken before, the parts written since, where they are + // known (`VICTORY_TAKE_PARTS=0`: the page). + let parts = if crate::toggled!("VICTORY_TAKE_PARTS") { parts_written(&new) } else { vec![WHOLE; new.len()] }; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (&(page, last), &parts) in new.iter().zip(&parts) { + let mut parts = if last == 0 { WHOLE } else { parts }; + while parts != 0 { + let first = parts.trailing_zeros() as usize; + let past = first + (!(parts >> first)).trailing_zeros() as usize; + parts &= if past >= PARTS { 0 } else { u16::MAX << past }; + let (start, end) = ((page * PAGE + first * KERNEL_PAGE).max(from), (page * PAGE + past.min(PARTS) * KERNEL_PAGE).min(to)); + if start >= end { + continue; + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } } } ranges @@ -1365,7 +1422,10 @@ static GUARDS: Mutex = Mutex::new(Guards { }); fn guards() -> std::sync::MutexGuard<'static, Guards> { - GUARDS.lock().unwrap_or_else(|e| e.into_inner()) + if let Ok(g) = GUARDS.try_lock() { + return g; + } + waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())) } /// The 4 KiB pages of title memory that what shaders wrote was put into, @@ -3553,6 +3613,42 @@ mod tests { crate::title_memory_section_gone(section); } + /// Of a page taken before, what is taken again is the kernel's pages + /// written since; where they are not known, all of it. + #[test] + fn what_is_taken_again_is_what_was_written() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + let write = |at: usize| { + // SAFETY: committed pages of ours. + unsafe { ((p + at) as *mut u8).write_volatile(1) } + }; + let tracked = track(p, 4 * PAGE, false).expect("watched"); + write(5); + write(PAGE + 5000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p, p + 2 * PAGE)], "never taken"); + assert!(tracked.take(p, p + 4 * PAGE).is_empty()); + write(PAGE + 5000); + write(PAGE + 8192); + write(PAGE + 65535); + write(2 * PAGE); + assert_eq!( + tracked.take(p, p + 4 * PAGE), + [(p + PAGE + 4096, p + PAGE + 3 * 4096), (p + 2 * PAGE - 4096, p + 3 * PAGE)], + "page 2 was never taken" + ); + write(2 * PAGE + 70); + // Two askings' writes are in what is taken after both. + assert!(writes(p, p + 4 * PAGE, false).is_some()); + write(2 * PAGE + 9000); + assert_eq!(tracked.take(p, p + 4 * PAGE), [(p + 2 * PAGE, p + 2 * PAGE + 4096), (p + 2 * PAGE + 8192, p + 2 * PAGE + 12288)]); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + /// The set of blocks against another of the same. #[test] fn blocks_are_a_set() { diff --git a/crates/victory-loader/src/write_sites.rs b/crates/victory-loader/src/write_sites.rs index 11f2d97..f1167e3 100644 --- a/crates/victory-loader/src/write_sites.rs +++ b/crates/victory-loader/src/write_sites.rs @@ -1,5 +1,6 @@ -//! Places in the title's code that set a bit of a byte which is nearly always set already, changed -//! at load to look first (`VICTORY_WRITE_SITES=`; off without it). +//! Places in the title's code that write what is nearly always there already, changed at load to +//! look first (`VICTORY_WRITE_SITES=`; off without it): flags that are set, registers and +//! constants moved to memory, 16 and 32 bytes of the vector registers. //! //! The title's threads raise flags in their objects at every use ("drawn this frame"): `or byte //! [object+n], bit`. The objects lie in memory that copies for the card are kept of, and each such @@ -52,8 +53,141 @@ fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> { Some((end + 1, rex, modrm, &code[rest..end], constant)) } +/// How many bytes behind a ModRM byte name an address, `None` for a register, for the instruction +/// pointer's neighbourhood, the stack (whose pointer is another in our code) and a plain address. +/// `b`: the prefix's bit for the base. +fn address(code: &[u8], modrm: u8, b: bool) -> Option { + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || mode == 0 && rm == 5 { + return None; + } + let mut len = 0; + if rm == 4 { + let sib = *code.first()?; + if sib & 7 == 4 && !b || sib & 7 == 5 && mode == 0 { + return None; + } + len = 1; + } + len += match mode { + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + +/// The end of a stub that has nothing in rcx if the write is left out, and the title's rcx on the +/// stack: the write (`code[..len]`, at `at`) or not, and back. `wide`: all of rcx counts. +fn write_or_not(out: &mut Vec, stub: usize, code: &[u8], at: usize, len: usize, wide: bool) -> Option<()> { + if !wide { + out.push(0x67); + } + out.extend([0xe3, u8::try_from(1 + len + 5).ok()?]); // jrcxz (jecxz) past the write + out.push(0x59); // pop rcx + out.extend(&code[..len]); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + out.push(0x59); + out.extend(crate::console_insn::jump(stub + out.len(), at + len)?); + Some(()) +} + +/// [`stub`] for a vector register's store. No flag is touched. +fn vector_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let (reg_high, xb, third, op_at) = match *code.first()? { + 0xc5 => { + let b = *code.get(1)?; + (b & 0x80 == 0, 0x60, b, 2) + } + 0xc4 => { + let b = *code.get(1)?; + if b & 0x1f != 1 { + return None; + } + (b & 0x80 == 0, b & 0x60, *code.get(2)?, 3) + } + _ => return None, + }; + let (op, modrm) = (*code.get(op_at)?, *code.get(op_at + 1)?); + if !matches!((op, third & 3), (0x11 | 0x29, 0 | 1) | (0x7f, 1 | 2)) || third >> 3 & 15 != 15 { + return None; + } + let long = third & 4; + if !std::is_x86_feature_detected!("avx2") { + return None; + } + let rest = address(code.get(op_at + 2..)?, modrm, xb & 0x20 == 0)?; + let len = op_at + 2 + rest; + if len < 5 { + return None; + } + let reg = modrm >> 3 & 7 | if reg_high { 8 } else { 0 }; + let spare = if reg == 1 { 2u8 } else { 1 }; + let mut out = vec![0x51]; // push rcx + out.extend([0x48, 0x8d, 0x64, 0x24, 0xe0]); // lea rsp, [rsp-32] + out.extend([0xc5, 0xfe, 0x7f, spare << 3 | 4, 0x24]); // vmovdqu [rsp], spare (32 bytes) + // vpcmpeqb spare, reg, [m] + out.extend([0xc4, 0x80 | xb | 1, (!reg & 15) << 3 | long | 1, 0x74, modrm & 0xc7 | spare << 3]); + out.extend(&code[op_at + 2..len]); + out.extend([0xc5, 0xf9 | long, 0xd7, 0xc8 | spare]); // vpmovmskb ecx, spare + out.extend([0xc5, 0xfe, 0x6f, spare << 3 | 4, 0x24]); // vmovdqu spare, [rsp] + out.extend([0x48, 0x8d, 0x64, 0x24, 0x20]); // lea rsp, [rsp+32] + out.extend([0xf7, 0xd1]); // not ecx + if long == 0 { + out.extend([0x0f, 0xb7, 0xc9]); // movzx ecx, cx + } + write_or_not(&mut out, stub, code, at, len, false)?; + Some((len, out)) +} + +/// [`stub`] for a `mov` of a register or a constant, 4 or 8 bytes. No flag is touched. +fn move_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + let mut at_op = 0; + let mut rex = 0x40; + if code.first()? & 0xf0 == 0x40 { + rex = code[0]; + at_op = 1; + } + let (op, modrm) = (*code.get(at_op)?, *code.get(at_op + 1)?); + let wide = rex & 8 != 0; + let reg = modrm >> 3 & 7 | (rex & 4) << 1; + let rest = address(code.get(at_op + 2..)?, modrm, rex & 1 != 0)?; + let end = at_op + 2 + rest; + let (len, constant) = match op { + 0x89 if reg != 1 && reg != 4 => (end, None), + 0xc7 if reg & 7 == 0 => { + let bytes = code.get(end..end + 4)?.try_into().ok()?; + (end + 4, Some(i32::from_le_bytes(bytes).checked_add(1)?)) + } + _ => return None, + }; + if len < 5 { + return None; + } + let mut out = vec![0x51]; // push rcx + out.extend([rex & 0x4b, 0x8b, modrm & 0xc7 | 1 << 3]); // mov rcx, [m] + out.extend(&code[at_op + 2..end]); + let w = 0x40 | rex & 8; + out.extend([w, 0xf7, 0xd1]); // not rcx + match constant { + Some(next) => { + out.extend([w, 0x8d, 0x89]); // lea rcx, [rcx+constant+1] + out.extend(next.to_le_bytes()); + } + // lea rcx, [rcx+reg+1] + None => out.extend([w | (reg & 8) >> 2, 0x8d, 0x4c, (reg & 7) << 3 | 1, 1]), + } + write_or_not(&mut out, stub, code, at, len, wide)?; + Some((len, out)) +} + /// The code at `stub` for the instruction at `at` (`code` from there). fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { + vector_stub(code, at, stub).or_else(|| move_stub(code, at, stub)).or_else(|| or_stub(code, at, stub)) +} + +/// [`stub`] for the `or` of a byte with a constant. +fn or_stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec)> { let (len, rex, modrm, rest, constant) = or_byte(code)?; if len < 5 { return None; @@ -232,6 +366,94 @@ mod tests { } } + /// Memory a vector store may ask to lie on its boundary. + #[repr(C, align(64))] + #[derive(Clone, Copy)] + struct Memory([u8; 0x80]); + + /// Moves of registers and constants, and vector stores, in code of a test's: changed, they + /// store what they did, leave registers and flags, and write nothing that is there already. + #[test] + fn changed_moves_and_vector_stores_do_what_they_did() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualProtect, + }; + // Each stores at r9+40h (r10 is 0): rdx, r13 or a vector register 0, 1, 9. + let stores: &[(&[u8], usize)] = &[ + (&[0x49, 0x89, 0x51, 0x40], 0), // (four bytes: left alone) + (&[0x4b, 0x89, 0x54, 0xd1, 0x40], 8), // mov [r9+r10*8+40h], rdx + (&[0x43, 0x89, 0x54, 0xd1, 0x40], 4), // mov [r9+r10*8+40h], edx + (&[0x4d, 0x89, 0xa9, 0x40, 0, 0, 0], 8), // mov [r9+40h], r13 + (&[0x45, 0x89, 0xa9, 0x40, 0, 0, 0], 4), // mov [r9+40h], r13d + (&[0x41, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 4), // mov dword [r9+40h], 92345678h + (&[0x49, 0xc7, 0x41, 0x40, 0x78, 0x56, 0x34, 0x92], 8), // mov qword [r9+40h], the same + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x41, 0x40], 16), // vmovdqu [r9+40h], xmm0 + (&[0xc4, 0xc1, 0x7a, 0x7f, 0x49, 0x40], 16), // vmovdqu [r9+40h], xmm1 + (&[0xc4, 0x41, 0x78, 0x29, 0x49, 0x40], 16), // vmovaps [r9+40h], xmm9 + (&[0xc4, 0x81, 0x78, 0x11, 0x44, 0xd1, 0x40], 16), // vmovups [r9+r10*8+40h], xmm0 + (&[0xc4, 0xc1, 0x7c, 0x11, 0x41, 0x40], 32), // vmovups [r9+40h], ymm0 + (&[0xc4, 0xc1, 0x7e, 0x7f, 0x49, 0x40], 32), // vmovdqu [r9+40h], ymm1 + ]; + type F = unsafe extern "system" fn(*mut u8, u64, *mut u8); + for &(store, size) in stores { + let mut code = vec![0x41, 0x55, 0x49, 0x89, 0xc9, 0x4d, 0x31, 0xd2, 0x49, 0x89, 0xd5]; // push r13 ; r9 = rcx ; r10 = 0 ; r13 = rdx + code.extend([0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0]); // mov rcx, 1234h + code.extend([0x48, 0x83, 0xec, 0x40, 0xc5, 0x7a, 0x7f, 0x0c, 0x24]); // sub rsp, 40h ; xmm9 kept + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x00]); // vmovdqu ymm0, [r8] + code.extend([0xc4, 0xc1, 0x7e, 0x6f, 0x48, 0x20]); // vmovdqu ymm1, [r8+32] + code.extend([0xc4, 0x41, 0x7a, 0x6f, 0x48, 0x10]); // vmovdqu xmm9, [r8+16] + code.extend([0x48, 0x39, 0xc0]); // cmp rax, rax + let at = code.len(); + code.extend(store); + code.extend([0x9c, 0x41, 0x5b]); // pushfq ; pop r11 + code.extend([0xc5, 0xfe, 0x7f, 0x4c, 0x24, 0x10]); // vmovdqu [rsp+10h], ymm1 + code.extend([0x48, 0x8b, 0x44, 0x24, 0x18, 0x48, 0x03, 0x44, 0x24, 0x28]); // rax = two of its parts + code.extend([0xc5, 0x7a, 0x6f, 0x0c, 0x24, 0x48, 0x83, 0xc4, 0x40, 0x41, 0x5d]); // xmm9 back ; rsp ; pop r13 + // Flags, rcx and rax behind the source ; vzeroupper ; ret + code.extend([0x4d, 0x89, 0x58, 0x40, 0x49, 0x89, 0x48, 0x48, 0x49, 0x89, 0x40, 0x50, 0xc5, 0xf8, 0x77, 0xc3]); + // SAFETY: fresh memory for code, twice, one of them changed before it runs; data of ours. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(place, 0); + let second = place + 0x2000; + std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len()); + assert_eq!(apply("t.dll", second, 0x2000, &format!("t.dll {at:x}")), usize::from(size != 0), "{store:x?}"); + if size == 0 { + continue; + } + let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + for seed in 0..200u64 { + let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); + let mut source = [[0u8; 0x60]; 2]; + for (k, byte) in source[0][..0x40].iter_mut().enumerate() { + *byte = (value >> (k % 8 * 8)) as u8 ^ k as u8; + } + source[1] = source[0]; + let was = Memory(std::array::from_fn(|k| (seed as usize * 7 + k) as u8)); + let mut memory = [was; 2]; + plain(memory[0].0.as_mut_ptr(), value, source[0].as_mut_ptr()); + changed(memory[1].0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(memory[0].0 == memory[1].0, "{store:x?}"); + assert!(memory[0].0[..0x40] == was.0[..0x40] && memory[0].0[0x40 + size..] == was.0[0x40 + size..]); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags"); + // One bit different; and nothing different, in read-only memory. + let mut off = memory[0]; + off.0[0x40 + seed as usize % size] ^= 1 << (seed % 8); + changed(off.0.as_mut_ptr(), value, source[1].as_mut_ptr()); + assert!(off.0 == memory[0].0, "{store:x?}"); + std::ptr::copy_nonoverlapping(memory[0].0.as_ptr(), data, 0x80); + let mut old = 0; + VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old); + changed(data, value, source[1].as_mut_ptr()); + assert_eq!(source[0], source[1], "{store:x?}: registers and flags, nothing written"); + VirtualProtect(data.cast(), 4096, PAGE_READWRITE, &mut old); + } + } + } + } + /// A byte that would not change is not written. #[test] fn a_byte_that_stays_is_not_written() {