Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions crates/xcl/src/eh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -970,6 +970,58 @@ pub fn start_probes() {
});
}

/// Free address space for helpers within reach of a `call rel32` from `near`: the nearest
/// `size` bytes (a multiple of 64 KiB) above it, else below; committed, readable, writable and
/// executable. 0: none.
pub(crate) unsafe fn alloc_near(near: usize, size: usize) -> usize {
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
const REACH: usize = 0x7000_0000;
let query = |at: usize| -> Option<(usize, usize, bool)> {
let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
(VirtualQuery(at as *const _, &mut mbi, std::mem::size_of::<MEMORY_BASIC_INFORMATION>()) != 0)
.then(|| (mbi.BaseAddress as usize, (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize), mbi.State == MEM_FREE))
};
let take = |p: usize| VirtualAlloc(p as *const _, size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize;
let mut at = near & !0xFFFF;
for _ in 0..4096 {
let Some((_, end, free)) = query(at) else { break };
if at - (near & !0xFFFF) > REACH {
break;
}
if free && at + size <= end {
let p = take(at);
if p != 0 {
return p;
}
}
let next = end.saturating_add(0xFFFF) & !0xFFFF;
if next <= at {
break;
}
at = next;
}
let mut at = near & !0xFFFF;
for _ in 0..4096 {
if at <= 0x2_0000 || (near & !0xFFFF) - at > REACH {
break;
}
let Some((base, _, free)) = query(at - 1) else { break };
let p = at.saturating_sub(size);
if free && p >= base {
let p = take(p);
if p != 0 {
return p;
}
}
let next = base & !0xFFFF;
if next >= at {
break;
}
at = next;
}
0
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod insn;
pub mod inspect;
pub mod launcher;
pub mod loader;
pub mod maskmov;
pub mod modules;
pub mod pe;
pub mod preflight;
Expand Down
223 changes: 223 additions & 0 deletions crates/xcl/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result<Arc<MappedModule>, String>
}
}

// 3b. masked stores, where the host cannot resume one after a fault
if masked_store_helpers() {
let code: Vec<(u32, u32)> = pe.sections.iter().filter(|s| s.characteristics & 0x2000_0000 != 0).map(|s| (s.va, s.mapped_size())).collect();
let ex = pe.dir(pe::DIR_EXCEPTION);
unsafe { replace_masked_stores(base, size, &code, (ex.rva, ex.size), &name) };
}

let exports = OwnedExports::from_pe(&pe).unwrap_or_default();
let module = Arc::new(MappedModule {
name: name.clone(),
Expand Down Expand Up @@ -234,6 +241,105 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result<Arc<MappedModule>, String>
Ok(module)
}

/// Whether a title's AVX masked stores are replaced by calls to helpers (`maskmov`):
/// `XCL_MASKED_STORES=1` / `0`, else only where the title's code runs through Rosetta 2
/// (`util::rosetta`) – on a CPU the instructions are left alone.
fn masked_store_helpers() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| match std::env::var("XCL_MASKED_STORES") {
Ok(v) => v.trim() != "0",
Err(_) => crate::util::rosetta(),
})
}

/// Replaces the masked stores of the image mapped at `base` (relocated, its sections still
/// writable, none of its code run yet) by calls to helpers that store an element at a time
/// (`maskmov::plan`), and says how many. `code` is the (RVA, length) of each executable
/// section, `unwind` the (RVA, size) of the image's function table. The helpers get memory of
/// their own within a call's reach of the image, with unwind data, read-only once written.
/// One log line says what was done, and one for each pattern left as it is.
unsafe fn replace_masked_stores(base: usize, size: usize, code: &[(u32, u32)], unwind: (u32, u32), name: &str) -> usize {
use crate::maskmov::{self, Kind};
use windows_sys::Win32::System::Diagnostics::Debug::{FlushInstructionCache, RtlAddFunctionTable, IMAGE_RUNTIME_FUNCTION_ENTRY};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let started = std::time::Instant::now();
let image = std::slice::from_raw_parts(base as *const u8, size);
let functions: Vec<(u32, u32)> = image
.get(unwind.0 as usize..(unwind.0 as usize).saturating_add(unwind.1 as usize))
.unwrap_or_default()
.chunks_exact(12)
.map(|e| (u32::from_le_bytes([e[0], e[1], e[2], e[3]]), u32::from_le_bytes([e[4], e[5], e[6], e[7]])))
.collect();
let plan = maskmov::plan(image, base as u64, code, &functions);
for (rva, why) in plan.skipped.iter().take(32) {
crate::xlog_warn!("{name}: the bytes of a masked store at +{rva:#x} are left as they are ({why:?})");
}
if plan.sites.is_empty() {
if !plan.skipped.is_empty() {
crate::xlog_warn!("{name}: {} byte pattern(s) of a masked store, none replaced", plan.skipped.len());
}
return 0;
}
// helpers, their shared unwind data, one function entry each
let unwind_at = (plan.code.len() + 15) & !15;
let table_at = unwind_at + maskmov::UNWIND_INFO.len();
let entry = std::mem::size_of::<IMAGE_RUNTIME_FUNCTION_ENTRY>();
let pool_size = (table_at + plan.helpers.len() * entry + 0xFFFF) & !0xFFFF;
let pool = crate::eh::alloc_near(base + size, pool_size);
if pool == 0 {
crate::xlog_error!("{name}: no memory near the image for the helpers of {} masked stores – they stay, and one that faults past its first element ends the process on this host", plan.sites.len());
return 0;
}
std::ptr::copy_nonoverlapping(plan.code.as_ptr(), pool as *mut u8, plan.code.len());
std::ptr::copy_nonoverlapping(maskmov::UNWIND_INFO.as_ptr(), (pool + unwind_at) as *mut u8, maskmov::UNWIND_INFO.len());
let table = (pool + table_at) as *mut IMAGE_RUNTIME_FUNCTION_ENTRY;
for (k, &(start, end)) in plan.helpers.iter().enumerate() {
let e = &mut *table.add(k);
(e.BeginAddress, e.EndAddress) = (start, end);
e.Anonymous.UnwindInfoAddress = unwind_at as u32;
}
let (mut done, mut leaf, mut far) = ([0usize; 4], 0usize, 0usize);
for s in &plan.sites {
let site = base + s.rva as usize;
let Some(call) = maskmov::call_site(site as u64, s.store.len, (pool + s.helper as usize) as u64) else {
far += 1;
continue;
};
std::ptr::copy_nonoverlapping(call.as_ptr(), site as *mut u8, s.store.len as usize);
done[Kind::ALL.iter().position(|&k| k == s.store.kind).unwrap_or(0)] += 1;
leaf += s.leaf as usize;
}
let mut old = 0u32;
VirtualProtect(pool as *const c_void, pool_size, PAGE_EXECUTE_READ, &mut old);
FlushInstructionCache(GetCurrentProcess(), pool as *const c_void, pool_size);
if !RtlAddFunctionTable(table, plan.helpers.len() as u32, pool as u64) {
crate::xlog_warn!("{name}: RtlAddFunctionTable for the masked-store helpers at {pool:#x} failed");
}
MASKED_STORE_HELPERS.lock().unwrap().push((pool, pool + plan.code.len()));
let kinds: Vec<String> = Kind::ALL.iter().zip(done).filter(|(_, n)| *n != 0).map(|(k, n)| format!("{n} {}", k.name())).collect();
crate::xlog_info!(
"{name}: {} masked stores ({}) call {} helpers at {pool:#x}..{:#x} that store an element at a time – the host cannot resume one that faults past its first element (XCL_MASKED_STORES=0 leaves them){}{}{}; {} ms",
done.iter().sum::<usize>(),
kinds.join(", "),
plan.helpers.len(),
pool + plan.code.len(),
if leaf != 0 { format!("; {leaf} of them in functions without unwind data") } else { String::new() },
if plan.skipped.is_empty() { String::new() } else { format!("; {} pattern(s) left as they are", plan.skipped.len()) },
if far != 0 { format!("; {far} out of a call's reach and left") } else { String::new() },
started.elapsed().as_millis()
);
done.iter().sum()
}

/// The helpers' memory, per image: (start, end).
static MASKED_STORE_HELPERS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());

/// Whether `addr` is in a masked-store helper – code of XCL's that runs in place of an
/// instruction of the title's (a crash line then names the store by the return address).
pub fn in_masked_store_helper(addr: usize) -> bool {
MASKED_STORE_HELPERS.try_lock().is_ok_and(|g| g.iter().any(|r| (r.0..r.1).contains(&addr)))
}

unsafe fn tls_install(m: &MappedModule, template: usize, len: usize, total: u64, index_ptr: *mut u32) -> Result<(), String> {
let k = crate::tls::install(&m.name, template, len, total, index_ptr, &cache_dir())?;
// the title's executable: slot 0, as a process's executable has it
Expand Down Expand Up @@ -522,4 +628,121 @@ mod tests {
assert!(modules::find_mapped_by_name(&key).is_none(), "attempt {attempt}: still registered");
}
}
/// What the masked-store test's exception handler saw: the page it repairs (start, end),
/// faults repaired, the faulting instruction, and the frame one step up from it by the
/// unwind data (RIP, the word 0x30 bytes above RSP, RAX, RCX, RDX, R8).
#[cfg(target_arch = "x86_64")]
static FAULT: [std::sync::atomic::AtomicUsize; 10] = [const { std::sync::atomic::AtomicUsize::new(0) }; 10];

#[cfg(target_arch = "x86_64")]
unsafe extern "system" fn repair_and_unwind(info: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 {
use windows_sys::Win32::System::Diagnostics::Debug::{RtlLookupFunctionEntry, RtlVirtualUnwind};
let rec = &*(*info).ExceptionRecord;
let at = rec.ExceptionInformation[1];
if rec.ExceptionCode as u32 != 0xC000_0005 || !(FAULT[0].load(Ordering::Relaxed)..FAULT[1].load(Ordering::Relaxed)).contains(&at) {
return 0;
}
let mut ctx = *(*info).ContextRecord;
FAULT[3].store(ctx.Rip as usize, Ordering::Relaxed);
let mut image = 0u64;
let entry = RtlLookupFunctionEntry(ctx.Rip, &mut image, std::ptr::null_mut());
if !entry.is_null() {
let (mut data, mut frame) = (std::ptr::null_mut(), 0u64);
RtlVirtualUnwind(0, image, ctx.Rip, entry, &mut ctx, &mut data, &mut frame, std::ptr::null_mut());
// (the stack is read now: the frames are gone when the test looks)
let above = ((ctx.Rsp + 0x28 + 8) as *const u64).read();
for (slot, v) in [ctx.Rip, above, ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.R8].into_iter().enumerate() {
FAULT[4 + slot].store(v as usize, Ordering::Relaxed);
}
}
let mut old = 0;
VirtualProtect((at & !0xFFF) as *const c_void, 0x1000, PAGE_READWRITE, &mut old);
FAULT[2].fetch_add(1, Ordering::Relaxed);
-1 // EXCEPTION_CONTINUE_EXECUTION
}

/// A mapped image with a masked store in a function and one in a leaf function behind it:
/// both become calls to helpers near the image. Run, the function stores what the
/// instruction would; a fault in the helper (the second page is read-only) is in memory
/// XCL names, has unwind data that leads back to the store with the title's registers, and
/// is resumed when the page has been made writable.
#[test]
#[cfg(target_arch = "x86_64")]
fn masked_stores_of_a_mapped_image_call_helpers_with_unwind_data() {
use crate::maskmov::exec::{defined, has_avx2, point, set_mask, Rng, State, STACK_AT};
use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, RemoveVectoredExceptionHandler};
if !has_avx2() {
eprintln!("SKIPPED: this CPU has no AVX2");
return;
}
extern "C" {
fn xcl_maskmov_test_run(state: *mut State, code: *const u8);
}
const STORE: [u8; 6] = [0xC4, 0xE2, 0x4D, 0x8E, 0x04, 0x90]; // vpmaskmovd [rax + 4 * rdx], ymm6, ymm0
const LEAF: [u8; 7] = [0xC4, 0x22, 0xC5, 0x8E, 0x44, 0x04, 0x40]; // vpmaskmovq [rsp + r8 + 0x40], ymm7, ymm8
unsafe {
let base = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize;
let put = |at: usize, bytes: &[u8]| std::ptr::copy_nonoverlapping(bytes.as_ptr(), (base + at) as *mut u8, bytes.len());
std::ptr::write_bytes(base as *mut u8, 0xCC, 0x1_0000);
// 0x1000: lea rsp, [rsp - 0x28]; STORE; lea rsp, [rsp + 0x28]; ret – and its function entry
put(0x1000, &[0x48, 0x8D, 0x64, 0x24, 0xD8]);
put(0x1005, &STORE);
put(0x100B, &[0x48, 0x8D, 0x64, 0x24, 0x28, 0xC3]);
put(0x3000, &[0x00, 0x10, 0, 0, 0x11, 0x10, 0, 0, 0, 0, 0, 0]);
// 0x1020, a leaf function: LEAF; ret
put(0x1020, &LEAF);
put(0x1027, &[0xC3]);
assert_eq!(replace_masked_stores(base, 0x1_0000, &[(0x1000, 0x1000)], (0x3000, 12), "test image"), 2);
let site = std::slice::from_raw_parts((base + 0x1005) as *const u8, 6);
assert_eq!((site[0], site[5]), (0xE8, 0x90), "a call and a NOP");
let helper = base + 0x100A + i32::from_le_bytes([site[1], site[2], site[3], site[4]]) as isize as usize;
assert!(in_masked_store_helper(helper) && helper.abs_diff(base) < 0x7000_0000 && !in_masked_store_helper(base + 0x1005));
assert_eq!(*((base + 0x1020) as *const u8), 0xE8);
assert_eq!(std::slice::from_raw_parts((base + 0x1025) as *const u8, 3), [0x90, 0x90, 0xC3]);

// the function, with its store across a writable and a read-only page
let pages = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize;
let s = crate::maskmov::decode(&STORE).unwrap();
let mut rng = Rng(0x0BAD_C0DE_600D_F00D);
let st = {
let mut st = rng.state(true);
set_mask(&s, &mut st, 0xB7);
point(&s, &mut st, pages + 0x1000 - 12, 9);
st
};
let mut old = 0;
VirtualProtect((pages + 0x1000) as *const c_void, 0x1000, PAGE_READONLY, &mut old);
FAULT[0].store(pages, Ordering::Relaxed);
FAULT[1].store(pages + 0x2000, Ordering::Relaxed);
let handler = AddVectoredExceptionHandler(1, Some(repair_and_unwind));
let mut out = st.clone();
xcl_maskmov_test_run(&mut out, (base + 0x1000) as *const u8);
RemoveVectoredExceptionHandler(handler);
assert_eq!(out, st, "registers, flags, vectors and stack are as they were");
assert_eq!(((pages + 0x1000 - 12) as *const [u8; 32]).read()[..], defined(&s, &st, &[0; 32])[..]);
let seen: Vec<usize> = FAULT.iter().map(|v| v.load(Ordering::Relaxed)).collect();
assert_eq!(seen[2], 1, "one fault, at the first element on the read-only page");
assert!(in_masked_store_helper(seen[3]), "the fault is in the helper: {:#x}", seen[3]);
assert!(crate::modules::describe_address(seen[3]).contains("masked-store helper"));
// one frame up: back in the function right behind the call, RSP as at the store (the
// function's 0x28 bytes and its return address below the caller's two pointers),
// and the title's RAX, RCX, RDX and R8
assert_eq!(seen[4], base + 0x100A, "unwound RIP");
assert_eq!(seen[5], &out as *const State as usize, "unwound RSP");
assert_eq!(seen[6..10], [st.gpr[0] as usize, st.gpr[1] as usize, st.gpr[2] as usize, st.gpr[8] as usize]);

// the leaf function: the store goes to the stack, 0x40 bytes above its RSP
let s = crate::maskmov::decode(&LEAF).unwrap();
let mut st = rng.state(false);
set_mask(&s, &mut st, 0b0110);
st.gpr[8] = 0x10;
let mut out = st.clone();
xcl_maskmov_test_run(&mut out, (base + 0x1020) as *const u8);
let at = 0x40 + 0x10 - STACK_AT as usize;
let stored = defined(&s, &st, &st.stack[at..at + 32]);
st.stack[at..at + 32].copy_from_slice(&stored);
assert_eq!(out, st);
VirtualFree(pages as *mut c_void, 0, MEM_RELEASE);
}
}
}
Loading
Loading