Merge day/faults
This commit is contained in:
commit
53ab99577f
10 files changed
+1791
-132
No files matched your search
@@ -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.
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! A book of the title's write faults on guarded view memory
|
||||
//! (`VICTORY_FAULT_BOOK=<file>`; 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 `<file>.<n>.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<Vec<Record>> = 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<Option<(String, Vec<u64>)>> = OnceLock::new();
|
||||
static BEGAN: OnceLock<std::time::Instant> = 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::<u8>(), 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Views> = Mutex::new(Views {
|
||||
/// Read by many threads at once (write faults, landings), changed when the
|
||||
/// runtime maps or unmaps.
|
||||
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
|
||||
views: BTreeMap::new(),
|
||||
pages: BTreeMap::new(),
|
||||
pages_twice: 0,
|
||||
@@ -289,14 +290,18 @@ static VIEWS: Mutex<Views> = 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<usize> {
|
||||
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<usize> {
|
||||
(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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Result<bool, u32>> = 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<bool> = 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));
|
||||
}
|
||||
}
|
||||
@@ -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<Store> {
|
||||
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<u64> {
|
||||
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<u64> {
|
||||
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<usize> = 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 ; <code> ; 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<u8>> = 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);
|
||||
}
|
||||
}
|
||||
+683
-122
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user