Merge day/faults
This commit is contained in:
commit
866b84d5ce
8 files changed
+438
-18
No files matched your search
@@ -68,6 +68,7 @@ pub fn run(
|
|||||||
// and their patched copy are not read again, and were held for the
|
// and their patched copy are not read again, and were held for the
|
||||||
// whole run (two blocks of 114.7 MB each for the title, in
|
// whole run (two blocks of 114.7 MB each for the title, in
|
||||||
// physical memory: run 65's memory map).
|
// physical memory: run 65's memory map).
|
||||||
|
let image_name = prepared.file_name();
|
||||||
drop(prepared);
|
drop(prepared);
|
||||||
drop(original);
|
drop(original);
|
||||||
victory_hle::runtime::set_main_image(image.base());
|
victory_hle::runtime::set_main_image(image.base());
|
||||||
@@ -162,6 +163,11 @@ pub fn run(
|
|||||||
}
|
}
|
||||||
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
|
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
|
||||||
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
|
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
|
||||||
|
if execute {
|
||||||
|
let size = image.info().size_of_image as usize;
|
||||||
|
// SAFETY: the image stays mapped, and nothing of it has run yet.
|
||||||
|
unsafe { victory_loader::write_sites::apply_asked(&image_name, image.base(), size) };
|
||||||
|
}
|
||||||
if !execute {
|
if !execute {
|
||||||
println!("not executing (pass --execute to start the title)");
|
println!("not executing (pass --execute to start the title)");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
|
|||||||
@@ -1210,11 +1210,13 @@ pub(crate) fn log(frames: f64) {
|
|||||||
"guards over several views of a page, since the start: {together} blocks guarded with their other views, \
|
"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"
|
{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] =
|
let [copies, blocks, opened, stores, unknown, full, stayed, copied_same] =
|
||||||
[0, 1, 2, 3, 4, 5].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed));
|
[0, 1, 2, 3, 4, 5, 6, 7].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed));
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \
|
"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"
|
{stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \
|
||||||
|
the busiest stores (left out/changed): {}",
|
||||||
|
crate::titlewrite::busiest()
|
||||||
);
|
);
|
||||||
// Where the wall clock of a frame goes: the phases of a frame, the
|
// 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
|
// processor time of the whole process, and what each submitting and
|
||||||
|
|||||||
@@ -32,8 +32,9 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed};
|
|||||||
/// Diagnostics, since the start: copies of the title's that put bytes beside
|
/// 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
|
/// the guards, blocks they did so in, blocks they opened instead; stores done
|
||||||
/// beside the guards, faulting stores not understood, and blocks opened
|
/// beside the guards, faulting stores not understood, and blocks opened
|
||||||
/// because too many came.
|
/// because too many came; stores and parts of copies that left the memory as
|
||||||
pub(crate) static DONE: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
|
/// it was, and were not made.
|
||||||
|
pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
|
||||||
|
|
||||||
fn add(what: usize) {
|
fn add(what: usize) {
|
||||||
DONE[what].fetch_add(1, Relaxed);
|
DONE[what].fetch_add(1, Relaxed);
|
||||||
@@ -141,7 +142,11 @@ unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8
|
|||||||
// SAFETY: by the caller.
|
// SAFETY: by the caller.
|
||||||
return unsafe { real(to, from, n) };
|
return unsafe { real(to, from, n) };
|
||||||
}
|
}
|
||||||
in_pieces(to as usize, n, |at, offset, len| {
|
let same = |at: usize, offset: usize, len: usize| {
|
||||||
|
// SAFETY: both are the title's, the one read-only by our hand, the other read by it next.
|
||||||
|
unsafe { std::slice::from_raw_parts(at as *const u8, len) == std::slice::from_raw_parts(from.add(offset), len) }
|
||||||
|
};
|
||||||
|
in_pieces(to as usize, n, same, |at, offset, len| {
|
||||||
// SAFETY: a part of what the title asked for; or the same bytes at
|
// SAFETY: a part of what the title asked for; or the same bytes at
|
||||||
// our view of the pages.
|
// our view of the pages.
|
||||||
unsafe { real(at as *mut u8, from.add(offset), len) };
|
unsafe { real(at as *mut u8, from.add(offset), len) };
|
||||||
@@ -156,7 +161,11 @@ unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u
|
|||||||
// SAFETY: the title's, as it asked for it.
|
// SAFETY: the title's, as it asked for it.
|
||||||
return unsafe { real(to, byte, n) };
|
return unsafe { real(to, byte, n) };
|
||||||
}
|
}
|
||||||
in_pieces(to as usize, n, |at, _, len| {
|
let same = |at: usize, _: usize, len: usize| {
|
||||||
|
// SAFETY: the title's, read-only by our hand.
|
||||||
|
unsafe { std::slice::from_raw_parts(at as *const u8, len) }.iter().all(|&there| there == byte as u8)
|
||||||
|
};
|
||||||
|
in_pieces(to as usize, n, same, |at, _, len| {
|
||||||
// SAFETY: as in `copied`.
|
// SAFETY: as in `copied`.
|
||||||
unsafe { real(at as *mut u8, byte, len) };
|
unsafe { real(at as *mut u8, byte, len) };
|
||||||
});
|
});
|
||||||
@@ -173,7 +182,10 @@ fn overlap(to: usize, from: usize, n: usize) -> bool {
|
|||||||
|
|
||||||
/// Does `[to, to + n)` block by block: `put(at, offset, len)` with the
|
/// Does `[to, to + n)` block by block: `put(at, offset, len)` with the
|
||||||
/// address to write at, the title's or ours.
|
/// address to write at, the title's or ours.
|
||||||
fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) {
|
///
|
||||||
|
/// What is there already (`same`, of a part in one guarded block) is not
|
||||||
|
/// written.
|
||||||
|
fn in_pieces(to: usize, n: usize, same: impl Fn(usize, usize, usize) -> bool, put: impl Fn(usize, usize, usize)) {
|
||||||
const BLOCK: usize = crate::watch::PAGE;
|
const BLOCK: usize = crate::watch::PAGE;
|
||||||
add(0);
|
add(0);
|
||||||
let mut offset = 0;
|
let mut offset = 0;
|
||||||
@@ -181,6 +193,11 @@ fn in_pieces(to: usize, n: usize, put: impl Fn(usize, usize, usize)) {
|
|||||||
let at = to + offset;
|
let at = to + offset;
|
||||||
let len = (BLOCK - at % BLOCK).min(n - offset);
|
let len = (BLOCK - at % BLOCK).min(n - offset);
|
||||||
if crate::watch::guards_any(at, len) {
|
if crate::watch::guards_any(at, len) {
|
||||||
|
if same(at, offset, len) {
|
||||||
|
add(7);
|
||||||
|
offset += len;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) {
|
match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) {
|
||||||
Beside::Done => {
|
Beside::Done => {
|
||||||
add(1);
|
add(1);
|
||||||
@@ -212,6 +229,84 @@ fn sparse(counts: u64) -> bool {
|
|||||||
full < 4 || full * 12 < done
|
full < 4 || full * 12 < done
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Faulting stores by their place in the title's code: the place, and how
|
||||||
|
/// many left the memory as it was (the low half) or did not (the high one).
|
||||||
|
static LEARNED: [(AtomicUsize, AtomicU64); 1 << 9] = [const { (AtomicUsize::new(0), AtomicU64::new(0)) }; 1 << 9];
|
||||||
|
|
||||||
|
/// A store at `rip` would leave the memory as it is, or not. With
|
||||||
|
/// `VICTORY_WRITE_SITES=<file>`, a place that can be made to look first
|
||||||
|
/// (`can_look`) and mostly left it is written into that file, for the next
|
||||||
|
/// start (`victory_loader::write_sites`).
|
||||||
|
fn learn(rip: usize, same: bool, can_look: bool) {
|
||||||
|
let slot = &LEARNED[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 55 & 511];
|
||||||
|
let there = slot.0.compare_exchange(0, rip, Relaxed, Relaxed).unwrap_or_else(|there| there);
|
||||||
|
if there != 0 && there != rip {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let counts = slot.1.fetch_add(if same { 1 } else { 1 << 32 }, Relaxed);
|
||||||
|
let (stayed, changed) = (counts & 0xffff_ffff, counts >> 32);
|
||||||
|
if !same || !can_look || stayed != 256 || changed * 4 > stayed {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// (Not here, under a fault of the title's.)
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let Some((image, offset)) = place(rip) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
use std::io::Write;
|
||||||
|
let line = format!("{image} {offset:x} or\n");
|
||||||
|
let known = std::fs::read_to_string(&file).unwrap_or_default();
|
||||||
|
if known.lines().any(|l| l == line.trim_end()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) {
|
||||||
|
let _ = file.write_all(line.as_bytes());
|
||||||
|
}
|
||||||
|
tracing::info!(image, offset = format_args!("{offset:#x}"), stayed, changed, "a write of the title's that mostly changes nothing, noted");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The file name of the image `address` is in, and where in it.
|
||||||
|
fn place(address: usize) -> Option<(String, usize)> {
|
||||||
|
use windows_sys::Win32::System::LibraryLoader::{
|
||||||
|
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW,
|
||||||
|
};
|
||||||
|
const FLAGS: u32 = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
|
||||||
|
let mut module = std::ptr::null_mut();
|
||||||
|
let mut name = [0u16; 1024];
|
||||||
|
// SAFETY: an address, and room for the answers.
|
||||||
|
let n = unsafe {
|
||||||
|
if GetModuleHandleExW(FLAGS, address as *const u16, &mut module) == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32)
|
||||||
|
} as usize;
|
||||||
|
let path = String::from_utf16_lossy(&name[..n]);
|
||||||
|
let file = path.rsplit(['\\', '/']).next()?.to_owned();
|
||||||
|
(!file.is_empty()).then(|| (file, address - module as usize))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The places with the most faulting stores, for the log: offset in its
|
||||||
|
/// image, how many left the memory as it was, how many did not.
|
||||||
|
#[cfg(feature = "diagnostics")]
|
||||||
|
pub(crate) fn busiest() -> String {
|
||||||
|
let mut all: Vec<(u64, u64, usize)> = LEARNED
|
||||||
|
.iter()
|
||||||
|
.map(|(rip, counts)| (counts.load(Relaxed), rip.load(Relaxed)))
|
||||||
|
.filter(|s| s.1 != 0)
|
||||||
|
.map(|(counts, rip)| (counts & 0xffff_ffff, counts >> 32, rip))
|
||||||
|
.collect();
|
||||||
|
all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0 + s.1));
|
||||||
|
let of = |&(stayed, changed, rip): &(u64, u64, usize)| {
|
||||||
|
let (image, offset) = place(rip).unwrap_or_default();
|
||||||
|
format!("{}+{offset:x} {stayed}/{changed}", image.chars().skip(14).take(4).collect::<String>())
|
||||||
|
};
|
||||||
|
all.iter().take(16).map(of).collect::<Vec<_>>().join(", ")
|
||||||
|
}
|
||||||
|
|
||||||
/// Does the store that faulted at `at`, a byte of a guarded block, beside the
|
/// 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).
|
/// 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 {
|
pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool {
|
||||||
@@ -221,13 +316,6 @@ pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug
|
|||||||
let rip = context.Rip as usize;
|
let rip = context.Rip as usize;
|
||||||
let site = site(rip);
|
let site = site(rip);
|
||||||
let counts = site.load(Relaxed);
|
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];
|
let mut code = [0u8; 15];
|
||||||
// (To the end of the page if the next is not there.)
|
// (To the end of the page if the next is not there.)
|
||||||
let left = 4096 - rip % 4096;
|
let left = 4096 - rip % 4096;
|
||||||
@@ -245,6 +333,23 @@ pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug
|
|||||||
add(4);
|
add(4);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
// SAFETY: a guarded block's, which can be read.
|
||||||
|
if let Some((same, flags)) = unsafe { store.same(context) } {
|
||||||
|
learn(rip, same, store.can_look(&code));
|
||||||
|
if same && crate::watch::nothing_put(store.at / BLOCK) {
|
||||||
|
context.EFlags = flags;
|
||||||
|
context.Rip += store.len as u64;
|
||||||
|
add(6);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 done = false;
|
let mut done = false;
|
||||||
let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| {
|
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.
|
// SAFETY: the bytes the title is storing to, at our view of them.
|
||||||
|
|||||||
@@ -382,6 +382,38 @@ unsafe fn change(at: usize, size: usize, locked: bool, f: impl Fn(u64) -> u64) -
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Store {
|
impl Store {
|
||||||
|
/// Whether it leaves the memory as it is, and what it leaves in the flags
|
||||||
|
/// then; `None` for those of which that is not asked (locked ones,
|
||||||
|
/// exchanges).
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// [`Store::size`] bytes can be read at `at`.
|
||||||
|
pub(super) unsafe fn same(&self, c: &CONTEXT) -> Option<(bool, u32)> {
|
||||||
|
if self.locked {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut there = [0u8; 32];
|
||||||
|
// SAFETY: by the caller.
|
||||||
|
unsafe { std::ptr::copy_nonoverlapping(self.at as *const u8, there.as_mut_ptr(), self.size) };
|
||||||
|
match self.op {
|
||||||
|
Op::Put(bytes) => Some((there[..self.size] == bytes[..self.size], c.EFlags)),
|
||||||
|
Op::Alu { alu, with, keeps } => {
|
||||||
|
let was = u64::from_le_bytes(there[..8].try_into().expect("eight bytes")) & mask(self.size);
|
||||||
|
let (value, flags) = arithmetic(alu, was, with, self.size, keeps, c.EFlags);
|
||||||
|
Some((value == was, flags))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the loader can make it look before it writes
|
||||||
|
/// (`victory_loader::write_sites`): an `or` of a byte with a constant, of
|
||||||
|
/// the five bytes a jump needs.
|
||||||
|
pub(super) fn can_look(&self, code: &[u8]) -> bool {
|
||||||
|
let at = usize::from(code[0] & 0xf0 == 0x40);
|
||||||
|
self.len >= 5 && code[at] == 0x80 && matches!(self.op, Op::Alu { alu: Alu::Or, .. })
|
||||||
|
}
|
||||||
|
|
||||||
/// Does it, with `to` for the address, and gives the registers what the
|
/// Does it, with `to` for the address, and gives the registers what the
|
||||||
/// instruction leaves in them (but the instruction pointer). `false`:
|
/// instruction leaves in them (but the instruction pointer). `false`:
|
||||||
/// nothing was done.
|
/// nothing was done.
|
||||||
|
|||||||
@@ -968,6 +968,15 @@ pub(crate) fn put_beside(block: usize, weight: u32, put: impl FnOnce(usize)) ->
|
|||||||
Beside::Done
|
Beside::Done
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A faulting store of the title's leaves `block` as it is: whether it may be
|
||||||
|
/// left out (until that has been so often, since the block was taken, that
|
||||||
|
/// the faults cost more than opening it).
|
||||||
|
pub(crate) fn nothing_put(block: usize) -> bool {
|
||||||
|
use std::sync::atomic::Ordering::Relaxed;
|
||||||
|
let count = put_count(block);
|
||||||
|
count.load(Relaxed) < crate::titlewrite::MOST && count.fetch_add(1, Relaxed) < crate::titlewrite::MOST
|
||||||
|
}
|
||||||
|
|
||||||
/// The title is about to write block by block around `at`: as by a fault.
|
/// The title is about to write block by block around `at`: as by a fault.
|
||||||
pub(crate) fn opened_for_writing(at: usize) {
|
pub(crate) fn opened_for_writing(at: usize) {
|
||||||
let mut g = guards();
|
let mut g = guards();
|
||||||
@@ -3524,6 +3533,15 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
assert!(kept > 10, "the guard stayed {kept} times: {:?}", crate::titlewrite::DONE);
|
assert!(kept > 10, "the guard stayed {kept} times: {:?}", crate::titlewrite::DONE);
|
||||||
|
// What is there already is not written: nothing to tell.
|
||||||
|
for k in 0..10 {
|
||||||
|
// SAFETY (all): as above.
|
||||||
|
unsafe { ((one + 64) as *mut u32).write_volatile(198) };
|
||||||
|
let same = unsafe { std::slice::from_raw_parts((one + BLOCK - 900) as *const u8, 1500) }.to_vec();
|
||||||
|
unsafe { copy((one + BLOCK - 900) as *mut u8, same.as_ptr(), same.len()) };
|
||||||
|
assert!(!writable(one) && !writable(two), "{k}");
|
||||||
|
}
|
||||||
|
assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
|
||||||
// Many stores to a block: it is opened.
|
// Many stores to a block: it is opened.
|
||||||
quiet();
|
quiet();
|
||||||
for k in 0..20 {
|
for k in 0..20 {
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ fn patches_clzero() -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `jmp rel32` at `at` to `to`, if it reaches.
|
/// `jmp rel32` at `at` to `to`, if it reaches.
|
||||||
fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
|
pub(crate) fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
|
||||||
let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?;
|
let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?;
|
||||||
let [a, b, c, d] = rel.to_le_bytes();
|
let [a, b, c, d] = rel.to_le_bytes();
|
||||||
Some([0xe9, a, b, c, d])
|
Some([0xe9, a, b, c, d])
|
||||||
@@ -111,10 +111,10 @@ fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option<Vec<u8>> {
|
|||||||
|
|
||||||
/// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used.
|
/// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used.
|
||||||
static STUBS: std::sync::Mutex<Option<(usize, usize)>> = std::sync::Mutex::new(None);
|
static STUBS: std::sync::Mutex<Option<(usize, usize)>> = std::sync::Mutex::new(None);
|
||||||
const STUBS_LEN: usize = 64 << 10;
|
pub(crate) const STUBS_LEN: usize = 64 << 10;
|
||||||
|
|
||||||
/// Memory for code within reach of a `jmp rel32` at `at`.
|
/// Memory for code within reach of a `jmp rel32` at `at`.
|
||||||
fn near(at: usize) -> Option<usize> {
|
pub(crate) fn near(at: usize) -> Option<usize> {
|
||||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
|
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
|
||||||
let at = at & !0xffff;
|
let at = at & !0xffff;
|
||||||
(0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| {
|
(0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| {
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ mod thunks;
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
mod tls;
|
mod tls;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
pub mod write_sites;
|
||||||
|
#[cfg(windows)]
|
||||||
mod windows;
|
mod windows;
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
//! Places in the title's code that set a bit of a byte which is nearly always set already, changed
|
||||||
|
//! at load to look first (`VICTORY_WRITE_SITES=<file>`; off without it).
|
||||||
|
//!
|
||||||
|
//! The title's threads raise flags in their objects at every use ("drawn this frame"): `or byte
|
||||||
|
//! [object+n], bit`. The objects lie in memory that copies for the card are kept of, and each such
|
||||||
|
//! write was a fault on a guarded page, a copy of its block and a guard again, for a byte that
|
||||||
|
//! stayed as it was (a fifth of a frame's write faults at one place, run faults-3). Here the
|
||||||
|
//! instruction becomes a jump to code of ours that reads the byte, leaves the flags the instruction
|
||||||
|
//! leaves, and runs the instruction only if the byte would change.
|
||||||
|
//!
|
||||||
|
//! The places are not ours to know: `victory-gpu` (`titlewrite`) finds them while the title runs,
|
||||||
|
//! by their faults, and writes them into that file, a line each: the image file's name, the place's
|
||||||
|
//! offset in it (hexadecimal). Nothing of the title's code is kept. What is not such an instruction
|
||||||
|
//! is left alone.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// An `or byte [m], constant` at the start of `code`: its length, the bytes that name its address
|
||||||
|
/// (prefix or 0, ModRM without its register field, what follows up to the constant), the constant.
|
||||||
|
fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> {
|
||||||
|
let mut at = 0;
|
||||||
|
let mut rex = 0;
|
||||||
|
if code.first()? & 0xf0 == 0x40 {
|
||||||
|
rex = code[0];
|
||||||
|
at = 1;
|
||||||
|
}
|
||||||
|
let (&op, &modrm) = (code.get(at)?, code.get(at + 1)?);
|
||||||
|
if op != 0x80 || modrm >> 3 & 7 != 1 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (mode, rm) = (modrm >> 6, modrm & 7);
|
||||||
|
// Not a register, nor the instruction pointer's neighbourhood.
|
||||||
|
if mode == 3 || mode == 0 && rm == 5 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let rest = at + 2;
|
||||||
|
let mut end = rest;
|
||||||
|
if rm == 4 {
|
||||||
|
let sib = *code.get(end)?;
|
||||||
|
// Not the stack, whose pointer is another in our code; a plain address is left too.
|
||||||
|
if sib & 7 == 4 && rex & 1 == 0 || sib & 7 == 5 && mode == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
end += 1;
|
||||||
|
}
|
||||||
|
end += match mode {
|
||||||
|
1 => 1,
|
||||||
|
2 => 4,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
let constant = *code.get(end)?;
|
||||||
|
Some((end + 1, rex, modrm, &code[rest..end], constant))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The code at `stub` for the instruction at `at` (`code` from there).
|
||||||
|
fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec<u8>)> {
|
||||||
|
let (len, rex, modrm, rest, constant) = or_byte(code)?;
|
||||||
|
if len < 5 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = vec![0x50, 0x51]; // push rax, push rcx
|
||||||
|
// movzx eax, byte [m] (the prefix's register field is none of it)
|
||||||
|
if rex & 0x43 != 0 {
|
||||||
|
out.push(rex & 0x43);
|
||||||
|
}
|
||||||
|
out.extend([0x0f, 0xb6, modrm & 0xc7]);
|
||||||
|
out.extend(rest);
|
||||||
|
out.extend([0x89, 0xc1]); // mov ecx, eax
|
||||||
|
out.extend([0xf7, 0xd1]); // not ecx
|
||||||
|
out.extend([0x81, 0xe1, constant, 0, 0, 0]); // and ecx, constant: the bits to be set
|
||||||
|
out.extend([0x0c, constant]); // or al, constant: the flags
|
||||||
|
let back = |out: &mut Vec<u8>| {
|
||||||
|
let from = stub + out.len();
|
||||||
|
out.extend(crate::console_insn::jump(from, at + len)?);
|
||||||
|
Some(())
|
||||||
|
};
|
||||||
|
let mut write = vec![0x59, 0x58]; // pop rcx, pop rax
|
||||||
|
write.extend(&code[..len]);
|
||||||
|
out.extend([0x67, 0xe3, u8::try_from(write.len() + 5).ok()?]); // jecxz past it
|
||||||
|
out.extend(write);
|
||||||
|
back(&mut out)?;
|
||||||
|
out.extend([0x59, 0x58]);
|
||||||
|
back(&mut out)?;
|
||||||
|
Some((len, out))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes the places of `list` that are in the image called `name`, mapped at `base` with `size`
|
||||||
|
/// bytes: how many.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// The image stays mapped, and no thread runs its code yet.
|
||||||
|
pub unsafe fn apply(name: &str, base: usize, size: usize, list: &str) -> usize {
|
||||||
|
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
|
||||||
|
use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
|
||||||
|
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||||
|
let mut room: Option<(usize, usize)> = None;
|
||||||
|
let mut done = 0;
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
for line in list.lines() {
|
||||||
|
let mut words = line.split_whitespace();
|
||||||
|
let (Some(image), Some(offset)) = (words.next(), words.next()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Ok(offset) = usize::from_str_radix(offset.trim_start_matches("0x"), 16) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !image.eq_ignore_ascii_case(name) || offset + 16 > size || !seen.insert(offset) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let at = base + offset;
|
||||||
|
if room.is_none() {
|
||||||
|
room = crate::console_insn::near(at).map(|place| (place, 0));
|
||||||
|
}
|
||||||
|
let Some((place, used)) = room.as_mut() else {
|
||||||
|
return done;
|
||||||
|
};
|
||||||
|
// SAFETY: sixteen bytes inside the image; what is not mapped in it is not named.
|
||||||
|
let code: [u8; 16] = unsafe { std::ptr::read_unaligned(at as *const _) };
|
||||||
|
let to = *place + *used;
|
||||||
|
let Some((len, body)) = stub(&code, at, to) else {
|
||||||
|
tracing::warn!(image, offset = format_args!("{offset:#x}"), "not a write of the kind that can be looked at first");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(jump) = crate::console_insn::jump(at, to) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if *used + body.len() > crate::console_insn::STUBS_LEN {
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
let mut old = 0;
|
||||||
|
// SAFETY: our own code memory, which nothing runs yet; then the instruction, whose page is
|
||||||
|
// made writable for it and put back, and which nothing runs either.
|
||||||
|
unsafe {
|
||||||
|
std::ptr::copy_nonoverlapping(body.as_ptr(), to as *mut u8, body.len());
|
||||||
|
if VirtualProtect(at as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
std::ptr::write_bytes(at as *mut u8, 0x90, len);
|
||||||
|
std::ptr::copy_nonoverlapping(jump.as_ptr(), at as *mut u8, jump.len());
|
||||||
|
VirtualProtect(at as *const _, len, old, &mut old);
|
||||||
|
FlushInstructionCache(GetCurrentProcess(), at as *const _, len);
|
||||||
|
}
|
||||||
|
*used += body.len().next_multiple_of(16);
|
||||||
|
done += 1;
|
||||||
|
}
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`apply`] with the file `VICTORY_WRITE_SITES` names.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// As [`apply`].
|
||||||
|
pub unsafe fn apply_asked(name: &str, base: usize, size: usize) {
|
||||||
|
let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Ok(list) = std::fs::read_to_string(Path::new(&file)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// SAFETY: by the caller.
|
||||||
|
let places = unsafe { apply(name, base, size, &list) };
|
||||||
|
tracing::info!(image = name, places, "writes of the title's that look first (VICTORY_WRITE_SITES)");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_can_be_looked_at_first() {
|
||||||
|
// or byte [r9+9eh], 1
|
||||||
|
let (len, rex, modrm, rest, constant) = or_byte(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1, 0, 0]).unwrap();
|
||||||
|
assert_eq!((len, rex, modrm, rest, constant), (8, 0x41, 0x89, &[0x9e, 0, 0, 0][..], 1));
|
||||||
|
// or byte [r9+31h], 80h; [rax+rcx*8+5]; [r12+5] (a base of its own)
|
||||||
|
assert_eq!(or_byte(&[0x41, 0x80, 0x49, 0x31, 0x80]).unwrap().0, 5);
|
||||||
|
assert_eq!(or_byte(&[0x80, 0x4c, 0xc8, 5, 1]).unwrap().0, 5);
|
||||||
|
assert_eq!(or_byte(&[0x41, 0x80, 0x4c, 0x24, 5, 1]).unwrap().0, 6);
|
||||||
|
// Of the stack, beside the instruction, a register's, another operation.
|
||||||
|
assert!(or_byte(&[0x80, 0x4c, 0x24, 5, 1]).is_none());
|
||||||
|
assert!(or_byte(&[0x80, 0x0d, 1, 0, 0, 0, 1]).is_none());
|
||||||
|
assert!(or_byte(&[0x80, 0xc9, 1]).is_none());
|
||||||
|
assert!(or_byte(&[0x80, 0x61, 5, 1, 0]).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The instruction in code of a test's, changed, run: the byte, the registers and the flags
|
||||||
|
/// are what it makes of them unchanged.
|
||||||
|
#[test]
|
||||||
|
fn a_changed_write_does_what_it_did() {
|
||||||
|
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualProtect};
|
||||||
|
type F = unsafe extern "system" fn(*mut u8, *mut [u64; 3]);
|
||||||
|
for (constant, with) in [(0x80u8, 0x49u8), (1, 0x49), (0x7f, 0x49), (0xff, 0x48), (0x10, 0x49)] {
|
||||||
|
// mov rax, rcx ; mov r9, rcx ; mov rcx, 1234h ; xor r10, r10 ; or byte [r9+31h | rax+31h], constant ;
|
||||||
|
// pushfq ; pop r10 ; mov [rdx], r10 ; mov [rdx+8], rax ; mov [rdx+16], rcx ; ret
|
||||||
|
let mut code = vec![0x48, 0x89, 0xc8, 0x49, 0x89, 0xc9, 0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0, 0x4d, 0x31, 0xd2];
|
||||||
|
let at = code.len();
|
||||||
|
if with == 0x49 {
|
||||||
|
code.extend([0x41, 0x80, 0x49, 0x31, constant]);
|
||||||
|
} else {
|
||||||
|
// (With a long address, for the five bytes.)
|
||||||
|
code.extend([0x80, 0x88, 0x31, 0, 0, 0, constant]);
|
||||||
|
}
|
||||||
|
code.extend([0x9c, 0x41, 0x5a, 0x4c, 0x89, 0x12, 0x48, 0x89, 0x42, 0x08, 0x48, 0x89, 0x4a, 0x10, 0xc3]);
|
||||||
|
// SAFETY: fresh memory for code, twice, one of them changed before it runs.
|
||||||
|
unsafe {
|
||||||
|
let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
|
||||||
|
assert_ne!(place, 0);
|
||||||
|
std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len());
|
||||||
|
let second = place + 0x1000;
|
||||||
|
std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len());
|
||||||
|
let mut old = 0;
|
||||||
|
VirtualProtect(second as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old);
|
||||||
|
let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at);
|
||||||
|
assert_eq!(apply("t.dll", second, 0x1000, &list), 1);
|
||||||
|
assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9);
|
||||||
|
let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second));
|
||||||
|
for was in 0..=255u8 {
|
||||||
|
let mut bytes = [[0u8; 0x40]; 2];
|
||||||
|
bytes[0][0x31] = was;
|
||||||
|
bytes[1][0x31] = was;
|
||||||
|
let mut out = [[0u64; 3]; 2];
|
||||||
|
plain(bytes[0].as_mut_ptr(), &mut out[0]);
|
||||||
|
changed(bytes[1].as_mut_ptr(), &mut out[1]);
|
||||||
|
assert_eq!(bytes[0], bytes[1], "{was:x} | {constant:x}");
|
||||||
|
out[0][1] = out[0][1].wrapping_sub(bytes[0].as_ptr() as u64);
|
||||||
|
out[1][1] = out[1][1].wrapping_sub(bytes[1].as_ptr() as u64);
|
||||||
|
// (AF is left as it likes.)
|
||||||
|
out[0][0] &= 0x8c5;
|
||||||
|
out[1][0] &= 0x8c5;
|
||||||
|
assert_eq!(out[0], out[1], "{was:x} | {constant:x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A byte that would not change is not written.
|
||||||
|
#[test]
|
||||||
|
fn a_byte_that_stays_is_not_written() {
|
||||||
|
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, VirtualAlloc, VirtualProtect};
|
||||||
|
// mov r9, rcx ; or byte [r9+31h], 80h ; ret
|
||||||
|
let code = [0x49, 0x89, 0xc9, 0x41, 0x80, 0x49, 0x31, 0x80, 0xc3];
|
||||||
|
// SAFETY: fresh memory for code and for a byte, which is read-only when the code runs.
|
||||||
|
unsafe {
|
||||||
|
let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
|
||||||
|
std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len());
|
||||||
|
assert_eq!(apply("t.dll", place, 0x10000, "t.dll 3"), 1);
|
||||||
|
let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
|
||||||
|
data.add(0x31).write(0x83);
|
||||||
|
let mut old = 0;
|
||||||
|
VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old);
|
||||||
|
let f: unsafe extern "system" fn(*mut u8) = std::mem::transmute(place);
|
||||||
|
f(data);
|
||||||
|
assert_eq!(data.add(0x31).read(), 0x83);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user