diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a4..c4b714ec9 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -618,14 +618,46 @@ unsafe fn name_thread(tid: u32, name: &[u16]) { } } +/// Bytes of a thread's stack (from RSP up) a thread dump keeps +const DUMP_STACK: usize = 0x4_0000; + +/// The stack from `rsp` up (to the end of its region, at most `buf.len()` bytes) copied to +/// `buf`: its length. Only system calls – no lock a suspended thread may hold. +unsafe fn copy_stack(rsp: u64, buf: &mut [u8]) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(rsp as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.State != MEM_COMMIT { + return None; + } + let n = (mbi.BaseAddress as usize + mbi.RegionSize).saturating_sub(rsp as usize).min(buf.len()); + let mut read = 0usize; + let cur = windows_sys::Win32::System::Threading::GetCurrentProcess(); + (n >= 8 && ReadProcessMemory(cur, rsp as *const c_void, buf.as_mut_ptr() as *mut c_void, n, &mut read) != 0 && read == n).then_some(n) +} + /// The return addresses of the frames from `ctx` on (its RIP first), unwound with the -/// functions' unwind data (registered for the title's images too); up to `n`. -unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, n: usize) -> Vec { +/// functions' unwind data (registered for the title's images too); up to `n`. `stack` is the +/// thread's stack from `ctx.Rsp` on, copied while it was stopped: the thread has gone on (or +/// ended) since, so the unwinding reads the copy – addresses into the stack are moved to it – +/// and ends where a frame would leave it. +unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, n: usize, stack: &[u8]) -> Vec { use windows_sys::Win32::System::Diagnostics::Debug::{RtlLookupFunctionEntry, RtlVirtualUnwind, UNW_FLAG_NHANDLER}; + let (orig, copy, len) = (ctx.Rsp, stack.as_ptr() as u64, stack.len() as u64); + let in_copy = |v: u64| v >= copy && v < copy + len; + let to_copy = |ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT| { + for r in [&mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, + &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, &mut ctx.R14, &mut ctx.R15] { + if *r >= orig && *r < orig + len { + *r = *r - orig + copy; + } + } + }; + to_copy(ctx); let mut out = Vec::new(); for _ in 0..n { let rip = ctx.Rip; - if rip == 0 { + if rip == 0 || !in_copy(ctx.Rsp) || ctx.Rsp + 8 > copy + len { break; } out.push(rip as usize); @@ -633,16 +665,22 @@ unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTE let f = RtlLookupFunctionEntry(rip, &mut base, std::ptr::null_mut()); if f.is_null() { // a leaf function: the return address is at RSP - if !crate::gpu::shader::readable(ctx.Rsp as usize, 8) { - break; - } ctx.Rip = (ctx.Rsp as *const u64).read_unaligned(); ctx.Rsp += 8; } else { + // a frame register (UNWIND_INFO byte 3, low nibble) has to point into the copy too + let info = (base + (*f).Anonymous.UnwindData as u64) as *const u8; + let fp = (*info.add(3) & 0xF) as usize; + let regs = [ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15]; + if fp != 0 && !in_copy(regs[fp]) { + break; + } let mut data = std::ptr::null_mut(); let mut frame = 0u64; RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, rip, f, ctx, &mut data, &mut frame, std::ptr::null_mut()); } + // registers restored from the copy hold addresses into the stack + to_copy(ctx); } out } @@ -661,6 +699,9 @@ pub fn dump_threads() { return; } let mut lines = Vec::new(); + // allocated before any thread is stopped: it may hold the heap's lock. (The slack past + // the copy: a frame's unwinding may read a little beyond where the copy ends.) + let mut stack = vec![0u8; DUMP_STACK + 0x1_0000]; let mut te: THREADENTRY32 = std::mem::zeroed(); te.dwSize = std::mem::size_of::() as u32; let mut ok = Thread32First(snap, &mut te) != 0; @@ -673,16 +714,18 @@ pub fn dump_threads() { struct Aligned(CONTEXT); let mut c: Aligned = std::mem::zeroed(); c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; - // only the context is taken while the thread is suspended: the unwinding - // (RtlLookupFunctionEntry), the module lookup (loader lock), the name and the - // formatting (heap) take locks the suspended thread may hold (#106) + // only the context and a copy of the stack are taken while the thread is + // suspended: the unwinding (RtlLookupFunctionEntry), the module lookup (loader + // lock), the name and the formatting (heap) take locks the suspended thread + // may hold (#106). The unwinding reads the copy: the thread goes on, or ends. + let mut len = 0; let got = SuspendThread(h) != u32::MAX && { - let ok = GetThreadContext(h, &mut c.0) != 0; + let ok = GetThreadContext(h, &mut c.0) != 0 && copy_stack(c.0.Rsp, &mut stack[..DUMP_STACK]).inspect(|&n| len = n).is_some(); ResumeThread(h); ok }; if got { - let frames: Vec = unwind(&mut c.0, 14).into_iter().map(modules::describe_address).collect(); + let frames: Vec = unwind(&mut c.0, 14, &stack[..len]).into_iter().map(modules::describe_address).collect(); lines.push(format!("thread {} '{}': {}", te.th32ThreadID, thread_name(h), frames.join(" < "))); } CloseHandle(h); @@ -974,6 +1017,47 @@ pub fn start_probes() { mod tests { use super::*; + /// recursion whose frames hold return addresses and saved registers that change as it runs + #[inline(never)] + fn churn_stack(depth: u32, seed: u64) -> u64 { + let local = std::hint::black_box([seed; 8]); + if depth == 0 { + return local.iter().fold(0u64, |a, &x| a.wrapping_add(x)); + } + churn_stack(depth - 1, seed.wrapping_mul(6364136223846793005).wrapping_add(depth as u64)) ^ local[depth as usize % 8] + } + + /// Thread dumps while threads run, start and end around them (#106: a dump read a near-null + /// address inside RtlVirtualUnwind). + #[test] + fn thread_dumps_while_threads_run_and_exit() { + use std::sync::atomic::AtomicBool; + static STOP: AtomicBool = AtomicBool::new(false); + let busy: Vec<_> = (0..4u64) + .map(|i| std::thread::spawn(move || { + let mut n = 0u64; + while !STOP.load(Ordering::Relaxed) { + n = n.wrapping_add(churn_stack((n % 40) as u32 + 1, n ^ i)); + } + n + })) + .collect(); + let churn: Vec<_> = (0..4u64) + .map(|i| std::thread::spawn(move || { + let mut n = 0u64; + while !STOP.load(Ordering::Relaxed) { + n = std::thread::spawn(move || churn_stack((n % 24) as u32 + 1, n ^ i)).join().unwrap(); + } + })) + .collect(); + for _ in 0..40 { + dump_threads(); + } + STOP.store(true, Ordering::Relaxed); + churn.into_iter().for_each(|t| t.join().unwrap()); + busy.into_iter().for_each(|t| { t.join().unwrap(); }); + } + #[test] fn bounded_cstr_stops_at_nul_limit_and_unreadable_memory() { unsafe {