990 lines
29 KiB
Rust
990 lines
29 KiB
Rust
|
|
|
|
use std::sync::atomic::{
|
|
AtomicBool, AtomicPtr, AtomicU8, AtomicU64, AtomicUsize,
|
|
Ordering::{AcqRel, Acquire, Relaxed, Release},
|
|
};
|
|
|
|
pub fn on() -> bool {
|
|
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
|
|
|
*ON.get_or_init(|| std::env::var("EONACAT_XS_HEAP_HOOKS").is_ok_and(|v| v.trim() == "1"))
|
|
}
|
|
|
|
pub const RECORD: u8 = 1;
|
|
pub const OTHER: u8 = 2;
|
|
pub const FREED: u8 = 3;
|
|
|
|
const BLOCK: usize = 64 << 10;
|
|
|
|
const SLOT: usize = 32;
|
|
|
|
const LINE: usize = 64;
|
|
const SLOTS_A_BLOCK: usize = BLOCK / SLOT;
|
|
|
|
#[repr(C)]
|
|
pub struct Cells {
|
|
base: AtomicU64,
|
|
len: AtomicU64,
|
|
deltas: AtomicPtr<AtomicU64>,
|
|
slots: AtomicPtr<AtomicU8>,
|
|
blocks: AtomicPtr<AtomicU8>,
|
|
told: AtomicPtr<AtomicU8>,
|
|
any: AtomicU8,
|
|
_pad: [u8; 7],
|
|
}
|
|
|
|
const _: () = assert!(size_of::<Cells>() == 56);
|
|
|
|
static CELLS: Cells = Cells {
|
|
base: AtomicU64::new(0),
|
|
len: AtomicU64::new(0),
|
|
deltas: AtomicPtr::new(std::ptr::null_mut()),
|
|
slots: AtomicPtr::new(std::ptr::null_mut()),
|
|
blocks: AtomicPtr::new(std::ptr::null_mut()),
|
|
told: AtomicPtr::new(std::ptr::null_mut()),
|
|
any: AtomicU8::new(0),
|
|
_pad: [0; 7],
|
|
};
|
|
|
|
pub fn cells_address() -> usize {
|
|
std::ptr::from_ref(&CELLS) as usize
|
|
}
|
|
|
|
pub fn resolve_address() -> usize {
|
|
resolve as *const () as usize
|
|
}
|
|
|
|
struct Image {
|
|
base: usize,
|
|
size: usize,
|
|
stubs: Vec<(usize, usize, usize)>,
|
|
}
|
|
|
|
static IMAGE: std::sync::RwLock<Option<Image>> = std::sync::RwLock::new(None);
|
|
static HOOKED: AtomicBool = AtomicBool::new(false);
|
|
|
|
static MIRROR: AtomicPtr<AtomicU64> = AtomicPtr::new(std::ptr::null_mut());
|
|
|
|
fn mirror(base: u64, len: u64) {
|
|
let at = MIRROR.load(Acquire);
|
|
if at.is_null() {
|
|
return;
|
|
}
|
|
|
|
unsafe {
|
|
if len == 0 {
|
|
(*at.add(1)).store(0, Release);
|
|
}
|
|
(*at).store(base, Release);
|
|
(*at.add(1)).store(len, Release);
|
|
}
|
|
}
|
|
|
|
pub fn hooked(base: usize, size: usize, stubs: Vec<(usize, usize, usize)>, mirror_at: usize) {
|
|
MIRROR.store(mirror_at as *mut AtomicU64, Release);
|
|
let n = stubs.len();
|
|
stubs_made(base, size, stubs);
|
|
HOOKED.store(true, Release);
|
|
tracing::info!(
|
|
stores = n,
|
|
"heap hooks: the title's stores into its view heap are hooked; the heap's memory is guarded, a write no hook takes is traced (EONACAT_XS_HEAP_HOOKS; EONACAT_XS_HEAP_HOOKS_STRICT=1 stops the process there)"
|
|
);
|
|
}
|
|
|
|
pub(crate) fn stubs_made(base: usize, size: usize, stubs: Vec<(usize, usize, usize)>) {
|
|
let mut image = IMAGE.write().unwrap_or_else(|e| e.into_inner());
|
|
match image.as_mut() {
|
|
Some(image) => image.stubs.extend(stubs),
|
|
None => *image = Some(Image { base, size, stubs }),
|
|
}
|
|
}
|
|
|
|
pub fn refused(why: &str) {
|
|
tracing::warn!(
|
|
why,
|
|
"heap hooks: off for this executable, the view heap is synced by its pages (EONACAT_XS_HEAP_HOOKS=1)"
|
|
);
|
|
}
|
|
|
|
fn working() -> bool {
|
|
on() && HOOKED.load(Acquire)
|
|
}
|
|
|
|
struct Tables {
|
|
start: usize,
|
|
count: usize,
|
|
blocks: usize,
|
|
slots: &'static [AtomicU8],
|
|
marks: &'static [AtomicU8],
|
|
}
|
|
|
|
static ADOPTED: std::sync::RwLock<Option<Tables>> = std::sync::RwLock::new(None);
|
|
|
|
pub(crate) fn adopt(start: u64, count: u32) -> bool {
|
|
working() && adopt_now(start as usize, count as usize)
|
|
}
|
|
|
|
fn adopt_now(start: usize, count: usize) -> bool {
|
|
let mut adopted = ADOPTED.write().unwrap_or_else(|e| e.into_inner());
|
|
if adopted.is_some() {
|
|
tracing::info!(
|
|
start = format_args!("{start:#x}"),
|
|
count,
|
|
"heap hooks: another placed view heap, synced by its pages as before"
|
|
);
|
|
return false;
|
|
}
|
|
if !start.is_multiple_of(BLOCK) || count == 0 {
|
|
tracing::warn!(
|
|
start = format_args!("{start:#x}"),
|
|
count,
|
|
"heap hooks: a view heap that does not begin on 64 KiB, synced by its pages as before"
|
|
);
|
|
return false;
|
|
}
|
|
let len = count * SLOT;
|
|
let blocks = len.div_ceil(BLOCK);
|
|
|
|
let bytes =
|
|
|n: usize| -> &'static [AtomicU8] { Box::leak((0..n).map(|_| AtomicU8::new(0)).collect()) };
|
|
let deltas: &'static [AtomicU64] = Box::leak((0..=blocks).map(|_| AtomicU64::new(0)).collect());
|
|
let (slots, marks, told) = (
|
|
bytes(count + 1),
|
|
bytes((blocks + 1) * LINE),
|
|
bytes((blocks + 1) * LINE),
|
|
);
|
|
|
|
slots[..count].iter().for_each(|s| s.store(RECORD, Relaxed));
|
|
(0..blocks).for_each(|block| marks[block * LINE].store(1, Relaxed));
|
|
CELLS.deltas.store(deltas.as_ptr().cast_mut(), Release);
|
|
CELLS.slots.store(slots.as_ptr().cast_mut(), Release);
|
|
CELLS.blocks.store(marks.as_ptr().cast_mut(), Release);
|
|
CELLS.told.store(told.as_ptr().cast_mut(), Release);
|
|
CELLS.base.store(start as u64, Release);
|
|
|
|
CELLS.len.store(len as u64, Release);
|
|
mirror(start as u64, len as u64);
|
|
*adopted = Some(Tables {
|
|
start,
|
|
count,
|
|
blocks,
|
|
slots,
|
|
marks,
|
|
});
|
|
tracing::info!(
|
|
start = format_args!("{start:#x}"),
|
|
count,
|
|
blocks,
|
|
"heap hooks: the title's view heap is synced by what its hooked writers note, not by its pages; its memory stays guarded (EONACAT_XS_HEAP_HOOKS)"
|
|
);
|
|
true
|
|
}
|
|
|
|
pub(crate) fn let_go(start: u64) {
|
|
let mut adopted = ADOPTED.write().unwrap_or_else(|e| e.into_inner());
|
|
if adopted.as_ref().is_some_and(|t| t.start == start as usize) {
|
|
mirror(start, 0);
|
|
CELLS.len.store(0, Release);
|
|
*adopted = None;
|
|
tracing::info!(
|
|
start = format_args!("{start:#x}"),
|
|
"heap hooks: the hooked view heap went"
|
|
);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn adopted(start: u64) -> bool {
|
|
ADOPTED
|
|
.read()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.as_ref()
|
|
.is_some_and(|t| t.start == start as usize)
|
|
}
|
|
|
|
#[inline]
|
|
fn heap() -> (usize, usize) {
|
|
let len = CELLS.len.load(Acquire) as usize;
|
|
(CELLS.base.load(Relaxed) as usize, len)
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub(crate) fn hooked_heap() -> (usize, usize) {
|
|
heap()
|
|
}
|
|
|
|
#[inline]
|
|
fn touches(at: usize, n: usize) -> bool {
|
|
let (base, len) = heap();
|
|
len != 0 && n != 0 && at < base + len && base < at.saturating_add(n)
|
|
}
|
|
|
|
extern "system" fn resolve(block: u64) -> u64 {
|
|
std::panic::catch_unwind(|| way(block as usize)).unwrap_or(1)
|
|
}
|
|
|
|
fn way(block: usize) -> u64 {
|
|
let (base, len) = heap();
|
|
if len == 0 || block >= len.div_ceil(BLOCK) {
|
|
return 1;
|
|
}
|
|
let page = base + block * BLOCK;
|
|
|
|
let _reading = crate::watch::title_memory_reading();
|
|
let Some((ours, _)) = crate::inplace::beside_page(page) else {
|
|
|
|
COUNTS[NO_WAY].fetch_add(1, Relaxed);
|
|
return 1;
|
|
};
|
|
let delta = ours.wrapping_sub(page) as u64;
|
|
|
|
unsafe { (*CELLS.deltas.load(Acquire).add(block)).store(delta, Release) };
|
|
COUNTS[WAYS].fetch_add(1, Relaxed);
|
|
delta
|
|
}
|
|
|
|
fn ours(at: usize) -> usize {
|
|
let (base, _) = heap();
|
|
let block = (at - base) / BLOCK;
|
|
|
|
let known = unsafe { (*CELLS.deltas.load(Acquire).add(block)).load(Acquire) };
|
|
match if known == 0 { way(block) } else { known } {
|
|
1 => at,
|
|
delta => at.wrapping_add(delta as usize),
|
|
}
|
|
}
|
|
|
|
fn pieces(at: usize, n: usize, mut put: impl FnMut(usize, usize, usize)) {
|
|
let (base, len) = heap();
|
|
let mut offset = 0;
|
|
while offset < n {
|
|
let here = at + offset;
|
|
let piece = if len != 0 && here.wrapping_sub(base) < len {
|
|
let piece = (BLOCK - (here - base) % BLOCK)
|
|
.min(n - offset)
|
|
.min(base + len - here);
|
|
put(ours(here), offset, piece);
|
|
piece
|
|
} else {
|
|
let piece = if len != 0 && here < base {
|
|
(base - here).min(n - offset)
|
|
} else {
|
|
n - offset
|
|
};
|
|
put(here, offset, piece);
|
|
piece
|
|
};
|
|
offset += piece;
|
|
}
|
|
}
|
|
|
|
fn note(at: usize, n: usize, note: u8) {
|
|
let (base, len) = heap();
|
|
let (from, to) = (at.max(base), at.saturating_add(n).min(base + len));
|
|
if len == 0 || from >= to {
|
|
return;
|
|
}
|
|
let (slots, marks, told) = (
|
|
CELLS.slots.load(Acquire),
|
|
CELLS.blocks.load(Acquire),
|
|
CELLS.told.load(Acquire),
|
|
);
|
|
|
|
unsafe {
|
|
for slot in (from - base) / SLOT..=(to - 1 - base) / SLOT {
|
|
(*slots.add(slot)).store(note, Release);
|
|
}
|
|
for block in (from - base) / BLOCK..=(to - 1 - base) / BLOCK {
|
|
(*marks.add(block * LINE)).store(1, Release);
|
|
if (*told.add(block * LINE)).swap(1, AcqRel) == 0 {
|
|
CELLS.any.store(1, Release);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn write(at: u64, bytes: &[u8]) -> bool {
|
|
let at = at as usize;
|
|
if !touches(at, bytes.len()) {
|
|
return false;
|
|
}
|
|
pieces(at, bytes.len(), |to, offset, n| {
|
|
|
|
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr().add(offset), to as *mut u8, n) };
|
|
});
|
|
note(at, bytes.len(), RECORD);
|
|
COUNTS[OURS].fetch_add(1, Relaxed);
|
|
true
|
|
}
|
|
|
|
pub(crate) unsafe fn copy(to: u64, from: u64, n: usize) -> bool {
|
|
let (to, from) = (to as usize, from as usize);
|
|
if !touches(to, n) {
|
|
return false;
|
|
}
|
|
|
|
let same = unsafe {
|
|
std::slice::from_raw_parts(to as *const u8, n)
|
|
== std::slice::from_raw_parts(from as *const u8, n)
|
|
};
|
|
if crate::toggled!("EONACAT_XS_SAME_RECORDS") && same {
|
|
return true;
|
|
}
|
|
|
|
let held: Vec<u8>;
|
|
let source = if from < to + n && to < from + n {
|
|
|
|
held = unsafe { std::slice::from_raw_parts(from as *const u8, n) }.to_vec();
|
|
held.as_ptr()
|
|
} else {
|
|
from as *const u8
|
|
};
|
|
pieces(to, n, |at, offset, len| {
|
|
|
|
unsafe { std::ptr::copy_nonoverlapping(source.add(offset), at as *mut u8, len) };
|
|
});
|
|
note(to, n, RECORD);
|
|
COUNTS[OURS].fetch_add(1, Relaxed);
|
|
true
|
|
}
|
|
|
|
static REAL: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3];
|
|
|
|
type CopyFn = unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8;
|
|
type SetFn = unsafe extern "system-unwind" fn(*mut u8, i32, usize) -> *mut u8;
|
|
|
|
pub fn import(name: &str, address: usize) -> usize {
|
|
let (which, ours) = match name {
|
|
"memcpy" => (0, copy_import as *const () as usize),
|
|
"memmove" => (1, move_import as *const () as usize),
|
|
"memset" => (2, set_import as *const () as usize),
|
|
_ => return address,
|
|
};
|
|
if !on() {
|
|
return address;
|
|
}
|
|
REAL[which].store(address, Relaxed);
|
|
ours
|
|
}
|
|
|
|
unsafe extern "system-unwind" fn copy_import(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
|
|
|
|
unsafe { copied(to, from, n, REAL[0].load(Relaxed)) }
|
|
}
|
|
|
|
unsafe extern "system-unwind" fn move_import(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
|
|
|
|
unsafe { copied(to, from, n, REAL[1].load(Relaxed)) }
|
|
}
|
|
|
|
#[inline]
|
|
unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 {
|
|
|
|
let real: CopyFn = unsafe { std::mem::transmute(real) };
|
|
if !touches(to as usize, n) {
|
|
|
|
return unsafe { real(to, from, n) };
|
|
}
|
|
let held: Vec<u8>;
|
|
let source = if (from as usize) < to as usize + n && (to as usize) < from as usize + n {
|
|
|
|
held = unsafe { std::slice::from_raw_parts(from, n) }.to_vec();
|
|
held.as_ptr()
|
|
} else {
|
|
from
|
|
};
|
|
pieces(to as usize, n, |at, offset, len| {
|
|
|
|
unsafe { real(at as *mut u8, source.add(offset), len) };
|
|
});
|
|
note(to as usize, n, RECORD);
|
|
COUNTS[COPIES].fetch_add(1, Relaxed);
|
|
to
|
|
}
|
|
|
|
unsafe extern "system-unwind" fn set_import(to: *mut u8, byte: i32, n: usize) -> *mut u8 {
|
|
|
|
let real: SetFn = unsafe { std::mem::transmute(REAL[2].load(Relaxed)) };
|
|
if !touches(to as usize, n) {
|
|
|
|
return unsafe { real(to, byte, n) };
|
|
}
|
|
pieces(to as usize, n, |at, _, len| {
|
|
|
|
unsafe { real(at as *mut u8, byte, len) };
|
|
});
|
|
note(to as usize, n, RECORD);
|
|
COUNTS[COPIES].fetch_add(1, Relaxed);
|
|
to
|
|
}
|
|
|
|
pub(crate) fn changed(at: usize, len: usize) {
|
|
let (base, n) = heap();
|
|
let (from, to) = (at.max(base), at.saturating_add(len).min(base + n));
|
|
if n == 0 || from >= to {
|
|
return;
|
|
}
|
|
note(from, to - from, RECORD);
|
|
COUNTS[CHANGED].fetch_add(1, Relaxed);
|
|
}
|
|
|
|
pub(crate) fn views_gone(at: usize, len: usize) {
|
|
let (base, n) = heap();
|
|
let (from, to) = (at.max(base), at.saturating_add(len).min(base + n));
|
|
if n == 0 || from >= to {
|
|
return;
|
|
}
|
|
let deltas = CELLS.deltas.load(Acquire);
|
|
for block in (from - base) / BLOCK..=(to - 1 - base) / BLOCK {
|
|
|
|
unsafe { (*deltas.add(block)).store(0, Release) };
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
pub(crate) fn tell_watch() {
|
|
if !HOOKED.load(Relaxed) || CELLS.any.load(Relaxed) == 0 || CELLS.any.swap(0, AcqRel) == 0 {
|
|
return;
|
|
}
|
|
let (base, len) = heap();
|
|
let told = CELLS.told.load(Acquire);
|
|
let slots = CELLS.slots.load(Acquire);
|
|
if len == 0 || told.is_null() {
|
|
return;
|
|
}
|
|
let count = len / SLOT;
|
|
for block in 0..len.div_ceil(BLOCK) {
|
|
|
|
let mark = unsafe { &*told.add(block * LINE) };
|
|
if mark.load(Relaxed) != 0 && mark.swap(0, AcqRel) != 0 {
|
|
|
|
let mut parts = taken_parts(base, block);
|
|
if !slots.is_null() {
|
|
parts |= parts_of_slots(block, count, |slot| {
|
|
|
|
let state = unsafe { (*slots.add(slot)).load(Acquire) };
|
|
state != 0
|
|
});
|
|
}
|
|
if parts_told() && parts != 0 {
|
|
crate::watch::written_beside_parts(base + block * BLOCK, parts);
|
|
COUNTS[TOLD_PARTS].fetch_add(u64::from(parts.count_ones()), Relaxed);
|
|
} else {
|
|
crate::watch::written_beside(base + block * BLOCK);
|
|
}
|
|
COUNTS[TOLD].fetch_add(1, Relaxed);
|
|
}
|
|
}
|
|
}
|
|
|
|
const PART: usize = 4 << 10;
|
|
|
|
fn part_of(i: usize) -> u16 {
|
|
1 << ((i * SLOT) / PART)
|
|
}
|
|
|
|
fn parts_of_slots(block: usize, count: usize, written: impl Fn(usize) -> bool) -> u16 {
|
|
let first = block * SLOTS_A_BLOCK;
|
|
let mut parts = 0;
|
|
for i in 0..SLOTS_A_BLOCK.min(count.saturating_sub(first)) {
|
|
if written(first + i) {
|
|
parts |= part_of(i);
|
|
}
|
|
}
|
|
parts
|
|
}
|
|
|
|
fn parts_told() -> bool {
|
|
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
|
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_HEAP_HOOKS_PARTS").is_none_or(|v| v != "0"))
|
|
}
|
|
|
|
static PARTS_TAKEN: std::sync::Mutex<(usize, Vec<u16>)> = std::sync::Mutex::new((0, Vec::new()));
|
|
|
|
fn parts_seen(start: usize, block: usize, parts: u16) {
|
|
note_parts(&mut PARTS_TAKEN.lock().unwrap_or_else(|e| e.into_inner()), start, block, parts);
|
|
}
|
|
|
|
fn taken_parts(start: usize, block: usize) -> u16 {
|
|
take_parts(&mut PARTS_TAKEN.lock().unwrap_or_else(|e| e.into_inner()), start, block)
|
|
}
|
|
|
|
fn note_parts(t: &mut (usize, Vec<u16>), start: usize, block: usize, parts: u16) {
|
|
if t.0 != start {
|
|
*t = (start, Vec::new());
|
|
}
|
|
if t.1.len() <= block {
|
|
t.1.resize(block + 1, 0);
|
|
}
|
|
t.1[block] |= parts;
|
|
}
|
|
|
|
fn take_parts(t: &mut (usize, Vec<u16>), start: usize, block: usize) -> u16 {
|
|
if t.0 != start {
|
|
return 0;
|
|
}
|
|
t.1.get_mut(block).map_or(0, std::mem::take)
|
|
}
|
|
|
|
pub(crate) fn reguard(start: u64, take: impl Fn(usize, usize) -> Vec<(usize, usize)>) {
|
|
let (base, len) = heap();
|
|
if len == 0 || base != start as usize {
|
|
return;
|
|
}
|
|
let (first, last) = (base / BLOCK, (base + len).div_ceil(BLOCK));
|
|
if (first..last).all(|block| crate::watch::guards_any(block * BLOCK, 1)) {
|
|
return;
|
|
}
|
|
let open = crate::watch::unguarded(first, last);
|
|
let mut runs: Vec<(usize, usize)> = Vec::new();
|
|
for block in open {
|
|
match runs.last_mut() {
|
|
Some((_, end)) if *end == block => *end += 1,
|
|
_ => runs.push((block, block + 1)),
|
|
}
|
|
}
|
|
for (from, to) in runs {
|
|
COUNTS[REGUARDED].fetch_add((to - from) as u64, Relaxed);
|
|
for (at, end) in take(from * BLOCK, to * BLOCK) {
|
|
note(at, end - at, RECORD);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn take(start: u64) -> Option<Vec<(u32, u32)>> {
|
|
let adopted = ADOPTED.read().unwrap_or_else(|e| e.into_inner());
|
|
let t = adopted.as_ref().filter(|t| t.start == start as usize)?;
|
|
let mut runs: Vec<(u32, u32)> = Vec::new();
|
|
let mut seen = [0u64; 4];
|
|
let mut blocks = 0;
|
|
for block in 0..t.blocks {
|
|
let mark = &t.marks[block * LINE];
|
|
|
|
if mark.load(Relaxed) == 0 || mark.swap(0, AcqRel) == 0 {
|
|
continue;
|
|
}
|
|
blocks += 1;
|
|
let first = block * SLOTS_A_BLOCK;
|
|
for (i, slot) in t.slots[first..(first + SLOTS_A_BLOCK).min(t.count)]
|
|
.iter()
|
|
.enumerate()
|
|
{
|
|
if slot.load(Relaxed) == 0 {
|
|
continue;
|
|
}
|
|
let state = slot.swap(0, AcqRel);
|
|
|
|
if state != 0 {
|
|
parts_seen(t.start, block, part_of(i));
|
|
}
|
|
seen[usize::from(state.min(3))] += 1;
|
|
if state != RECORD {
|
|
continue;
|
|
}
|
|
let index = (first + i) as u32;
|
|
match runs.last_mut() {
|
|
Some((at, n))
|
|
if *at + *n == index && !(index as usize).is_multiple_of(SLOTS_A_BLOCK) =>
|
|
{
|
|
*n += 1
|
|
}
|
|
_ => runs.push((index, 1)),
|
|
}
|
|
}
|
|
}
|
|
for (count, n) in [
|
|
(RECORDS, seen[1]),
|
|
(OTHERS, seen[2]),
|
|
(FREES, seen[3]),
|
|
(BLOCKS, blocks),
|
|
(RUNS, runs.len() as u64),
|
|
(TAKES, 1),
|
|
] {
|
|
COUNTS[count].fetch_add(n, Relaxed);
|
|
}
|
|
Some(runs)
|
|
}
|
|
|
|
fn strict() -> bool {
|
|
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
|
*ON.get_or_init(|| std::env::var("EONACAT_XS_HEAP_HOOKS_STRICT").is_ok_and(|v| v.trim() == "1"))
|
|
}
|
|
|
|
struct Writer {
|
|
stack: Vec<usize>,
|
|
count: u64,
|
|
recent: u64,
|
|
blocks: std::collections::BTreeSet<usize>,
|
|
first: u64,
|
|
last: u64,
|
|
at: usize,
|
|
region: Option<String>,
|
|
}
|
|
|
|
pub(crate) const HEAP_WRITER: u8 = 0;
|
|
pub(crate) const POOL_WRITER: u8 = 1;
|
|
|
|
static WRITERS: std::sync::Mutex<std::collections::BTreeMap<(u8, usize, usize), Writer>> =
|
|
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
|
|
|
static TRACE: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);
|
|
|
|
pub fn trace_to(path: std::path::PathBuf) {
|
|
*TRACE.lock().unwrap_or_else(|e| e.into_inner()) = Some(path);
|
|
}
|
|
|
|
fn dynamic(
|
|
rip: usize,
|
|
context: *const windows_sys::Win32::System::Diagnostics::Debug::CONTEXT,
|
|
heap_at: usize,
|
|
) {
|
|
traced(HEAP_WRITER, rip, context, heap_at, || None);
|
|
COUNTS[DYNAMIC].fetch_add(1, Relaxed);
|
|
changed(heap_at / BLOCK * BLOCK, BLOCK);
|
|
}
|
|
|
|
pub(crate) fn traced(
|
|
kind: u8,
|
|
rip: usize,
|
|
context: *const windows_sys::Win32::System::Diagnostics::Debug::CONTEXT,
|
|
at: usize,
|
|
region: impl FnOnce() -> Option<String>,
|
|
) {
|
|
let frame = crate::frame::current();
|
|
let caller = caller(context);
|
|
let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner());
|
|
let w = writers
|
|
.entry((kind, rip, caller))
|
|
.or_insert_with(|| Writer {
|
|
stack: Vec::new(),
|
|
count: 0,
|
|
recent: 0,
|
|
blocks: Default::default(),
|
|
first: frame,
|
|
last: frame,
|
|
at,
|
|
region: region(),
|
|
});
|
|
|
|
if w.count < 4 && w.stack.len() < 2 {
|
|
w.stack = stack(context, 16);
|
|
}
|
|
w.count += 1;
|
|
w.recent += 1;
|
|
w.last = frame;
|
|
if w.blocks.len() < 4096 {
|
|
w.blocks.insert(at / BLOCK);
|
|
}
|
|
}
|
|
|
|
fn stack(
|
|
context: *const windows_sys::Win32::System::Diagnostics::Debug::CONTEXT,
|
|
most: usize,
|
|
) -> Vec<usize> {
|
|
use windows_sys::Win32::System::Diagnostics::Debug::{
|
|
RtlLookupFunctionEntry, RtlVirtualUnwind, UNW_FLAG_NHANDLER,
|
|
};
|
|
let mut out = Vec::new();
|
|
if context.is_null() {
|
|
return out;
|
|
}
|
|
|
|
let mut copy = unsafe { *context };
|
|
while out.len() < most && copy.Rip != 0 {
|
|
out.push(copy.Rip as usize);
|
|
let mut base = 0u64;
|
|
|
|
let entry = unsafe { RtlLookupFunctionEntry(copy.Rip, &mut base, std::ptr::null_mut()) };
|
|
if entry.is_null() {
|
|
let mut back = 0usize;
|
|
|
|
let read = crate::host::read_into(copy.Rsp as *const u8, unsafe {
|
|
std::slice::from_raw_parts_mut((&raw mut back).cast::<u8>(), 8)
|
|
});
|
|
if !read {
|
|
break;
|
|
}
|
|
copy.Rip = back as u64;
|
|
copy.Rsp += 8;
|
|
continue;
|
|
}
|
|
let (mut data, mut frame) = (std::ptr::null_mut(), 0u64);
|
|
|
|
unsafe {
|
|
RtlVirtualUnwind(
|
|
UNW_FLAG_NHANDLER,
|
|
base,
|
|
copy.Rip,
|
|
entry,
|
|
&mut copy,
|
|
&mut data,
|
|
&mut frame,
|
|
std::ptr::null_mut(),
|
|
)
|
|
};
|
|
}
|
|
out
|
|
}
|
|
|
|
pub(crate) fn writers_line(kind: u8) -> String {
|
|
let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner());
|
|
let mut v: Vec<(u64, u64, usize, usize, usize)> = writers
|
|
.iter()
|
|
.filter(|(key, _)| key.0 == kind)
|
|
.map(|(&(_, rip, caller), w)| (w.recent, w.count, rip, caller, w.blocks.len()))
|
|
.collect();
|
|
writers
|
|
.iter_mut()
|
|
.filter(|(key, _)| key.0 == kind)
|
|
.for_each(|(_, w)| w.recent = 0);
|
|
drop(writers);
|
|
v.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
|
|
v.iter()
|
|
.filter(|w| w.0 != 0)
|
|
.take(12)
|
|
.map(|&(recent, count, rip, caller, blocks)| {
|
|
format!(
|
|
"{} from {} {recent} ({count} in all, {blocks} blocks)",
|
|
place(rip),
|
|
place(caller)
|
|
)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("; ")
|
|
}
|
|
|
|
pub fn write_trace() {
|
|
let Some(path) = TRACE.lock().unwrap_or_else(|e| e.into_inner()).clone() else {
|
|
return;
|
|
};
|
|
write_trace_of(HEAP_WRITER, &path);
|
|
write_trace_of(POOL_WRITER, &path.with_file_name("pool-writers.tsv"));
|
|
}
|
|
|
|
fn write_trace_of(kind: u8, path: &std::path::Path) {
|
|
#[allow(clippy::type_complexity)]
|
|
let rows: Vec<(
|
|
usize,
|
|
usize,
|
|
Vec<usize>,
|
|
u64,
|
|
usize,
|
|
u64,
|
|
u64,
|
|
usize,
|
|
Option<String>,
|
|
)> = WRITERS
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.iter()
|
|
.filter(|(key, _)| key.0 == kind)
|
|
.map(|(&(_, rip, caller), w)| {
|
|
(
|
|
rip,
|
|
caller,
|
|
w.stack.clone(),
|
|
w.count,
|
|
w.blocks.len(),
|
|
w.first,
|
|
w.last,
|
|
w.at,
|
|
w.region.clone(),
|
|
)
|
|
})
|
|
.collect();
|
|
if rows.is_empty() {
|
|
return;
|
|
}
|
|
let buffers: Vec<(u64, u64, bool)> = crate::shadow::spans()
|
|
.into_iter()
|
|
.filter(|s| !s.2)
|
|
.collect();
|
|
let mut out =
|
|
String::from("site\tcaller\tstack\tcount\tblocks\tfirst_frame\tlast_frame\tregion\n");
|
|
for (rip, caller, stack, count, blocks, first, last, at, region) in rows {
|
|
let region = match region {
|
|
Some(region) => region,
|
|
None if buffers
|
|
.iter()
|
|
.any(|&(s, n, _)| (at as u64).wrapping_sub(s) < n) =>
|
|
{
|
|
"tail".into()
|
|
}
|
|
None => "persistent".into(),
|
|
};
|
|
let stack: Vec<String> = stack.iter().map(|&a| place(a)).collect();
|
|
out.push_str(&format!(
|
|
"{}\t{}\t{}\t{count}\t{blocks}\t{first}\t{last}\t{region}\n",
|
|
place(rip),
|
|
place(caller),
|
|
stack.join(" < ")
|
|
));
|
|
}
|
|
if let Err(e) = std::fs::write(path, out) {
|
|
tracing::warn!(path = %path.display(), %e, "heap hooks: the writers' trace could not be written");
|
|
}
|
|
}
|
|
|
|
pub(crate) fn guard_fault(
|
|
at: usize,
|
|
rip: usize,
|
|
context: *const windows_sys::Win32::System::Diagnostics::Debug::CONTEXT,
|
|
) {
|
|
let (base, len) = heap();
|
|
if len == 0 || !HOOKED.load(Relaxed) {
|
|
return;
|
|
}
|
|
let heap_at = if at.wrapping_sub(base) < len {
|
|
Some(at)
|
|
} else {
|
|
crate::inplace::pages_of(at / BLOCK * BLOCK)
|
|
.into_iter()
|
|
.find(|page| page.wrapping_sub(base) < len)
|
|
.map(|page| page + at % BLOCK)
|
|
};
|
|
let Some(heap_at) = heap_at else {
|
|
return;
|
|
};
|
|
if !strict() {
|
|
dynamic(rip, context, heap_at);
|
|
return;
|
|
}
|
|
let slot = (heap_at - base) / SLOT;
|
|
let writer = place(rip);
|
|
let caller = place(caller(context));
|
|
let through = if heap_at == at {
|
|
String::new()
|
|
} else {
|
|
format!(" (through another address of its page, {at:#x})")
|
|
};
|
|
tracing::error!(
|
|
writer,
|
|
caller,
|
|
slot,
|
|
at = format_args!("{heap_at:#x}"),
|
|
"heap hooks: a write into the hooked view heap that no hook took{through}; the process stops (EONACAT_XS_HEAP_HOOKS=1: hook this writer, or turn the hooks off)"
|
|
);
|
|
crate::host::fail(format_args!(
|
|
"heap hooks: {writer} (called from {caller}) wrote slot {slot} of the hooked view heap at {heap_at:#x}{through}, and no hook took it"
|
|
));
|
|
}
|
|
|
|
pub(crate) fn place(address: usize) -> String {
|
|
if let Some(image) = IMAGE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
|
if let Some(&(span, _, _)) = image
|
|
.stubs
|
|
.iter()
|
|
.find(|&&(_, stub, n)| address.wrapping_sub(stub) < n)
|
|
{
|
|
return format!("the stub of the hooked store at title+{span:#x}");
|
|
}
|
|
if address.wrapping_sub(image.base) < image.size {
|
|
return format!("title+{:#x}", address - image.base);
|
|
}
|
|
}
|
|
match crate::titlewrite::place(address) {
|
|
Some((image, offset)) => format!("{image}+{offset:#x}"),
|
|
None => format!("{address:#x}"),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn caller(
|
|
context: *const windows_sys::Win32::System::Diagnostics::Debug::CONTEXT,
|
|
) -> usize {
|
|
use windows_sys::Win32::System::Diagnostics::Debug::{
|
|
RtlLookupFunctionEntry, RtlVirtualUnwind, UNW_FLAG_NHANDLER,
|
|
};
|
|
if context.is_null() {
|
|
return 0;
|
|
}
|
|
|
|
let mut copy = unsafe { *context };
|
|
let mut base = 0u64;
|
|
|
|
let entry = unsafe { RtlLookupFunctionEntry(copy.Rip, &mut base, std::ptr::null_mut()) };
|
|
if entry.is_null() {
|
|
let mut back = 0usize;
|
|
|
|
let read = crate::host::read_into(copy.Rsp as *const u8, unsafe {
|
|
std::slice::from_raw_parts_mut((&raw mut back).cast::<u8>(), 8)
|
|
});
|
|
return if read { back } else { 0 };
|
|
}
|
|
let (mut data, mut frame) = (std::ptr::null_mut(), 0u64);
|
|
|
|
unsafe {
|
|
RtlVirtualUnwind(
|
|
UNW_FLAG_NHANDLER,
|
|
base,
|
|
copy.Rip,
|
|
entry,
|
|
&mut copy,
|
|
&mut data,
|
|
&mut frame,
|
|
std::ptr::null_mut(),
|
|
)
|
|
};
|
|
copy.Rip as usize
|
|
}
|
|
|
|
static COUNTS: [AtomicU64; 15] = [const { AtomicU64::new(0) }; 15];
|
|
const RECORDS: usize = 0;
|
|
const OTHERS: usize = 1;
|
|
const FREES: usize = 2;
|
|
const BLOCKS: usize = 3;
|
|
const RUNS: usize = 4;
|
|
const TAKES: usize = 5;
|
|
const REGUARDED: usize = 6;
|
|
const CHANGED: usize = 7;
|
|
const OURS: usize = 8;
|
|
const COPIES: usize = 9;
|
|
const WAYS: usize = 10;
|
|
const NO_WAY: usize = 11;
|
|
const TOLD: usize = 12;
|
|
const DYNAMIC: usize = 13;
|
|
|
|
const TOLD_PARTS: usize = 14;
|
|
|
|
pub(crate) fn line(frames: f64) {
|
|
if !on() {
|
|
return;
|
|
}
|
|
if !working() {
|
|
static SAID: std::sync::Once = std::sync::Once::new();
|
|
SAID.call_once(|| tracing::info!("heap hooks (EONACAT_XS_HEAP_HOOKS=1): not working, the title's stores were not hooked (the launcher's log says why)"));
|
|
return;
|
|
}
|
|
let c: [f64; 15] = std::array::from_fn(|i| COUNTS[i].swap(0, Relaxed) as f64 / frames);
|
|
tracing::info!(
|
|
"heap hooks (EONACAT_XS_HEAP_HOOKS=1) per frame: slots taken {:.0} records, {:.0} no records, {:.0} given back; {:.1} blocks in {:.0} runs, {:.1} takings; \
|
|
{:.2} blocks guarded again, {:.1} ranges changed by others; {:.0} records of ours, {:.0} title copies into the heap; {:.2} ways to our view found, {:.2} not; {:.1} blocks told to the watch ({:.1} of their 4 KiB parts, EONACAT_XS_HEAP_HOOKS_PARTS)",
|
|
c[RECORDS],
|
|
c[OTHERS],
|
|
c[FREES],
|
|
c[BLOCKS],
|
|
c[RUNS],
|
|
c[TAKES],
|
|
c[REGUARDED],
|
|
c[CHANGED],
|
|
c[OURS],
|
|
c[COPIES],
|
|
c[WAYS],
|
|
c[NO_WAY],
|
|
c[TOLD],
|
|
c[TOLD_PARTS]
|
|
);
|
|
|
|
let writers = writers_line(HEAP_WRITER);
|
|
if !writers.is_empty() {
|
|
tracing::info!(
|
|
"heap hooks: writes no hook took, {:.1} per frame, taken and traced (EONACAT_XS_HEAP_HOOKS_STRICT=1: stop instead): {writers}",
|
|
c[DYNAMIC]
|
|
);
|
|
}
|
|
static LINES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
if LINES.fetch_add(1, Relaxed) % 10 == 9 {
|
|
write_trace();
|
|
}
|
|
}
|
|
|