diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 484c90a..6fa7971 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1203,6 +1203,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 index 9fca8fa..1b0db43 100644 --- a/crates/victory-gpu/src/faultbook.rs +++ b/crates/victory-gpu/src/faultbook.rs @@ -32,8 +32,11 @@ pub(crate) enum What { Alias = 6, /// A fault on block `a` that someone else had opened; b: nanoseconds. Open = 7, - /// Blocks `[a, b)` were opened ahead of the title's writes. - Ahead = 8, + /// 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)] diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 8679e68..28f570e 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -565,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 1147880..f725253 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -78,6 +78,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/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 7d98205..1c790d2 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -791,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) } } @@ -883,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 { - if g.clean.contains(*page) || g.held.contains(*page) { - PUBLISHED.set(*page); + for &page in pages { + if g.clean.contains(page) || g.held.contains(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); + } } } } @@ -1240,6 +1338,7 @@ impl Guards { self.opened.clear(); } } + put_count(block).store(0, std::sync::atomic::Ordering::Relaxed); self.opened.insert(block, std::time::Instant::now()); } } @@ -1434,7 +1533,7 @@ 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); @@ -1471,7 +1570,7 @@ fn guard(start: usize, end: usize) -> Option> { // clean. let mut written = Vec::new(); for word in first / 64..last.div_ceil(64) { - let known = g.clean.word(word) | g.absent.word(word); + 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; @@ -1486,12 +1585,20 @@ fn guard(start: usize, end: usize) -> Option> { 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. + // 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 cover(&mut g, block, block + 1) { g.clean.insert(block); } @@ -2330,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 @@ -2353,6 +2462,13 @@ pub(crate) fn install() { } let at = r.ExceptionInformation[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 @@ -2380,6 +2496,7 @@ pub(crate) fn install() { 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; } @@ -3308,6 +3425,116 @@ mod tests { 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() { @@ -3604,6 +3831,7 @@ 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 || { @@ -3635,7 +3863,7 @@ 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]; @@ -3657,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 { @@ -3694,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 {