diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 34c214d..5d2a3af 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1210,6 +1210,12 @@ 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] = + [0, 1, 2, 3, 4, 5].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" + ); // Where the wall clock of a frame goes: the phases of a frame, the // processor time of the whole process, and what each submitting and // recording thread did. diff --git a/crates/victory-gpu/src/faultbook.rs b/crates/victory-gpu/src/faultbook.rs new file mode 100644 index 0000000..1b0db43 --- /dev/null +++ b/crates/victory-gpu/src/faultbook.rs @@ -0,0 +1,113 @@ +//! A book of the title's write faults on guarded view memory +//! (`VICTORY_FAULT_BOOK=`; builds with diagnostics): which block, when +//! in the frame, what it waited for, and what else happened to the block +//! (taken by a refresh, asked about), for 40 frames from each of the times +//! `VICTORY_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless +//! given). Written as `..bin`, records of 40 bytes: ticks of the +//! performance counter, two words, thread, what. +#![cfg(feature = "diagnostics")] + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +/// What a record is of. +#[derive(Clone, Copy)] +#[repr(u32)] +pub(crate) enum What { + /// A frame ended (a: its number). + Frame = 0, + /// A write fault opened block `a`; b: blocks opened with it (the upper + /// 32 bits), nanoseconds of waiting for the guards' lock; c: nanoseconds + /// with it. + Fault = 1, + /// Blocks `[a, b)` were found written, or never taken, and made read-only. + Taken = 2, + /// `[a, b)` was asked about and known unwritten by its bits. + Known = 3, + /// `[a, b)` was asked about block by block; c: how many were written. + Asked = 4, + /// We opened block `a` ourselves. + Ours = 5, + /// Another view of a page taken, block `a`, was made read-only. + Alias = 6, + /// A fault on block `a` that someone else had opened; b: nanoseconds. + Open = 7, + /// The instruction at `a` made the fault before (block `b`). + Site = 9, + /// A store (the instruction at `a`) was done beside the guard of block + /// `b`. + Stored = 10, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Record { + at: i64, + a: u64, + b: u64, + c: u64, + thread: u32, + what: u32, +} + +static ON: AtomicBool = AtomicBool::new(false); +static BOOK: Mutex> = Mutex::new(Vec::new()); + +fn ticks() -> i64 { + let mut t = 0; + // SAFETY: an out pointer of the right size. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut t) }; + t +} + +/// Whether records are kept now. +pub(crate) fn on() -> bool { + ON.load(Relaxed) +} + +pub(crate) fn note(what: What, a: usize, b: usize, c: u64) { + if !on() { + return; + } + // SAFETY: a question about this thread. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let record = Record { at: ticks(), a: a as u64, b: b as u64, c, thread, what: what as u32 }; + BOOK.lock().unwrap_or_else(|e| e.into_inner()).push(record); +} + +/// A frame ended. +pub(crate) fn frame() { + const FRAMES: u64 = 40; + static SETTINGS: OnceLock)>> = OnceLock::new(); + static BEGAN: OnceLock = OnceLock::new(); + static LEFT: AtomicU64 = AtomicU64::new(0); + static MADE: AtomicU64 = AtomicU64::new(0); + let began = *BEGAN.get_or_init(std::time::Instant::now); + let Some((file, times)) = SETTINGS.get_or_init(|| { + let file = std::env::var("VICTORY_FAULT_BOOK").ok().filter(|f| !f.is_empty())?; + let times = std::env::var("VICTORY_FAULT_BOOK_AT").unwrap_or_else(|_| "150,210,270".into()); + Some((file, times.split(',').filter_map(|t| t.trim().parse().ok()).collect())) + }) else { + return; + }; + note(What::Frame, crate::frame::current() as usize, 0, 0); + if on() { + if LEFT.fetch_sub(1, Relaxed) > 1 { + return; + } + ON.store(false, Relaxed); + let records = std::mem::take(&mut *BOOK.lock().unwrap_or_else(|e| e.into_inner())); + let file = format!("{file}.{}.bin", MADE.fetch_add(1, Relaxed)); + std::thread::spawn(move || { + // SAFETY: plain data, every byte of it written. + let bytes = unsafe { std::slice::from_raw_parts(records.as_ptr().cast::(), size_of_val(&records[..])) }; + match std::fs::write(&file, bytes) { + Ok(()) => tracing::info!(file, records = records.len(), "book of faults written"), + Err(e) => tracing::warn!(file, %e, "book of faults not written"), + } + }); + } else if times.get(MADE.load(Relaxed) as usize).is_some_and(|&t| began.elapsed().as_secs() >= t) { + LEFT.store(FRAMES, Relaxed); + ON.store(true, Relaxed); + } +} diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 82275c9..28f570e 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -37,7 +37,6 @@ use std::collections::BTreeMap; use std::ffi::c_void; -use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Foundation::HANDLE; @@ -281,7 +280,9 @@ struct Views { whole: Vec<(usize, usize)>, } -static VIEWS: Mutex = Mutex::new(Views { +/// Read by many threads at once (write faults, landings), changed when the +/// runtime maps or unmaps. +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), pages_twice: 0, @@ -289,14 +290,18 @@ static VIEWS: Mutex = Mutex::new(Views { whole: Vec::new(), }); -fn views() -> std::sync::MutexGuard<'static, Views> { - VIEWS.lock().unwrap_or_else(|e| e.into_inner()) +fn views() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) } /// The runtime made a section of `bytes` for physical pages; `committed` /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { - let mut v = views(); + let mut v = views_mut(); v.sections.retain(|s| s.0 != section); // A handle's number given out again: the view was of the section that // had it before (it stays mapped: someone may be writing through it). @@ -308,7 +313,7 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { /// sees is of it any more, and [`beside`]'s view goes. pub fn title_memory_section_gone(section: usize) { let whole = { - let mut v = views(); + let mut v = views_mut(); let at = v.whole.iter().position(|w| w.0 == section); at.map(|i| v.whole.swap_remove(i).1) }; @@ -324,7 +329,7 @@ pub fn title_memory_section_gone(section: usize) { /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { { - let mut v = views(); + let mut v = views_mut(); v.views.insert(at, (len, section, offset)); for k in 0..len.div_ceil(K64) { let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default(); @@ -343,7 +348,7 @@ pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { /// the views that touch it are forgotten (the runtime tells again those it /// maps anew). pub(crate) fn views_gone(at: usize, len: usize) { - let mut v = views(); + let mut v = views_mut(); if v.views.is_empty() { return; } @@ -529,7 +534,17 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { /// `crate::watch::title_memory_reading`: until it lets go the title sees /// the same pages at `at`. pub(crate) fn beside(at: usize, len: usize) -> Option { - let mut v = views(); + let known = { + let v = views(); + let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset)) + }; + if let Some((base, offset)) = known { + return (base != 0).then(|| base + offset as usize); + } + let mut v = views_mut(); let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { return None; }; @@ -550,6 +565,34 @@ pub(crate) fn beside(at: usize, len: usize) -> Option { (base != 0).then(|| base + offset as usize) } +/// Our own address of the 64 KiB page the title sees at `page` ([`beside`]), +/// and every address the title sees it at (0: no more); `None` if the page is +/// in no view of a section, or in very many. While the caller holds +/// `crate::watch::title_memory_reading`. +pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> { + for asked in [false, true] { + { + let v = views(); + let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return None; + } + let offset = offset + within as u64; + if let Some(whole) = v.whole.iter().find(|w| w.0 == section) { + let mut shown = [0; 8]; + let all = v.pages.get(&(section, offset))?; + shown.get_mut(..all.len())?.copy_from_slice(all); + return (whole.1 != 0).then(|| (whole.1 + offset as usize, shown)); + } + } + if asked || beside(page, K64).is_none() { + return None; + } + } + None +} + /// Whether `[at, at + len)` is private memory, all committed and /// read-write: what [`From::Part`] takes. One question to Windows (it /// walks the page tables to the end of the pages that share the first diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d837afc..85ba22b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -22,6 +22,8 @@ mod capture; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; +#[cfg(all(windows, feature = "diagnostics"))] +mod faultbook; #[cfg(windows)] mod cores; pub mod descriptor; @@ -80,6 +82,8 @@ mod tdr; mod texture; pub mod timeline; #[cfg(windows)] +pub mod titlewrite; +#[cfg(windows)] mod upload; #[cfg(windows)] mod watch; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index b4cf177..ede3bb3 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -985,6 +985,7 @@ extern "system" fn present( #[cfg(all(windows, feature = "diagnostics"))] fn frame_ends() { crate::timeline::presented(); + crate::faultbook::frame(); crate::ab::presented(|switch, was, will| { if switch == "VICTORY_ASYNC_SUBMIT" && was && !will { behind::leave(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 671d6d8..ce94da1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3485,7 +3485,8 @@ impl Shadow { fn update_free(&self, from: usize, to: usize) -> usize { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { if let Some((now, written)) = crate::watch::writes(from, to, true) { - let guarded = crate::watch::guarded(from, to); + // (A range whose blocks rest after a write has no guard now.) + let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED; self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); self.refresh_check(from, to); diff --git a/crates/victory-gpu/src/titlewrite.rs b/crates/victory-gpu/src/titlewrite.rs new file mode 100644 index 0000000..08aee3a --- /dev/null +++ b/crates/victory-gpu/src/titlewrite.rs @@ -0,0 +1,290 @@ +//! The title's writes into guarded view memory that do not go through a +//! fault that opens the block (`crate::watch`): its bytes are put in through +//! our own view of the same pages (`crate::inplace`), which no guard covers, +//! and the block is told as written (`crate::watch::put_beside`). The block +//! stays read-only, so neither this write nor the block's next taking changes +//! a protection. +//! +//! A change of protection is some 5 us in the game's process, one at a time +//! whoever asks; a frame had 590 write faults, and made as many blocks +//! read-only again (run faults-1). What faults is, by the time spent in it, +//! for a third the title's `memcpy`, and for most of the rest single stores +//! into objects that lie in memory some buffer's copy covers: a flag, a +//! reference count, the link of a free list. +//! +//! - [`import`]: the title's `memcpy`, `memmove` and `memset` are ours +//! (`VICTORY_COPY_BESIDE=1`; off unless asked for). They look at the bits +//! of the blocks they write and go to the runtime's own, but for the parts +//! that lie in guarded blocks. +//! - [`store`]: a store that faults is done here, and the thread goes on +//! behind it (`VICTORY_STORE_BESIDE=1`; off unless asked for). Nothing of +//! the title's code is known ahead: the instruction is read where it +//! faulted, and one that is not understood opens the block as before. So +//! does a block's fifth store since it was taken, and one at a place in the +//! code most of whose blocks come to that ([`SITES`]): code that fills a +//! block would fault at every store. + +mod decode; + +use crate::watch::Beside; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; + +/// Diagnostics, since the start: copies of the title's that put bytes beside +/// 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. +pub(crate) static DONE: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +fn add(what: usize) { + DONE[what].fetch_add(1, Relaxed); +} + +/// A switch that is off unless its variable is `1` (or `VICTORY_AB` names it: +/// on and off while the title runs). +macro_rules! asked_for { + ($name:literal) => {{ + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = ASKED.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if let Some(bit) = crate::ab::bit($name) { + return Err(bit); + } + Ok(std::env::var_os($name).is_some_and(|v| v == "1")) + }); + match *asked { + Ok(on) => on, + #[cfg(feature = "diagnostics")] + Err(bit) => crate::ab::on(bit), + #[cfg(not(feature = "diagnostics"))] + Err(_) => false, + } + }}; +} + +fn copies_on() -> bool { + #[cfg(test)] + if ON_IN_TEST.get() { + return true; + } + asked_for!("VICTORY_COPY_BESIDE") +} + +fn stores_on() -> bool { + #[cfg(test)] + if ON_IN_TEST.get() { + return true; + } + asked_for!("VICTORY_STORE_BESIDE") +} + +#[cfg(test)] +thread_local! { + /// Both, for this thread's writes. + pub(crate) static ON_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The runtime's own `memcpy`, `memmove` and `memset`. +static REAL: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3]; + +type Copy = unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8; +type Set = unsafe extern "system-unwind" fn(*mut u8, i32, usize) -> *mut u8; + +/// What the title's import of `name`, which the host has at `address`, is +/// bound to. +pub fn import(name: &str, address: usize) -> usize { + let (which, ours) = match name { + "memcpy" => (0, copy as *const () as usize), + "memmove" => (1, shift as *const () as usize), + "memset" => (2, set as *const () as usize), + _ => return address, + }; + #[cfg(feature = "diagnostics")] + let on = crate::ab::bit("VICTORY_COPY_BESIDE").is_some() || copies_on(); + #[cfg(not(feature = "diagnostics"))] + let on = copies_on(); + if !on { + return address; + } + REAL[which].store(address, Relaxed); + ours +} + +#[cfg(test)] +pub(crate) fn copy_for_test(real: usize) -> usize { + REAL[0].store(real, Relaxed); + copy as *const () as usize +} + +/// The most a block takes of copies beside its guard before it is opened; a +/// store counts as [`A_STORE`]. +pub(crate) const MOST: u32 = 32; +const A_STORE: u32 = 8; + +unsafe extern "system-unwind" fn copy(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: the title's copy, as it asked for it, by the function it asked. + unsafe { copied(to, from, n, REAL[0].load(Relaxed)) } +} + +unsafe extern "system-unwind" fn shift(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: as above. + unsafe { copied(to, from, n, REAL[1].load(Relaxed)) } +} + +/// # Safety +/// `real` copies as `memcpy` (or `memmove`) does, `to`, `from` and `n` are +/// the title's. +#[inline] +unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 { + // SAFETY: the host's function, noted by `import` before the title ran. + let real: Copy = unsafe { std::mem::transmute(real) }; + if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() || overlap(to as usize, from as usize, n) { + // SAFETY: by the caller. + return unsafe { real(to, from, n) }; + } + in_pieces(to as usize, n, |at, offset, len| { + // SAFETY: a part of what the title asked for; or the same bytes at + // our view of the pages. + unsafe { real(at as *mut u8, from.add(offset), len) }; + }); + to +} + +unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u8 { + // SAFETY: as in `copied`. + let real: Set = unsafe { std::mem::transmute(REAL[2].load(Relaxed)) }; + if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() { + // SAFETY: the title's, as it asked for it. + return unsafe { real(to, byte, n) }; + } + in_pieces(to as usize, n, |at, _, len| { + // SAFETY: as in `copied`. + unsafe { real(at as *mut u8, byte, len) }; + }); + to +} + +/// 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 { + const BLOCK: usize = crate::watch::PAGE; + let (first, last) = (to / BLOCK * BLOCK, to.saturating_add(n).next_multiple_of(BLOCK)); + from < last && first < from.saturating_add(n) +} + +/// Does `[to, to + n)` block by block: `put(at, offset, len)` with the +/// address to write at, the title's or ours. +fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) { + const BLOCK: usize = crate::watch::PAGE; + add(0); + let mut offset = 0; + while offset < n { + let at = to + offset; + let len = (BLOCK - at % BLOCK).min(n - offset); + if crate::watch::guards_any(at, len) { + match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) { + Beside::Done => { + add(1); + offset += len; + continue; + } + // Opened with no fault: the next copies here are plain ones. + _ => crate::watch::opened_for_writing(at), + } + add(2); + } + put(at, offset, len); + offset += len; + } +} + +/// Places of the title's code whose stores faulted, by a hash of the address: +/// the stores done beside the guards (the low half) and the blocks that had +/// too many of them (the high half). +static SITES: [AtomicU64; 1 << 10] = [const { AtomicU64::new(0) }; 1 << 10]; + +fn site(rip: usize) -> &'static AtomicU64 { + &SITES[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 54 & 1023] +} + +/// Whether a site's stores come one to a block, as far as is known. +fn sparse(counts: u64) -> bool { + let (done, full) = (counts & 0xffff_ffff, counts >> 32); + full < 4 || full * 12 < done +} + +/// Does the store that faulted at `at`, a byte of a guarded block, beside the +/// guards; `false` if it is to open the block (and nothing was done). +pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool { + if !stores_on() { + return false; + } + let rip = context.Rip as usize; + let site = site(rip); + let counts = site.load(Relaxed); + if !sparse(counts) { + // Looked at anew some time. + if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 { + site.store(0, Relaxed); + } + return false; + } + let mut code = [0u8; 15]; + // (To the end of the page if the next is not there.) + let left = 4096 - rip % 4096; + let there = crate::host::read_into(rip as *const u8, &mut code) || { + let n = left.min(15); + n < 15 && crate::host::read_into(rip as *const u8, &mut code[..n]) + }; + let Some(store) = there.then(|| decode::store(&code, context)).flatten() else { + add(4); + return false; + }; + const BLOCK: usize = crate::watch::PAGE; + let end = store.at.wrapping_add(store.size); + if !(store.at..end).contains(&at) || store.at / BLOCK != (end - 1) / BLOCK { + add(4); + return false; + } + let mut done = false; + let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| { + // SAFETY: the bytes the title is storing to, at our view of them. + done = unsafe { store.run(context, store.at.wrapping_add(delta)) }; + }); + if put != Beside::Done { + if put == Beside::Full { + site.fetch_add(1 << 32, Relaxed); + add(5); + } + return false; + } + if !done { + // (A locked one that is not aligned: told as written for nothing.) + add(4); + return false; + } + context.Rip += store.len as u64; + site.fetch_add(1, Relaxed); + add(3); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Stored, rip, at / BLOCK, 0); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sites_that_fill_blocks_are_told_from_others() { + assert!(sparse(0) && sparse(1000) && sparse(3 << 32)); + assert!(!sparse(4 << 32 | 16) && sparse(4 << 32 | 60)); + } + + #[test] + fn copies_that_meet_are_left_to_the_runtime() { + const B: usize = crate::watch::PAGE; + assert!(overlap(10 * B + 5, 10 * B + 900, 8), "in one block"); + assert!(!overlap(10 * B + 5, 12 * B, 8) && !overlap(10 * B, 9 * B, B)); + assert!(overlap(10 * B, 9 * B, B + 1)); + } +} diff --git a/crates/victory-gpu/src/titlewrite/decode.rs b/crates/victory-gpu/src/titlewrite/decode.rs new file mode 100644 index 0000000..4c1bd67 --- /dev/null +++ b/crates/victory-gpu/src/titlewrite/decode.rs @@ -0,0 +1,632 @@ +//! 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`. + +use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering::SeqCst}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Alu { + Add, + Or, + And, + Sub, + Xor, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Op { + /// These bytes (the low `size` of them). + Put([u8; 16]), + /// With a value; `keeps` carry (`inc`, `dec`). + Alu { alu: Alu, with: u64, keeps: bool }, + /// With a register, which gets what was there. + Xchg(Register), + Xadd(Register), + Cmpxchg(Register), +} + +/// A general register, or (`high`) the second byte of one of the first four. +#[derive(Clone, Copy, PartialEq, Debug)] +struct Register { + number: usize, + high: bool, +} + +pub(super) struct Store { + /// Where it stores, and how many bytes. + pub(super) at: usize, + pub(super) size: usize, + /// The instruction's length. + pub(super) len: usize, + op: Op, + locked: bool, +} + +fn general(c: &CONTEXT, number: usize) -> u64 { + match number { + 0 => c.Rax, + 1 => c.Rcx, + 2 => c.Rdx, + 3 => c.Rbx, + 4 => c.Rsp, + 5 => c.Rbp, + 6 => c.Rsi, + 7 => c.Rdi, + 8 => c.R8, + 9 => c.R9, + 10 => c.R10, + 11 => c.R11, + 12 => c.R12, + 13 => c.R13, + 14 => c.R14, + _ => c.R15, + } +} + +fn general_mut(c: &mut CONTEXT, number: usize) -> &mut u64 { + match number { + 0 => &mut c.Rax, + 1 => &mut c.Rcx, + 2 => &mut c.Rdx, + 3 => &mut c.Rbx, + 4 => &mut c.Rsp, + 5 => &mut c.Rbp, + 6 => &mut c.Rsi, + 7 => &mut c.Rdi, + 8 => &mut c.R8, + 9 => &mut c.R9, + 10 => &mut c.R10, + 11 => &mut c.R11, + 12 => &mut c.R12, + 13 => &mut c.R13, + 14 => &mut c.R14, + _ => &mut c.R15, + } +} + +impl Register { + /// Operand `number` of `size` bytes, with or without a REX prefix. + fn of(number: usize, size: usize, rex: bool) -> Register { + if size == 1 && !rex && (4..8).contains(&number) { + Register { number: number - 4, high: true } + } else { + Register { number, high: false } + } + } + + fn get(self, c: &CONTEXT) -> u64 { + general(c, self.number) >> if self.high { 8 } else { 0 } + } + + /// As an instruction writes it: 32 bits clear the rest, fewer leave it. + fn put(self, c: &mut CONTEXT, value: u64, size: usize) { + let register = general_mut(c, self.number); + let shift = if self.high { 8 } else { 0 }; + *register = match size { + 8 => value, + 4 => value & 0xffff_ffff, + _ => *register & !(mask(size) << shift) | (value & mask(size)) << shift, + }; + } +} + +fn mask(size: usize) -> u64 { + if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 } +} + +/// 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; + let mut next = || { + let byte = code.get(at).copied(); + at += 1; + byte + }; + let (mut locked, mut narrow, mut repeat) = (false, false, 0u8); + let mut byte = next()?; + loop { + match byte { + 0xf0 => locked = true, + 0x66 => narrow = true, + 0xf2 | 0xf3 => repeat = byte, + // (Of data and stack segments nothing is used; branch hints.) + 0x2e | 0x36 | 0x3e | 0x26 => {} + _ => break, + } + byte = next()?; + } + let mut rex = 0u8; + if byte & 0xf0 == 0x40 { + rex = byte; + byte = next()?; + } + // The vector prefixes, with their own forms of the others. + let vector = match byte { + 0xc5 if rex == 0 => { + let b = next()?; + rex = if b & 0x80 == 0 { 0x44 } else { 0x40 }; + Some(b) + } + 0xc4 if rex == 0 => { + let (b, d) = (next()?, next()?); + if b & 0x1f != 1 { + return None; + } + rex = 0x40 | (!b >> 5 & 7) | (d >> 4 & 8); + Some(d) + } + _ => None, + }; + if let Some(b) = vector { + // (No 32 byte ones: they fill memory.) + if b & 4 != 0 || narrow || repeat != 0 || locked { + return None; + } + // (A store has no third register.) + if b >> 3 & 15 != 15 { + return None; + } + (narrow, repeat) = match b & 3 { + 0 => (false, 0), + 1 => (true, 0), + 2 => (false, 0xf3), + _ => (false, 0xf2), + }; + byte = next()?; + } + let two = vector.is_some() || byte == 0x0f; + if two && vector.is_none() { + byte = next()?; + } + let wide = rex & 8 != 0; + let modrm = next()?; + let (mode, reg, rm) = (modrm >> 6, (modrm >> 3 & 7) as usize | (rex as usize & 4) << 1, modrm & 7); + if mode == 3 { + return None; + } + // The address, all but what hangs on the instruction's length. + let mut address = 0u64; + let mut on_rip = false; + let mut base = Some(rm as usize | (rex as usize & 1) << 3); + if rm == 4 { + let sib = next()?; + let index = (sib >> 3 & 7) as usize | (rex as usize & 2) << 2; + if index != 4 { + address = general(c, index) << (sib >> 6); + } + base = Some((sib & 7) as usize | (rex as usize & 1) << 3); + if sib & 7 == 5 && mode == 0 { + base = None; + } + } else if rm == 5 && mode == 0 { + base = None; + on_rip = true; + } + if let Some(base) = base { + address = address.wrapping_add(general(c, base)); + } + let displacement = match mode { + 1 => i64::from(next()? as i8), + 2 => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])), + _ if base.is_none() => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])), + _ => 0, + }; + address = address.wrapping_add(displacement as u64); + + let words = if wide { + 8 + } else if narrow { + 2 + } else { + 4 + }; + let put = |value: u64| { + let mut bytes = [0; 16]; + bytes[..8].copy_from_slice(&value.to_le_bytes()); + Op::Put(bytes) + }; + let of = |size: usize| Register::of(reg, size, rex != 0); + let vector_bytes = || { + // SAFETY: the registers, whichever way they are named. + let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg]; + let mut bytes = [0; 16]; + bytes[..8].copy_from_slice(&x.Low.to_le_bytes()); + bytes[8..].copy_from_slice(&x.High.to_le_bytes()); + bytes + }; + let alu_of = |kind: u8| match kind { + 0 => Some(Alu::Add), + 1 => Some(Alu::Or), + 4 => Some(Alu::And), + 5 => Some(Alu::Sub), + 6 => Some(Alu::Xor), + _ => None, + }; + let (op, size) = 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); + (Op::Put(bytes), 8) + } + (0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }), + _ if vector.is_some() || repeat != 0 => return None, + (0xc3, false, _) => (put(of(words).get(c)), words), + (0xb0 | 0xb1, _, _) => { + let size = if byte & 1 == 0 { 1 } else { words }; + (Op::Cmpxchg(of(size)), size) + } + (0xc0 | 0xc1, _, _) => { + let size = if byte & 1 == 0 { 1 } else { words }; + (Op::Xadd(of(size)), size) + } + _ => return None, + } + } else { + if repeat != 0 { + return None; + } + let size = if byte & 1 == 0 { 1 } else { words }; + let mut constant = |bytes: usize| -> Option { + Some(match bytes { + 1 => next()? as i8 as i64 as u64, + 2 => i64::from(i16::from_le_bytes([next()?, next()?])) as u64, + _ => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])) as u64, + }) + }; + match byte { + 0x88 | 0x89 => (put(of(size).get(c)), size), + 0xc6 | 0xc7 if reg & 7 == 0 => (put(constant(size)?), size), + 0x00 | 0x01 | 0x08 | 0x09 | 0x20 | 0x21 | 0x28 | 0x29 | 0x30 | 0x31 => { + (Op::Alu { alu: alu_of(byte >> 3)?, with: of(size).get(c), keeps: false }, size) + } + 0x80 | 0x81 | 0x83 => { + let alu = alu_of(reg as u8 & 7)?; + (Op::Alu { alu, with: constant(if byte == 0x81 { size } else { 1 })?, keeps: false }, size) + } + 0x86 | 0x87 => { + locked = true; + (Op::Xchg(of(size)), size) + } + 0xfe | 0xff if reg & 7 < 2 => { + (Op::Alu { alu: if reg & 7 == 0 { Alu::Add } else { Alu::Sub }, with: 1, keeps: true }, size) + } + _ => return None, + } + }; + if locked && matches!(op, Op::Put(_)) { + return None; + } + // What is read of memory decides nothing but what is stored: no + // register but the operand is written. + if on_rip { + address = address.wrapping_add(c.Rip).wrapping_add(at as u64); + } + Some(Store { at: address as usize, size, len: at, op, locked }) +} + +const CF: u32 = 1; +const PF: u32 = 4; +const AF: u32 = 0x10; +const ZF: u32 = 0x40; +const SF: u32 = 0x80; +const OF: u32 = 0x800; + +/// The result of an operation on `size` bytes and the flags it leaves. +fn arithmetic(alu: Alu, a: u64, b: u64, size: usize, keeps: bool, flags: u32) -> (u64, u32) { + let m = mask(size); + let (a, b) = (a & m, b & m); + let top = |v: u64| v >> (size * 8 - 1) & 1 != 0; + let r = match alu { + Alu::Add => a.wrapping_add(b), + Alu::Or => a | b, + Alu::And => a & b, + Alu::Sub => a.wrapping_sub(b), + Alu::Xor => a ^ b, + } & m; + let mut out = flags & !(CF | PF | AF | ZF | SF | OF); + let mut flag = |set: bool, flag: u32| out |= if set { flag } else { 0 }; + flag(r == 0, ZF); + flag(top(r), SF); + flag((r as u8).count_ones().is_multiple_of(2), PF); + match alu { + Alu::Add => { + flag(r < a, CF); + flag(top((a ^ r) & (b ^ r)), OF); + flag((a ^ b ^ r) & 16 != 0, AF); + } + Alu::Sub => { + flag(a < b, CF); + flag(top((a ^ b) & (a ^ r)), OF); + flag((a ^ b ^ r) & 16 != 0, AF); + } + _ => {} + } + if keeps { + out = out & !CF | flags & CF; + } + (r, out) +} + +/// A value of `size` bytes in memory, changed by `f` as one if `locked`: what +/// was there (`None`: not aligned). +/// +/// # Safety +/// `size` bytes can be read and written at `at`. +unsafe fn change(at: usize, size: usize, locked: bool, f: impl Fn(u64) -> u64) -> Option { + if !locked { + let mut bytes = [0u8; 8]; + // SAFETY (both): by the caller. + unsafe { std::ptr::copy_nonoverlapping(at as *const u8, bytes.as_mut_ptr(), size) }; + let was = u64::from_le_bytes(bytes); + unsafe { std::ptr::copy_nonoverlapping(f(was).to_le_bytes().as_ptr(), at as *mut u8, size) }; + return Some(was); + } + if !at.is_multiple_of(size) { + return None; + } + // SAFETY (all): by the caller, and aligned. + Some(unsafe { + match size { + 1 => u64::from(AtomicU8::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u8)).ok()?), + 2 => u64::from(AtomicU16::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u16)).ok()?), + 4 => u64::from(AtomicU32::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u32)).ok()?), + _ => AtomicU64::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v))).ok()?, + } + }) +} + +impl Store { + /// Does it, with `to` for the address, and gives the registers what the + /// instruction leaves in them (but the instruction pointer). `false`: + /// nothing was done. + /// + /// # Safety + /// [`Store::size`] bytes can be read and written at `to`. + pub(super) unsafe fn run(&self, c: &mut CONTEXT, to: usize) -> bool { + let (size, locked, m) = (self.size, self.locked, mask(self.size)); + // SAFETY (all `change`s): by the caller. + match self.op { + Op::Put(bytes) => { + // 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")); + 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), + 4 if to.is_multiple_of(4) => (to as *mut u32).write_volatile(low as u32), + 8 if to.is_multiple_of(8) => (to as *mut u64).write_volatile(low), + _ => std::ptr::copy_nonoverlapping(bytes.as_ptr(), to as *mut u8, size), + } + } + } + Op::Alu { alu, with, keeps } => { + let flags = c.EFlags; + let Some(was) = (unsafe { change(to, size, locked, |v| arithmetic(alu, v, with, size, keeps, flags).0) }) else { + return false; + }; + c.EFlags = arithmetic(alu, was, with, size, keeps, flags).1; + } + Op::Xchg(register) => { + let value = register.get(c) & m; + let Some(was) = (unsafe { change(to, size, true, |_| value) }) else { + return false; + }; + register.put(c, was & m, size); + } + Op::Xadd(register) => { + let value = register.get(c); + let Some(was) = (unsafe { change(to, size, locked, |v| v.wrapping_add(value) & m) }) else { + return false; + }; + c.EFlags = arithmetic(Alu::Add, was, value, size, false, c.EFlags).1; + register.put(c, was & m, size); + } + Op::Cmpxchg(register) => { + let (value, expected) = (register.get(c) & m, c.Rax & m); + let Some(was) = (unsafe { change(to, size, locked, |v| if v & m == expected { value } else { v }) }) else { + return false; + }; + let was = was & m; + c.EFlags = arithmetic(Alu::Sub, expected, was, size, false, c.EFlags).1; + if was != expected { + Register { number: 0, high: false }.put(c, was, size); + } + } + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn context() -> CONTEXT { + // SAFETY: plain data. + unsafe { std::mem::zeroed() } + } + + /// The instruction's address, size and length, with every register its + /// number times 0x10000. + fn decoded(code: &[u8]) -> Option<(usize, usize, usize)> { + let mut c = context(); + for n in 0..16 { + *general_mut(&mut c, n) = n as u64 * 0x10000; + } + c.Rip = 0x7000_0000; + let mut padded = code.to_vec(); + padded.resize(15, 0xcc); + store(&padded, &c).map(|s| (s.at, s.size, s.len)) + } + + #[test] + fn stores_are_told_by_their_bytes() { + // mov [rcx+rax+48h], rbx + assert_eq!(decoded(&[0x48, 0x89, 0x5c, 0x01, 0x48]), Some((0x10048, 8, 5))); + // mov [rbx], rdx + assert_eq!(decoded(&[0x48, 0x89, 0x13]), Some((0x30000, 8, 3))); + // or byte [r9+9eh], 1 + assert_eq!(decoded(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1]), Some((0x9009e, 1, 8))); + // lock dec dword [rcx+10h] + assert_eq!(decoded(&[0xf0, 0xff, 0x49, 0x10]), Some((0x10010, 4, 4))); + // lock xadd [r10+r12*8-1], eax + assert_eq!(decoded(&[0xf0, 0x43, 0x0f, 0xc1, 0x44, 0xe2, 0xff]), Some((0xa0000 + 0xc0000 * 8 - 1, 4, 7))); + // mov word [rsp], 1234h + assert_eq!(decoded(&[0x66, 0xc7, 0x04, 0x24, 0x34, 0x12]), Some((0x40000, 2, 6))); + // mov [rip+10h], al; mov byte [rip+10h], 5 (counted from its end) + assert_eq!(decoded(&[0x88, 0x05, 0x10, 0, 0, 0]), Some((0x7000_0016, 1, 6))); + assert_eq!(decoded(&[0xc6, 0x05, 0x10, 0, 0, 0, 5]), Some((0x7000_0017, 1, 7))); + // mov [12345678h], eax (no base) + assert_eq!(decoded(&[0x89, 0x04, 0x25, 0x78, 0x56, 0x34, 0x12]), Some((0x1234_5678, 4, 7))); + // vmovaps [rsi+10h], xmm4; vmovaps [r12], xmm3; movups [rax], xmm9 + assert_eq!(decoded(&[0xc5, 0xf8, 0x29, 0x66, 0x10]), Some((0x60010, 16, 5))); + assert_eq!(decoded(&[0xc4, 0xc1, 0x78, 0x29, 0x1c, 0x24]), Some((0xc0000, 16, 6))); + assert_eq!(decoded(&[0x44, 0x0f, 0x11, 0x08]), Some((0, 16, 4))); + // vmovss [rax], xmm0; movlps, movhps, vmovq, movd + assert_eq!(decoded(&[0xc5, 0xfa, 0x11, 0x00]), Some((0, 4, 4))); + 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); + assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None); + assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None); + assert_eq!(decoded(&[0xf3, 0xa4]), None); + assert_eq!(decoded(&[0x65, 0x48, 0x89, 0x13]), None); + assert_eq!(decoded(&[0x83, 0x38, 1]), None); + assert_eq!(decoded(&[0x11, 0x00]), None); + // blend by a mask (vmaskmov is of another map), vmovss with a third + // register. + assert_eq!(decoded(&[0xc4, 0xe2, 0x79, 0x2e, 0x00]), None); + } + + /// What the processor makes of `code` with rax as the address, rcx and + /// rdx as operands; against [`Store::run`]. + fn against_the_processor(code: &[u8], seed: u64) { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc}; + static PLACE: std::sync::OnceLock = std::sync::OnceLock::new(); + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: fresh memory for code. + let place = *PLACE.get_or_init(|| unsafe { + VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize + }); + let spread = |n: u64| { + let v = (seed + n).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ seed << 7; + // Small, edge and large ones. + match v >> 61 { + 0 => 0, + 1 => v & 1, + 2 => u64::MAX, + 3 => 0x8000_0000_0000_0000u64 | 0x8000 | 0x80 | 0x8000_0000, + _ => v, + } + }; + // f(address, operand, compared, flags, out): + // mov r11, rcx ; the address (its instruction takes [r11]) + // mov rax, r8 ; mov r10, r9 ; push r10 ; popfq ; ; pushfq ; pop r10 + // mov rcx, [rsp+28h] ; mov [rcx], r10 ; mov [rcx+8], rdx ; mov [rcx+16], rax ; ret + let mut f = vec![0x49, 0x89, 0xcb, 0x4c, 0x89, 0xc0, 0x41, 0x51, 0x9d]; + f.extend(code); + f.extend([0x9c, 0x41, 0x5a, 0x48, 0x8b, 0x4c, 0x24, 0x28]); + f.extend([0x4c, 0x89, 0x11, 0x48, 0x89, 0x51, 0x08, 0x48, 0x89, 0x41, 0x10, 0xc3]); + type F = unsafe extern "system" fn(*mut u64, u64, u64, u64, *mut [u64; 3]); + let (there, operand, compared) = (spread(1), spread(2), if seed % 3 == 0 { spread(1) } else { spread(3) }); + let flags = 0x202 | (spread(4) & 0x8d5) as u32; + let (mut memory, mut out) = (there, [0; 3]); + // SAFETY: the code above, which keeps to the calling convention. + unsafe { + std::ptr::copy_nonoverlapping(f.as_ptr(), place as *mut u8, f.len()); + let f: F = std::mem::transmute(place); + f(&mut memory, operand, compared, u64::from(flags), &mut out); + } + let mut c = context(); + let mut ours = there; + (c.R11, c.Rdx, c.Rax, c.EFlags) = (&raw mut ours as u64, operand, compared, flags); + let mut padded = code.to_vec(); + padded.resize(15, 0xcc); + let store = store(&padded, &c).unwrap_or_else(|| panic!("{code:x?}")); + assert_eq!((store.at, store.len), (&raw mut ours as usize, code.len()), "{code:x?}"); + // SAFETY: our word. + assert!(unsafe { store.run(&mut c, &raw mut ours as usize) }); + assert_eq!(ours, memory, "{code:x?} of {there:x} with {operand:x}"); + assert_eq!((c.Rdx, c.Rax), (out[1], out[2]), "{code:x?} of {there:x} with {operand:x}, {compared:x}"); + // (`and`, `or` and `xor` leave AF as they like.) + const SEEN: u32 = CF | PF | ZF | SF | OF; + assert_eq!(c.EFlags & SEEN, out[0] as u32 & SEEN, "{code:x?} of {there:x} with {operand:x}"); + } + + #[test] + fn stores_do_what_the_processor_does() { + let mut codes: Vec> = Vec::new(); + // op [r11], rdx in all sizes; op [r11], constant; inc, dec; xchg, xadd, cmpxchg. + for op in [0x00, 0x08, 0x20, 0x28, 0x30, 0x88, 0x86] { + codes.push(vec![0x41, op, 0x13]); + codes.push(vec![0x66, 0x41, op | 1, 0x13]); + codes.push(vec![0x41, op | 1, 0x13]); + codes.push(vec![0x49, op | 1, 0x13]); + if op < 0x80 { + codes.push(vec![0xf0, 0x41, op | 1, 0x13]); + codes.push(vec![0xf0, 0x49, op | 1, 0x13]); + } + } + for kind in [0u8, 1, 4, 5, 6] { + let modrm = 0x03 | kind << 3; + for constant in [1, 0x7f, 0x80, 0xff] { + codes.push(vec![0x41, 0x80, modrm, constant]); + codes.push(vec![0x41, 0x83, modrm, constant]); + codes.push(vec![0x49, 0x83, modrm, constant]); + codes.push(vec![0x66, 0x41, 0x83, modrm, constant]); + codes.push(vec![0xf0, 0x41, 0x83, modrm, constant]); + codes.push(vec![0x49, 0x81, modrm, 3, 0, 0, constant]); + codes.push(vec![0x66, 0x41, 0x81, modrm, 3, constant]); + } + } + for modrm in [0x03, 0x0b] { + codes.push(vec![0x41, 0xfe, modrm]); + codes.push(vec![0x41, 0xff, modrm]); + codes.push(vec![0x49, 0xff, modrm]); + codes.push(vec![0xf0, 0x41, 0xff, modrm]); + codes.push(vec![0x66, 0x41, 0xff, modrm]); + } + for op in [0xb0, 0xc0] { + codes.push(vec![0x41, 0x0f, op, 0x13]); + codes.push(vec![0xf0, 0x41, 0x0f, op, 0x13]); + codes.push(vec![0xf0, 0x66, 0x41, 0x0f, op | 1, 0x13]); + codes.push(vec![0xf0, 0x41, 0x0f, op | 1, 0x13]); + codes.push(vec![0xf0, 0x49, 0x0f, op | 1, 0x13]); + } + codes.push(vec![0x41, 0xc6, 0x03, 0x99]); + codes.push(vec![0x66, 0x41, 0xc7, 0x03, 0x99, 0x88]); + codes.push(vec![0x41, 0xc7, 0x03, 1, 2, 3, 0x84]); + codes.push(vec![0x49, 0xc7, 0x03, 1, 2, 3, 0x84]); + for code in &codes { + for seed in 0..200 { + against_the_processor(code, seed); + } + } + } + + /// The second byte of a register, and 32 bits that clear the rest. + #[test] + fn registers_are_read_and_written_as_by_the_processor() { + let mut c = context(); + c.Rax = 0x1122_3344_5566_7788; + assert_eq!(Register::of(4, 1, false).get(&c) & 0xff, 0x77, "ah"); + assert_eq!(Register::of(4, 1, true), Register { number: 4, high: false }, "spl"); + Register { number: 0, high: true }.put(&mut c, 0xff, 1); + assert_eq!(c.Rax, 0x1122_3344_5566_ff88); + Register { number: 0, high: false }.put(&mut c, 0xabcd, 2); + assert_eq!(c.Rax, 0x1122_3344_5566_abcd); + Register { number: 0, high: false }.put(&mut c, u64::MAX, 4); + assert_eq!(c.Rax, 0xffff_ffff); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 92c69e5..1c790d2 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -27,6 +27,7 @@ //! before. use std::collections::{BTreeMap, BTreeSet}; +use std::ops::{Bound, RangeBounds}; use std::sync::{Condvar, Mutex, RwLock}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's @@ -625,7 +626,10 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve // Read-only since an asking noted it: the bits first, then the journal. if guarded && published(start, end) { #[cfg(feature = "diagnostics")] - tally(2, 1); + { + tally(2, 1); + crate::faultbook::note(crate::faultbook::What::Known, first, last, 0); + } let j = journal(); return Some((next_asking(), of(&j))); } @@ -636,7 +640,9 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve return Some(known); } let mut guards_asked = false; - let pages = match kernel_written(first, last) { + // (View memory read-only by our hand: the kernel would refuse.) + let refused = guarded && light() && PROTECTED.any(first, last); + let pages = match if refused { None } else { kernel_written(first, last) } { Some(pages) => pages, None => { guards_asked = true; @@ -692,6 +698,10 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], let (first, last) = (start / PAGE, end.div_ceil(PAGE)); // The bits first, then the journal, as in `writes`. let known = published(start, end); + #[cfg(feature = "diagnostics")] + if known { + crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); + } let j = journal(); if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { return false; @@ -781,19 +791,36 @@ impl Bits { unsafe { piece.as_ref() } } - /// One caller at a time (under the guards' lock). fn set(&self, block: usize) { - use std::sync::atomic::Ordering::{Relaxed, Release}; + use std::sync::atomic::Ordering::{AcqRel, Acquire, SeqCst}; let word = block / 64; let Some(place) = self.0.get(word / Bits::WORDS) else { return; }; - if place.load(Relaxed).is_null() { + if place.load(Acquire).is_null() { let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); - place.store(Box::into_raw(piece), Release); + let piece = Box::into_raw(piece); + if place.compare_exchange(std::ptr::null_mut(), piece, AcqRel, Acquire).is_err() { + // SAFETY: made just now, and another thread's is there. + drop(unsafe { Box::from_raw(piece) }); + } } if let Some(piece) = self.piece(word) { - piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release); + piece[word % Bits::WORDS].fetch_or(1 << (block % 64), SeqCst); + } + } + + /// Sixty-four of them. + fn word(&self, word: usize) -> u64 { + self.piece(word).map_or(0, |piece| piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst)) + } + + /// Whether it was set, and is no more. + fn take(&self, block: usize) -> bool { + self.any(block, block + 1) && { + let (word, bit) = (block / 64, 1 << (block % 64)); + self.piece(word) + .is_some_and(|piece| piece[word % Bits::WORDS].fetch_and(!bit, std::sync::atomic::Ordering::SeqCst) & bit != 0) } } @@ -873,12 +900,93 @@ static PUBLISHED: Bits = Bits::new(); /// no view. static PROTECTED: Bits = Bits::new(); +/// The blocks the title's bytes were put in beside their guards +/// ([`put_beside`]) and that no asking has told as written since. Such a +/// block is as it was else: read-only, clean, and an asking that finds its +/// bit here takes the bit and tells it as written. +/// +/// The bit is set when the bytes are in, at every view of the page, and +/// [`PUBLISHED`]'s is cleared after that. So an asking either finds the bit +/// or came before the title's thread went on from its write; and who takes +/// the bit reads the bytes after. +static BESIDE: Bits = Bits::new(); + +/// How much was put into a block beside its guard since it was last told as +/// written (`crate::titlewrite::MOST`), by a few bits of its number. +static PUT: [std::sync::atomic::AtomicU32; 1 << 13] = [const { std::sync::atomic::AtomicU32::new(0) }; 1 << 13]; + +fn put_count(block: usize) -> &'static std::sync::atomic::AtomicU32 { + &PUT[block % PUT.len()] +} + +/// Whether [`put_beside`] put it there. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Beside { + Done, + /// The block has had its share. + Full, + /// Not guarded, or there is no other way to its page, or the runtime is + /// changing a mapping. + Cannot, +} + +/// Whether a block of `[at, at + len)` is (or is about to be) read-only by +/// our hand. `len` is not 0. +#[inline] +pub(crate) fn guards_any(at: usize, len: usize) -> bool { + PROTECTED.any(at / BLOCK, (at.saturating_add(len) - 1) / BLOCK + 1) +} + +/// The title's bytes for a guarded block, put in by `put` at our own view of +/// the same page: it is given what to add to an address of the block (as by +/// `wrapping_add`). `weight`: how much of the block's share it is. +pub(crate) fn put_beside(block: usize, weight: u32, put: impl FnOnce(usize)) -> Beside { + use std::sync::atomic::Ordering::Relaxed; + if !light() || !view_guard() || !PROTECTED.any(block, block + 1) { + return Beside::Cannot; + } + let count = put_count(block); + if count.load(Relaxed) + weight > crate::titlewrite::MOST { + return Beside::Full; + } + // No mapping changes until all is told: a view of the page that came + // after the look at them would not be. + let Some(_reading) = title_memory_reading_now() else { + return Beside::Cannot; + }; + let Some((page, shown)) = crate::inplace::beside_page(block * BLOCK) else { + return Beside::Cannot; + }; + put(page.wrapping_sub(block * BLOCK)); + count.fetch_add(weight, Relaxed); + for view in shown.iter().filter(|&&view| view != 0) { + BESIDE.set(view / BLOCK); + } + for view in shown.iter().filter(|&&view| view != 0) { + PUBLISHED.clear(view / BLOCK); + } + Beside::Done +} + +/// The title is about to write block by block around `at`: as by a fault. +pub(crate) fn opened_for_writing(at: usize) { + let mut g = guards(); + if open(&mut g, at, at + 1) != 0 { + g.opened(at / BLOCK); + } +} + /// An asking made blocks of `pages` clean and noted them in the journal. fn publish(pages: &[usize]) { let g = guards(); - for page in pages { + for &page in pages { if g.clean.contains(page) || g.held.contains(page) { - PUBLISHED.set(*page); + PUBLISHED.set(page); + // (Put there since: whoever did clears the bit after this is + // set, or its own bit is found here.) + if BESIDE.any(page, page + 1) { + PUBLISHED.clear(page); + } } } } @@ -948,9 +1056,9 @@ pub fn title_memory_allocated(at: usize, len: usize) { return; } let mut g = guards(); - let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + let blocks: Vec = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect(); for block in blocks { - g.held.remove(&block); + g.held.remove(block); PUBLISHED.clear(block); } } @@ -967,7 +1075,7 @@ pub(crate) fn look_at_holes() { let blocks: Vec = { let g = guards(); let from = FROM.load(std::sync::atomic::Ordering::Relaxed); - let part: Vec = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect(); + let part: Vec = g.held.range(from..).take(g.held.len() / PARTS + 1).collect(); FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed); part }; @@ -980,7 +1088,7 @@ pub(crate) fn look_at_holes() { // (Or unmapped memory was mapped since the part was taken: told // already, and forgotten.) let mut g = guards(); - if g.held.remove(&block) { + if g.held.remove(block) { PUBLISHED.clear(block); static SAID: std::sync::Once = std::sync::Once::new(); SAID.call_once(|| { @@ -1037,16 +1145,162 @@ fn guards_timed() -> std::sync::MutexGuard<'static, Guards> { g } +/// A set of blocks, a bit each: a fault, or a look at a range of thousands of +/// blocks, is a few words of it and no walk through a tree of every guarded +/// block there is. +struct Blocks(BTreeMap>); + +impl Blocks { + /// The words of 4 GiB. + const WORDS: usize = 1 << 10; + const IN_PIECE: usize = Blocks::WORDS * 64; + + const fn new() -> Blocks { + Blocks(BTreeMap::new()) + } + + fn word(&self, word: usize) -> u64 { + self.0.get(&(word / Blocks::WORDS)).map_or(0, |piece| piece[word % Blocks::WORDS]) + } + + fn contains(&self, block: usize) -> bool { + self.word(block / 64) >> (block % 64) & 1 != 0 + } + + /// Whether it was not there. + fn insert(&mut self, block: usize) -> bool { + let piece = self.0.entry(block / Blocks::IN_PIECE).or_insert_with(|| Box::new([0; Blocks::WORDS])); + let word = &mut piece[block % Blocks::IN_PIECE / 64]; + let was = *word; + *word |= 1 << (block % 64); + was != *word + } + + /// Whether it was there. + fn remove(&mut self, block: usize) -> bool { + let Some(piece) = self.0.get_mut(&(block / Blocks::IN_PIECE)) else { + return false; + }; + let word = &mut piece[block % Blocks::IN_PIECE / 64]; + let was = *word; + *word &= !(1 << (block % 64)); + was != *word + } + + fn insert_all(&mut self, blocks: std::ops::Range) { + for block in blocks { + self.insert(block); + } + } + + /// Those of `range`, in order. + fn range(&self, range: impl RangeBounds) -> impl Iterator + '_ { + let first = match range.start_bound() { + Bound::Included(&first) => first, + Bound::Excluded(&before) => before.saturating_add(1), + Bound::Unbounded => 0, + }; + // (Exclusive. No block's number is near the top.) + let last = match range.end_bound() { + Bound::Included(&last) => last.saturating_add(1), + Bound::Excluded(&last) => last, + Bound::Unbounded => usize::MAX, + } + .max(first); + self.0.range(first / Blocks::IN_PIECE..=last / Blocks::IN_PIECE).flat_map(move |(&piece, words)| { + let base = piece * Blocks::IN_PIECE; + let from = first.max(base) - base; + let to = last.min(base + Blocks::IN_PIECE).saturating_sub(base); + let words = if from < to { &words[from / 64..to.div_ceil(64)] } else { &[][..] }; + words.iter().enumerate().flat_map(move |(k, &bits)| { + let at = (from / 64 + k) * 64; + BitsOf(bits & in_word(at, from, to)).map(move |bit| base + at + bit) + }) + }) + } + + fn len(&self) -> usize { + self.0.values().flat_map(|piece| piece.iter()).map(|word| word.count_ones() as usize).sum() + } +} + +/// Of the 64 blocks from `at` on, those in `[from, to)`, a bit each. +fn in_word(at: usize, from: usize, to: usize) -> u64 { + let low = from.saturating_sub(at).min(64); + let high = to.saturating_sub(at).min(64); + if low >= high { 0 } else { (u64::MAX >> (64 - (high - low))) << low } +} + +/// The bits of a word that are set, by number. +struct BitsOf(u64); + +impl Iterator for BitsOf { + type Item = usize; + fn next(&mut self) -> Option { + let bit = (self.0 != 0).then(|| self.0.trailing_zeros() as usize)?; + self.0 &= self.0 - 1; + Some(bit) + } +} + +/// Whether a write fault opens the view that was written and leaves the +/// page's other views read-only, not clean any more +/// (`VICTORY_OPEN_ONE_VIEW=0`: opens them all, as before). +/// +/// The others were opened (a change of protection each, under the guards' +/// lock, with other faults waiting) and made read-only again when the page +/// was next taken, though the title writes through one of them: 586 faults a +/// frame opened 880 blocks (run faults-1). A write through one left as it was +/// faults, and opens it. +fn open_one_view() -> bool { + crate::toggled!("VICTORY_OPEN_ONE_VIEW") +} + +/// How long a block the title has just opened by a write is left open by +/// those that take it (`VICTORY_GUARD_REST=`, 3,000 unless +/// given; `0`: not at all, as before). +/// +/// 220 of a frame's 586 faults came within 3 ms after a refresh had taken the +/// block and made it read-only, while the title was still writing it, and +/// what a refresh takes is asked about again by the next within a millisecond +/// (run faults-1): made read-only, written, opened, up to a dozen times a +/// frame. A block that rests counts as written at each asking, so nothing is +/// missed; it is read-only at the first asking after its rest, which the +/// title's later writes are seen by. +fn rest() -> std::time::Duration { + #[cfg(test)] + { + REST_IN_TEST.get() + } + #[cfg(not(test))] + { + static US: std::sync::OnceLock = std::sync::OnceLock::new(); + if !crate::toggled!("VICTORY_GUARD_REST") { + return std::time::Duration::ZERO; + } + let us = *US.get_or_init(|| { + std::env::var("VICTORY_GUARD_REST").ok().and_then(|v| v.trim().parse().ok()).filter(|us| *us > 1).unwrap_or(3000) + }); + std::time::Duration::from_micros(us) + } +} + +#[cfg(test)] +thread_local! { + /// [`rest`], for what this thread asks. + static REST_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; +} + struct Guards { /// Blocks we made read-only. - protected: BTreeSet, + protected: Blocks, /// Of those, the ones not written since a copy took them. - clean: BTreeSet, + clean: Blocks, /// Blocks already copied as zeros. While they remain wholly uncommitted, /// the copy can skip hundreds of MB of failing kernel reads per world frame. - absent: BTreeSet, + absent: Blocks, /// Of those, the ones in placeholders ([`known_holes`]). - held: BTreeSet, + held: Blocks, /// Blocks that were absent and turned out to be other memory than views /// when something was there again: never guarded, copied every time. foreign: BTreeSet, @@ -1060,24 +1314,45 @@ struct Guards { /// read-only together with those (which are in it as well): what opens /// one opens them all. (A write's range can be huge, `fread`'s, so only /// these are looked up.) - aliased: BTreeSet, + aliased: Blocks, + /// Blocks opened by a write fault, and when ([`rest`]). + opened: std::collections::HashMap>, } impl Guards { fn left_alone(&self, block: usize) -> bool { self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block)) } + + /// Whether `block` is left open for now: the title has just written it. + fn rests(&self, block: usize, rest: std::time::Duration) -> bool { + !rest.is_zero() && self.opened.get(&block).is_some_and(|at| at.elapsed() < rest) + } + + /// A write fault opened `block`. + fn opened(&mut self, block: usize) { + const MANY: usize = 1 << 13; + if self.opened.len() >= MANY { + self.opened.retain(|_, at| at.elapsed().as_millis() < 50); + if self.opened.len() >= MANY { + self.opened.clear(); + } + } + put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); + self.opened.insert(block, std::time::Instant::now()); + } } static GUARDS: Mutex = Mutex::new(Guards { - protected: BTreeSet::new(), - clean: BTreeSet::new(), - absent: BTreeSet::new(), - held: BTreeSet::new(), + protected: Blocks::new(), + clean: Blocks::new(), + absent: Blocks::new(), + held: Blocks::new(), foreign: BTreeSet::new(), kernel: Vec::new(), changing: Vec::new(), - aliased: BTreeSet::new(), + aliased: Blocks::new(), + opened: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -1227,7 +1502,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { } let g = guards(); (at / BLOCK..=(at + len - 1) / BLOCK) - .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b) && !g.protected.contains(&b)) + .all(|b| !g.clean.contains(b) && !g.absent.contains(b) && !g.protected.contains(b)) } /// For view memory: the pages of `[start, end)`'s blocks written since @@ -1246,7 +1521,7 @@ fn guard(start: usize, end: usize) -> Option> { let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && (PROTECTED.any(first, first + 1) || { let g = guards_timed(); - g.protected.contains(&first) || g.absent.contains(&first) + g.protected.contains(first) || g.absent.contains(first) }); if !known && !is_view(start, end) { return None; @@ -1258,13 +1533,13 @@ fn guard(start: usize, end: usize) -> Option> { // takes the block out of the set, and it is looked at as any other. let unsure: Vec = { let g = guards_timed(); - if g.clean.range(first..last).count() == last - first { + if g.clean.range(first..last).count() == last - first && !BESIDE.any(first, last) { // Nothing written, mapped or new since the range was last taken. #[cfg(feature = "diagnostics")] tally(3, 1); return Some(Vec::new()); } - g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect() + g.absent.range(first..last).filter(|block| !g.held.contains(*block)).collect() }; let mut came: Vec<(usize, bool)> = Vec::new(); let mut uncommitted_until = first; @@ -1281,45 +1556,64 @@ fn guard(start: usize, end: usize) -> Option> { came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK))); } } + let rest = rest(); let mut g = guards_timed(); #[cfg(feature = "diagnostics")] tally(4, 1); for &(block, view) in &came { - if g.absent.remove(&block) && !view { + if g.absent.remove(block) && !view { g.foreign.insert(block); } } + // The range's blocks that are neither clean nor known to be holes. A + // frame asks about some 10 GB of view memory, 150,000 blocks, nearly all + // clean. let mut written = Vec::new(); - let mut run: Option = None; - // The range's clean blocks, and those known to be holes, in order: read - // off the sets in one pass, not looked up one block at a time. A frame - // asks about some 10 GB of view memory, 150,000 blocks, nearly all - // clean: the lookups were most of the 60-90 ms a frame of "guards" - // (run 54). What the loop adds to the sets meanwhile is the block it - // stands at or ones before it. - let clean: Vec = g.clean.range(first..last).copied().collect(); - let absent: Vec = g.absent.range(first..last).copied().collect(); - let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable()); - for block in first..=last { - let is_clean = clean.next_if_eq(&block).is_some(); - let is_absent = absent.next_if_eq(&block).is_some(); - if block < last && !is_clean && !is_absent { - written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); - if g.protected.contains(&block) { - // Read-only by way of another view of its page, or not clean - // because one could not be made so. - if cover(&mut g, block, block + 1) { - g.clean.insert(block); - } - } else if !g.foreign.contains(&block) && !g.left_alone(block) { - run.get_or_insert(block); + for word in first / 64..last.div_ceil(64) { + let known = g.clean.word(word) & !BESIDE.word(word) | g.absent.word(word); + written.extend(BitsOf(!known & in_word(word * 64, first, last)).map(|bit| word * 64 + bit)); + } + let mut run: Option<(usize, usize)> = None; + for &block in &written { + if let Some((from, to)) = run + && to != block + { + protect(&mut g, from, to); + run = None; + // Faults of the title's wait for the lock: each block is done on + // its own, and looked at anew below. + drop(g); + g = guards_timed(); + } + // Told as written by this, and read by the caller after. + if BESIDE.take(block) { + put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); + } + if g.protected.contains(block) { + // Read-only by way of another view of its page, or not clean + // because one could not be made so. (Or clean, and bytes were put + // in beside the guard: it stays.) + if let Some((from, to)) = run.take() { + protect(&mut g, from, to); + } + if g.clean.contains(block) { continue; } - } - if let Some(from) = run.take() { - protect(&mut g, from, block); + if cover(&mut g, block, block + 1) { + g.clean.insert(block); + } + } else if !g.foreign.contains(&block) && !g.left_alone(block) && !g.rests(block, rest) { + run = Some((run.map_or(block, |r| r.0), block + 1)); + } else if let Some((from, to)) = run.take() { + protect(&mut g, from, to); } } + if let Some((from, to)) = run { + protect(&mut g, from, to); + } + drop(g); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Asked, first, last, written.len() as u64); Some(written) } @@ -1374,6 +1668,8 @@ fn is_view(start: usize, end: usize) -> bool { /// one of those is this memory written, and only a fault can say so. /// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before. fn protect(g: &mut Guards, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Taken, from, to, 0); protect_here(g, from, to); cover(g, from, to); } @@ -1403,7 +1699,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { let mut all = true; for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) { let block = page / BLOCK; - if !g.protected.contains(&block) { + if !g.protected.contains(block) { continue; // not there, or not ours to guard } #[cfg(feature = "diagnostics")] @@ -1415,7 +1711,7 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { } if !covered { all = false; - g.clean.remove(&block); + g.clean.remove(block); } } all @@ -1430,10 +1726,10 @@ fn cover(g: &mut Guards, from: usize, to: usize) -> bool { fn protect_alias(g: &mut Guards, block: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; g.aliased.insert(block); - if g.protected.contains(&block) { + if g.protected.contains(block) { return true; } - if g.left_alone(block) { + if g.left_alone(block) || g.rests(block, rest()) { return false; } // Ahead of the protection. @@ -1450,6 +1746,8 @@ fn protect_alias(g: &mut Guards, block: usize) -> bool { } if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) { g.protected.insert(block); + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Alias, block, 0, 0); return true; } if done { @@ -1492,8 +1790,8 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) { done }; let note = |g: &mut Guards, from: usize, to: usize| { - g.protected.extend(from..to); - g.clean.extend(from..to); + g.protected.insert_all(from..to); + g.clean.insert_all(from..to); }; // Ahead of the protection (`PROTECTED`). (from..to).for_each(|block| PROTECTED.set(block)); @@ -1540,25 +1838,33 @@ fn uncommitted_end(block: usize) -> usize { } /// Gives write access back to the guarded blocks of `[start, end)` and -/// notes them written; true if any was guarded. The same physical pages at -/// every other view of them are opened too: the write that faulted (or is -/// ours, `crate::host::copy_mapped`) goes through one view, and every -/// guard over the pages must copy them again. -fn open(g: &mut Guards, start: usize, end: usize) -> bool { +/// notes them written; how many there were. The same physical pages at +/// every other view of them are written by that too (the write that faulted, +/// or is ours, `crate::host::copy_mapped`, goes through one view): they are +/// clean no longer, whether they are opened as well ([`open_one_view`]) or +/// not. +fn open(g: &mut Guards, start: usize, end: usize) -> usize { let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); if first >= last { - return false; + return 0; } - let mut blocks: Vec = g.protected.range(first..last).copied().collect(); + let mut blocks: Vec = g.protected.range(first..last).collect(); let here = blocks.len(); - if !g.aliased.is_empty() { - let aliased: Vec = g.aliased.range(first..last).copied().collect(); + let aliased: Vec = g.aliased.range(first..last).collect(); + if !aliased.is_empty() { + let one = open_one_view(); for block in aliased { - g.aliased.remove(&block); + g.aliased.remove(block); for other in crate::inplace::pages_of(block * BLOCK) { let other = other / BLOCK; - g.aliased.remove(&other); - if !(first..last).contains(&other) && g.protected.contains(&other) { + if one { + // Before the first can be written. + g.clean.remove(other); + PUBLISHED.clear(other); + continue; + } + g.aliased.remove(other); + if !(first..last).contains(&other) && g.protected.contains(other) { blocks.push(other); } } @@ -1567,7 +1873,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed); } unguard(g, &blocks); - here != 0 + here } /// Gives write access back to `blocks`, guarded ones. @@ -1577,10 +1883,10 @@ fn unguard(g: &mut Guards, blocks: &[usize]) { let started = std::time::Instant::now(); // All of them before the first can be written: a write through one is a // write of the others' bytes. - for block in blocks { + for &block in blocks { g.protected.remove(block); g.clean.remove(block); - PUBLISHED.clear(*block); + PUBLISHED.clear(block); } for &block in blocks { let mut old = 0; @@ -1611,11 +1917,13 @@ pub fn writing(at: usize, len: usize) { let last = at.saturating_add(len).div_ceil(BLOCK); if !light() || PROTECTED.any(at / BLOCK, last) { let mut g = guards_timed(); + let opened = open(&mut g, at, at.saturating_add(len)); #[cfg(feature = "diagnostics")] - let held = g.protected.len(); - open(&mut g, at, at.saturating_add(len)); - #[cfg(feature = "diagnostics")] - tally(6, (held - g.protected.len()) as u64); + { + tally(6, opened as u64); + crate::faultbook::note(crate::faultbook::What::Ours, at / BLOCK, last, opened as u64); + } + let _ = opened; } // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); @@ -1638,10 +1946,10 @@ pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { open(&mut g, at, at.saturating_add(len)); if len != 0 { // Nothing known of them stands while they are left alone. - let absent: Vec = g.absent.range(first..last).copied().collect(); + let absent: Vec = g.absent.range(first..last).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -1758,7 +2066,7 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { } let mut g = guards(); for &(at, n) in &ranges { - let blocks: Vec = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).copied().collect(); + let blocks: Vec = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect(); #[cfg(feature = "diagnostics")] ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed); unguard(&mut g, &blocks); @@ -1776,6 +2084,8 @@ pub fn title_memory_splitting(at: usize, len: usize) { return; } let mut g = guards(); + // (The view itself too: the part that stays is read-only until then.) + open(&mut g, at, at.saturating_add(len)); for other in others { open(&mut g, other, other + BLOCK); if CHANGING.get().0 { @@ -1905,7 +2215,7 @@ fn came_back(at: usize, write: bool) -> bool { return readable_view(at); } // (A refresh may have guarded the page that came back.) - open(&mut guards(), at, at + 1) || writable(at) + open(&mut guards(), at, at + 1) != 0 || writable(at) }; let before = changes(); if there() || again_after_change(before, there) { @@ -2016,14 +2326,10 @@ pub fn title_memory_unmapping(at: usize, len: usize) { _ => g.changing.push((first, last)), } } - let blocks: Vec = g - .protected - .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) - .copied() - .collect(); + let blocks: Vec = g.protected.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).collect(); for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); + g.protected.remove(block); + g.clean.remove(block); PUBLISHED.clear(block); PROTECTED.clear(block); } @@ -2036,8 +2342,8 @@ pub fn title_memory_unmapping(at: usize, len: usize) { pub fn title_memory_freed(at: usize, len: usize) { let mut g = guards(); let first = at / BLOCK; - let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next()); - let Some(noted) = noted.into_iter().flatten().min().copied() else { + let noted = [g.protected.range(first..).next(), g.absent.range(first..).next(), g.foreign.range(first..).next().copied()]; + let Some(noted) = noted.into_iter().flatten().min() else { return; }; let end = if len != 0 { @@ -2048,10 +2354,10 @@ pub fn title_memory_freed(at: usize, len: usize) { if noted >= end { return; } - let absent: Vec = g.absent.range(first..end).copied().collect(); + let absent: Vec = g.absent.range(first..end).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -2096,10 +2402,10 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); - let absent: Vec = g.absent.range(range.clone()).copied().collect(); + let absent: Vec = g.absent.range(range.clone()).collect(); for block in absent { - g.absent.remove(&block); - if g.held.remove(&block) { + g.absent.remove(block); + if g.held.remove(block) { PUBLISHED.clear(block); } } @@ -2107,9 +2413,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, for block in foreign { g.foreign.remove(&block); } - let aliased: Vec = g.aliased.range(range).copied().collect(); + let aliased: Vec = g.aliased.range(range).collect(); for block in aliased { - g.aliased.remove(&block); + g.aliased.remove(block); } g } @@ -2131,9 +2437,11 @@ pub(crate) fn install() { // A fault of our own copies (`crate::safecopy`): whatever it is, if // it is not a block we guard, the copy fails and goes on from there. let ours = crate::safecopy::failing_exit(r.ExceptionAddress as usize); - let fail = |exit: usize| { + // SAFETY: as above. + let context = unsafe { (*info).ContextRecord }; + let fail = move |exit: usize| { // SAFETY: the context the system passes, to go on from. - unsafe { (*(*info).ContextRecord).Rip = exit as u64 }; + unsafe { (*context).Rip = exit as u64 }; EXCEPTION_CONTINUE_EXECUTION }; if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS @@ -2153,20 +2461,49 @@ pub(crate) fn install() { }; } let at = r.ExceptionInformation[1]; - // Held across both checks: another thread may have opened the block - // since this one faulted, and a copy may have guarded it again since - // (then it is ours again, not read-only for some other reason). - let mut g = guards(); - if open(&mut g, at, at + 1) { - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::GuardFaults, 1); + let block = at / BLOCK; + if ours.is_none() + && PROTECTED.any(block, block + 1) + // SAFETY: the context the system passes, to go on from. + && crate::titlewrite::store(unsafe { &mut *context }, at) + { return EXCEPTION_CONTINUE_EXECUTION; } + // Another thread may have opened the block since this one faulted + // (then nothing waits for the lock), and a copy may have guarded it + // again since that (then it is ours again, not read-only for some + // other reason). + for _ in 0..3 { + if !PROTECTED.any(block, block + 1) && writable(at) { + #[cfg(feature = "diagnostics")] + crate::faultbook::note(crate::faultbook::What::Open, block, 0, 0); + return EXCEPTION_CONTINUE_EXECUTION; + } + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + // (Let go again before the next look: the runtime wants the + // guards to end a change.) + let mut g = guards(); + #[cfg(feature = "diagnostics")] + let waited = began.elapsed(); + let opened = open(&mut g, at, at + 1); + if opened != 0 { + g.opened(block); + drop(g); + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GuardFaults, 1); + let ns = waited.as_nanos().min(u128::from(u32::MAX)) as usize; + let held = (began.elapsed() - waited).as_nanos() as u64; + crate::faultbook::note(crate::faultbook::What::Fault, block, opened << 32 | ns, held); + crate::faultbook::note(crate::faultbook::What::Site, r.ExceptionAddress as usize, block, 0); + } + return EXCEPTION_CONTINUE_EXECUTION; + } + } if writable(at) { return EXCEPTION_CONTINUE_EXECUTION; } - // (The runtime wants the guards to end a change.) - drop(g); match ours { Some(exit) => fail(exit), None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION, @@ -2452,7 +2789,7 @@ mod tests { assert!(written.contains(&(p / PAGE + 1, now))); assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now)); } - assert!(!guards().held.contains(&(p / BLOCK + 1))); + assert!(!guards().held.contains(p / BLOCK + 1)); drop(writing); ask(); assert!((0..3).all(known) == holes); @@ -2460,12 +2797,12 @@ mod tests { let _changing = title_memory_remapping(); title_memory_unmapping(p, BLOCK); ask(); - assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + assert!(!known(0) && !guards().held.contains(p / BLOCK)); } ask(); assert!((0..3).all(known) == holes); title_memory_freed(p, BLOCK); - assert!(!known(0) && !guards().held.contains(&(p / BLOCK))); + assert!(!known(0) && !guards().held.contains(p / BLOCK)); title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our placeholders. unsafe { @@ -2495,7 +2832,7 @@ mod tests { assert!(writes(at, at + BLOCK, true).is_some()); { let g = guards(); - assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK))); + assert!(!g.protected.contains(at / BLOCK) && !g.clean.contains(at / BLOCK)); } assert!(!published(at, at + BLOCK)); // SAFETY: our view. @@ -2554,7 +2891,7 @@ mod tests { assert!(holes.iter().all(|page| written.contains(page)), "copied every time"); as_made(); let g = guards(); - assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block))); + assert!(holes.iter().all(|&block| !g.held.contains(block) && !g.absent.contains(block))); } writing(p, BLOCK); as_made(); @@ -2575,7 +2912,7 @@ mod tests { let noted = |block: usize| { let g = guards(); let block = p / BLOCK + block; - g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block) + g.protected.contains(block) || g.clean.contains(block) || g.absent.contains(block) }; assert!(guard(p, p + 3 * BLOCK).is_some()); assert!(noted(0) && noted(1) && noted(2)); @@ -3031,6 +3368,203 @@ mod tests { drop_views(section, &[one, two], SIZE); } + /// A write opens the view it goes through and no other: the others stay + /// read-only, are told as written, and take writes of their own. + #[test] + fn a_write_opens_the_view_it_goes_through() { + let (section, one, two) = two_views(BLOCK); + let page = |view: usize| view / PAGE; + for view in [one, two] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + } + // SAFETY (all): a view, opened by the handler. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert!(writable(two) && !writable(one)); + unsafe { ((one + 8) as *mut u8).write(1) }; + assert!(writable(two) && writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)])); + // Written at the view that was left as it was, after the other. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)]), "not clean, though never opened"); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(two, two + BLOCK), Some(vec![page(two)])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + // Of a page that was told at one view, a kernel write to the other + // finds it open. + unsafe { ((two + 8) as *mut u8).write(1) }; + assert!(!writable(one)); + writing(one, 8); + assert!(writable(one)); + drop_views(section, &[one, two], BLOCK); + } + + /// A block the title has just written is not made read-only, and is told + /// as written at each asking, at every view of it, until it has rested. + #[test] + fn a_block_just_written_rests() { + let (section, one, two) = two_views(BLOCK); + let page = one / PAGE; + let rests = |rests: bool| REST_IN_TEST.set(std::time::Duration::from_secs(if rests { 3600 } else { 0 })); + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + rests(true); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new()), "nothing written: as it was"); + // SAFETY (all): a view, opened by the handler. + unsafe { ((two + 8) as *mut u8).write(1) }; + for _ in 0..3 { + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert!(writable(two), "no fault for the next write"); + assert!(writes(two, two + BLOCK, true).is_some() && !published(two, two + BLOCK) && !published(one, one + BLOCK)); + unsafe { ((two + 8) as *mut u8).write(1) }; + } + rests(false); + assert_eq!(guard(one, one + BLOCK), Some(vec![page])); + assert!(!writable(two) && !writable(one)); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + } + + /// What is put in beside a guard is told at every view, once, and the + /// block stays read-only; until it has had its share. + #[test] + fn what_the_title_puts_in_beside_a_guard_is_told() { + let (section, one, two) = two_views(BLOCK); + crate::title_memory_section(section, BLOCK as u64, true); + let page = |view: usize| view / PAGE; + for view in [one, two] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + } + assert!(writes(one, one + BLOCK, true).is_some() && writes(two, two + BLOCK, true).is_some()); + put_count(one / BLOCK).store(0, std::sync::atomic::Ordering::Relaxed); + let put = |byte: u8| loop { + // SAFETY: a byte of the section's only page. + let done = put_beside(one / BLOCK, 1, |delta| unsafe { ((one + 100).wrapping_add(delta) as *mut u8).write(byte) }); + // (Other tests hold changes of mapping.) + if done != Beside::Cannot { + return done; + } + }; + for round in 1..4 { + assert_eq!(put(round), Beside::Done); + // SAFETY: the view the title reads it by. + assert_eq!(unsafe { ((two + 100) as *const u8).read_volatile() }, round); + assert!(!writable(one) && !writable(two) && !published(one, one + BLOCK) && !published(two, two + BLOCK)); + for view in [two, one] { + assert_eq!(guard(view, view + BLOCK), Some(vec![page(view)])); + assert_eq!(guard(view, view + BLOCK), Some(Vec::new())); + } + } + for _ in 0..crate::titlewrite::MOST { + assert_eq!(put(9), Beside::Done); + } + assert_eq!(put(9), Beside::Full); + // A refresh between gives it its share again. + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(put(9), Beside::Done); + // Opened by a fault, it is told by that. + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + // SAFETY: a view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(put_beside(one / BLOCK, 1, |_| panic!("it is not guarded")), Beside::Cannot); + assert_eq!(guard(one, one + BLOCK), Some(vec![page(one)])); + assert_eq!(guard(one, one + BLOCK), Some(Vec::new())); + drop_views(section, &[one, two], BLOCK); + crate::title_memory_section_gone(section); + } + + /// Stores that fault, and copies, as the title makes them: what is there + /// after, the block's guard and what the next asking says. + #[test] + fn stores_and_copies_of_the_title_leave_the_guard() { + use std::sync::atomic::{AtomicU32, Ordering}; + unsafe extern "system-unwind" fn real(to: *mut u8, from: *const u8, n: usize) -> *mut u8 { + // SAFETY: by the caller. + unsafe { std::ptr::copy(from, to, n) }; + to + } + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + crate::title_memory_section(section, SIZE as u64, true); + let pages = |view: usize| vec![view / PAGE, view / PAGE + 1]; + assert_eq!(guard(one, one + SIZE), Some(pages(one))); + assert_eq!(guard(two, two + SIZE), Some(pages(two))); + let copy = crate::titlewrite::import("memcpy", real as *const () as usize); + crate::titlewrite::ON_IN_TEST.set(true); + let copy = if copy == real as *const () as usize { + crate::titlewrite::copy_for_test(real as *const () as usize) + } else { + copy + }; + // SAFETY: of that signature. + let copy: unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8 = unsafe { std::mem::transmute(copy) }; + // No change of mapping meanwhile but the other tests' moments of it: + // a store that meets one opens the block, as before. + let mut kept = 0; + let quiet = || { + while title_memory_reading_now().is_none() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + for round in 1..200u32 { + quiet(); + // SAFETY (all): words of the view. + unsafe { ((one + 64) as *mut u32).write_volatile(round) }; + let was = unsafe { AtomicU32::from_ptr((two + 64) as *mut u32) }.fetch_sub(1, Ordering::SeqCst); + assert_eq!((was, unsafe { ((one + 64) as *const u32).read_volatile() }), (round, round - 1)); + let bytes = vec![round as u8; 3000 + round as usize]; + // Over the end of the first block. + assert_eq!(unsafe { copy((one + BLOCK - 1000) as *mut u8, bytes.as_ptr(), bytes.len()) } as usize, one + BLOCK - 1000); + let there = unsafe { std::slice::from_raw_parts((two + BLOCK - 1000) as *const u8, bytes.len()) }; + assert!(there == bytes && unsafe { ((two + BLOCK + 2000 + round as usize) as *const u8).read_volatile() } != round as u8); + kept += usize::from(!writable(one) && !writable(two)); + for view in [one, two] { + assert_eq!(guard(view, view + SIZE), Some(pages(view)), "round {round}"); + assert_eq!(guard(view, view + SIZE), Some(Vec::new()), "round {round}"); + } + } + assert!(kept > 10, "the guard stayed {kept} times: {:?}", crate::titlewrite::DONE); + // Many stores to a block: it is opened. + quiet(); + for k in 0..20 { + unsafe { ((one + 128 + k * 4) as *mut u32).write_volatile(7) }; + } + assert!(writable(one)); + crate::titlewrite::ON_IN_TEST.set(false); + drop_views(section, &[one, two], SIZE); + crate::title_memory_section_gone(section); + } + + /// The set of blocks against another of the same. + #[test] + fn blocks_are_a_set() { + let (mut set, mut other) = (Blocks::new(), BTreeSet::new()); + let mut seed = 1u64; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for round in 0..40_000 { + // About the ends of pieces and words. + let block = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); + if next(3) == 0 { + assert_eq!(set.remove(block), other.remove(&block)); + } else { + assert_eq!(set.insert(block), other.insert(block)); + } + assert_eq!(set.contains(block), other.contains(&block)); + if round % 64 == 0 { + let a = [0, 63, Blocks::IN_PIECE, 3 * Blocks::IN_PIECE - 70][next(4)] + next(140); + let b = a + [next(10), next(300), 2 * Blocks::IN_PIECE + next(100)][next(3)]; + assert!(set.range(a..b).eq(other.range(a..b).copied()), "{a}..{b}"); + assert!(set.range(a..).eq(other.range(a..).copied()) && set.range(..).eq(other.iter().copied())); + assert!(set.range(a..=b).eq(other.range(a..=b).copied())); + assert_eq!(set.len(), other.len()); + } + } + assert_eq!(set.range(5..usize::MAX).next(), other.range(5..).next().copied()); + } + /// What is known of a block by its bit is so at every view of its page: /// the write through one takes the bits of all. #[test] @@ -3251,7 +3785,14 @@ mod many_askers_tests { /// again between. #[test] fn no_write_to_views_is_lost_between_askers() { - writes_to_views_are_not_lost::<1>(); + writes_to_views_are_not_lost::<1>(0); + } + + /// The same with blocks that rest after a write ([`super::rest`]). + #[test] + fn no_write_to_resting_views_is_lost_between_askers() { + writes_to_views_are_not_lost::<1>(50); + writes_to_views_are_not_lost::<3>(50); } /// The same of pages shown at three addresses, each of which has copies @@ -3261,10 +3802,11 @@ mod many_askers_tests { /// for one address only, `VICTORY_VIEW_GUARD=0`.) #[test] fn no_write_through_another_view_is_lost_between_askers() { - writes_to_views_are_not_lost::<3>(); + writes_to_views_are_not_lost::<3>(0); } - fn writes_to_views_are_not_lost() { + fn writes_to_views_are_not_lost(rest: u64) { + let rest = std::time::Duration::from_micros(rest); const PAGES: usize = 12; const THREADS: usize = 8; // SAFETY: views of a section of our own. @@ -3289,9 +3831,11 @@ mod many_askers_tests { }; let by_bits = std::sync::atomic::AtomicUsize::new(0); let past = std::sync::atomic::AtomicUsize::new(0); + let title_beside = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|s| { if VIEWS > 1 { s.spawn(move || { + super::REST_IN_TEST.set(rest); let mut last = [0u64; VIEWS]; for round in 0..300usize { let (page, asked) = (round * 5 % PAGES, round % VIEWS); @@ -3319,8 +3863,9 @@ mod many_askers_tests { }); } for t in 0..THREADS { - let (by_bits, past) = (&by_bits, &past); + let (by_bits, past, title_beside) = (&by_bits, &past, &title_beside); s.spawn(move || { + super::REST_IN_TEST.set(rest); let mut last = [[0u64; PAGES]; VIEWS]; let mut seed = t as u64 * 7919 + 1; let mut next = |n: usize| { @@ -3340,6 +3885,21 @@ mod many_askers_tests { let word = through + page * PAGE + t * 8; // SAFETY (both): as above. // (Waited for: other tests hold changes of mapping.) + // (Some as a copy of the title's, or a store of it, does.) + if next(3) == 0 + && super::put_beside(word / PAGE, 1, |delta| unsafe { + (word.wrapping_add(delta) as *mut u64).write_volatile(3); + }) == super::Beside::Done + { + title_beside.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); + assert!(number > last[page], "page {page}, beside: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + continue; + } let reading = (next(3) == 0).then(super::title_memory_reading); let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); if let Some(to) = beside { @@ -3377,6 +3937,7 @@ mod many_askers_tests { }); assert!(by_bits.into_inner() > 0, "the bits answered none"); assert!(past.into_inner() > 0, "nothing was put past the guards"); + assert!(title_beside.into_inner() > 0, "nothing of the title's was put in beside the guards"); // (The view stays: at its address other tests' memory would be told // of these writes.) } diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 3c217d8..5199821 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -79,6 +79,14 @@ impl HostPolicy { return None; } let address = imp::resolve(dll, symbol)?; + // The title's copies of memory look where they write. + #[cfg(windows)] + if let ImportSymbol::Name { name, .. } = symbol { + let ours = victory_gpu::titlewrite::import(name, address); + if ours != address { + return Some(ours); + } + } // With a timeline asked for, what threads wait with is wrapped. #[cfg(all(windows, feature = "diagnostics"))] if let ImportSymbol::Name { name, .. } = symbol {