From e1226f07390900b957cd7b1fef9bdba6dc8af177 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:17:04 +0100 Subject: [PATCH 1/3] xcl run: XCL_THREAD_SAMPLE samples every thread's CPU time and stacks XCL_THREAD_SAMPLE=,, (+ XCL_THREAD_SAMPLE_FILE): from log time , every ms, a thread of its own reads for every other thread of the process its cycle time since the previous sample (QueryThreadCycleTime: the CPU it used, exact) and, when it ran, its registers and the top 16 KiB of its stack. The thread is stopped only for GetThreadContext and that copy: no lock and no allocation while it is suspended. Frames are unwound afterwards from the copy with RtlVirtualUnwind: RIP and up to 7 return addresses. A thread whose cycle time did not move and that waits in ntdll / win32u is not stopped again (its last stack is written as "unchanged"). Everything goes to a binary file with the modules and the thread names; the log gets a start line and the totals. Off unless set. ETW and VTune need elevation; this needs nothing. The walk never reads outside the copy: before each RtlVirtualUnwind, frame_extent bounds what the step can read from the function's UNWIND_INFO (pushes, allocations, machine frame, the farthest save, chained and indirect entries, version 2 epilogue descriptors, plus the return address; unknown codes are refused). That span must lie in the copy from RSP and, with a frame register, from FrameReg - 16 x FrameOffset; otherwise the walk ends with the frame TRUNCATED (1). The copy starts at RSP & !15 in a 16-aligned buffer and the CONTEXT is 16-aligned: RtlVirtualUnwind restores XMM saves with aligned moves (a misaligned copy is an access violation in ntdll); a misaligned one gives RIP alone. eh::thread_name is pub(crate) for the thread names. Tests (no GPU): the switch's parsing; the file read back record by record; the frame extent of every unwind code (synthetic UNWIND_INFOs, chained and indirect entries, refusals); a real 64 KiB frame walked from a 16 KiB copy that ends at a PAGE_NOACCESS page stops with [RIP, TRUNCATED], and from the whole stack unwinds into its caller; a sampling of this process that finds a spinning thread running and a waiting one unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 + crates/xcl/src/eh.rs | 2 +- crates/xcl/src/host.rs | 2 + crates/xcl/src/lib.rs | 1 + crates/xcl/src/thread_sample.rs | 1071 +++++++++++++++++++++++++++++++ 5 files changed, 1083 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/thread_sample.rs diff --git a/README.md b/README.md index d55abf4300..0e0a8bbf2b 100644 --- a/README.md +++ b/README.md @@ -468,6 +468,14 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. not prove that the driver immediately reclaimed the allocation or video memory. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. + - `XCL_THREAD_SAMPLE=,,`: from `` seconds of log time, every + `` ms (`` times), the CPU time each thread used since the last sample and, when + it ran, its instruction pointer and up to 7 callers, without a debugger, ETW or administrator + rights – where the CPU time goes when a title runs slowly. Each thread is stopped only to read + its registers and copy the top of its stack. Written to a binary file + (`XCL_THREAD_SAMPLE_FILE=`, else `xcl-thread-sample.bin` in the temp folder); `xcl.log` + gets a line when it starts and one with its totals (stops, their mean and longest time) at + the end. - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised (read, write or execute, the address, some registers and the callers on the stack), before the title's own handlers see them – for a title whose crash filter ends the process without a trace. diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 4f777df282..449ea26dd9 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -833,7 +833,7 @@ extern "system" { } /// A thread's description (SetThreadDescription – engines name their threads). -unsafe fn thread_name(h: *mut std::ffi::c_void) -> String { +pub(crate) unsafe fn thread_name(h: *mut std::ffi::c_void) -> String { let mut p: *mut u16 = std::ptr::null_mut(); if GetThreadDescription(h, &mut p) < 0 || p.is_null() { return String::new(); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f76e9a7a8d..80178bb9fb 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -260,6 +260,8 @@ pub fn host_main(boot_path: &Path) -> i32 { } }); } + // `XCL_THREAD_SAMPLE=,,`: every thread's CPU time and stacks, to a file (`thread_sample`) + crate::thread_sample::start_from_env(); crate::stubs::init_db(&boot.config.stub_returns); crate::hle::init(&boot.config); crate::hle::kernelx::fine_timer(); diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index df5aada1b7..ac3583d868 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -33,6 +33,7 @@ mod source_hash; pub mod stall; pub mod state; pub mod stubs; +pub mod thread_sample; pub mod tls; pub mod util; pub mod vfs; diff --git a/crates/xcl/src/thread_sample.rs b/crates/xcl/src/thread_sample.rs new file mode 100644 index 0000000000..ac0ea94693 --- /dev/null +++ b/crates/xcl/src/thread_sample.rs @@ -0,0 +1,1071 @@ +//! `XCL_THREAD_SAMPLE=,,` (+ `XCL_THREAD_SAMPLE_FILE=`) – +//! where the CPU time of every thread goes, without a debugger, ETW or elevation. Off unless set. +//! +//! From log time ``, every `` ms (`` times) a thread of its own takes, for +//! every other thread of the process: its cycle time since the previous sample +//! (`QueryThreadCycleTime`: the CPU it used, exact), and – when it ran since then – its registers +//! and the top of its stack, with the thread stopped only for that (`SuspendThread`, +//! `GetThreadContext`, a copy of at most 16 KiB of stack, `ResumeThread`). The frames are unwound +//! afterwards, thread running again, from that copy (`RtlVirtualUnwind` with the stack registers +//! moved into the copy, a step that could read outside the copy is not taken and ends the walk, +//! with the frame `TRUNCATED` (1) last when the frame is larger than the copy): RIP and up to 7 +//! return addresses. (Without that bound, `RtlVirtualUnwind` read past the 16 KiB copy at a frame +//! of 146 KiB, and the sampler's thread died in ntdll.) +//! A thread whose cycle time did not move and whose last RIP was in ntdll / win32u (a wait) is not +//! stopped: it did not run, so its stack is the one of its last sample (written as "unchanged"). +//! +//! Everything goes to a binary file (`XCL_THREAD_SAMPLE_FILE`, else `xcl-thread-sample.bin` in the +//! temp dir), not the log; scripts/thread_sample.py reads it (modules, xcl.exe's PDB, waits). Format, +//! little-endian (`Out` writes it, `read` in the tests reads it back): +//! header `XCLTSMP1`, u32 version, u32 period ms, f64 from, u32 count, u32 pid, f64 uptime, +//! u64 tsc, i64 qpc, i64 qpc frequency +//! 'M' u64 base, u64 size, u8 kind (0 other, 1 XCL's own exe, 2 an image XCL mapped), u16 n, name +//! 'T' u32 tid, u64 start address, u16 n, name (when first seen, and when the name changes) +//! 'S' u32 index, f64 uptime, u64 tsc, u16 entries; each: u32 tid, u8 state (0 stopped and +//! read, 1 unchanged, 2 failed), u8 frames, u64 cycles since its previous entry, frames x u64 +//! 'E' u32 samples, u32 threads, u64 stops, u64 unchanged, u64 failed, u64 sampler tsc, +//! u64 longest stop tsc, u64 stops tsc, u64 late, u64 tsc, i64 qpc, f64 uptime +//! The log gets one line at the start and one with the counts at the end. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::io::Write; + +pub(crate) const MAGIC: &[u8; 8] = b"XCLTSMP1"; +pub(crate) const VERSION: u32 = 1; +/// RIP + return addresses kept a sample +const FRAMES: usize = 8; +/// stack copied while a thread stands +const COPY_BYTES: usize = 16 << 10; +/// a thread is stopped at least once every this many samples, unchanged or not +const MAX_UNCHANGED: u32 = 20; +/// cycles a waiting thread may use between two samples and still count as not having run: stopping it +/// (SuspendThread runs a kernel APC on it, ResumeThread wakes it) charges it some cycles of its own, so +/// an exact `== 0` would stop every waiter at every sample +const WAKE_NOISE_CYCLES: u64 = 1_000_000; +/// samples between two looks at the thread list / at the thread names / at the modules +const REFRESH_THREADS: u32 = 100; +const REFRESH_NAMES: u32 = 200; +const REFRESH_MODULES: u32 = 2000; + +pub(crate) const STOPPED: u8 = 0; +pub(crate) const UNCHANGED: u8 = 1; +pub(crate) const FAILED: u8 = 2; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Config { + pub from: f64, + pub period_ms: u32, + pub count: u32, +} + +/// `,,`: all three, period 1..=1000 ms, count >= 1. +pub(crate) fn parse(v: &str) -> Option { + let f: Vec<&str> = v.split(',').map(str::trim).collect(); + if f.len() != 3 { + return None; + } + let from = f[0].parse::().ok().filter(|x| x.is_finite() && *x >= 0.0)?; + let period_ms = f[1].parse::().ok().filter(|p| (1..=1000).contains(p))?; + let count = f[2].parse::().ok().filter(|c| *c >= 1)?; + Some(Config { from, period_ms, count }) +} + +/// The binary file's writer (any `Write`: a file in the title, a Vec in the tests). +pub(crate) struct Out { + w: W, + pub ok: bool, +} + +impl Out { + pub fn new(w: W) -> Self { + Out { w, ok: true } + } + fn put(&mut self, b: &[u8]) { + if self.ok && self.w.write_all(b).is_err() { + self.ok = false; + } + } + fn name(&mut self, s: &str) { + let b = s.as_bytes(); + let n = b.len().min(u16::MAX as usize); + self.put(&(n as u16).to_le_bytes()); + self.put(&b[..n]); + } + #[allow(clippy::too_many_arguments)] + pub fn header(&mut self, c: &Config, pid: u32, uptime: f64, tsc: u64, qpc: i64, qpf: i64) { + self.put(MAGIC); + self.put(&VERSION.to_le_bytes()); + self.put(&c.period_ms.to_le_bytes()); + self.put(&c.from.to_le_bytes()); + self.put(&c.count.to_le_bytes()); + self.put(&pid.to_le_bytes()); + self.put(&uptime.to_le_bytes()); + self.put(&tsc.to_le_bytes()); + self.put(&qpc.to_le_bytes()); + self.put(&qpf.to_le_bytes()); + } + pub fn module(&mut self, base: u64, size: u64, kind: u8, name: &str) { + self.put(b"M"); + self.put(&base.to_le_bytes()); + self.put(&size.to_le_bytes()); + self.put(&[kind]); + self.name(name); + } + pub fn thread(&mut self, tid: u32, start: u64, name: &str) { + self.put(b"T"); + self.put(&tid.to_le_bytes()); + self.put(&start.to_le_bytes()); + self.name(name); + } + pub fn sample(&mut self, index: u32, uptime: f64, tsc: u64, entries: u16) { + self.put(b"S"); + self.put(&index.to_le_bytes()); + self.put(&uptime.to_le_bytes()); + self.put(&tsc.to_le_bytes()); + self.put(&entries.to_le_bytes()); + } + pub fn entry(&mut self, tid: u32, state: u8, cycles: u64, frames: &[u64]) { + let n = frames.len().min(u8::MAX as usize); + self.put(&tid.to_le_bytes()); + self.put(&[state, n as u8]); + self.put(&cycles.to_le_bytes()); + for f in &frames[..n] { + self.put(&f.to_le_bytes()); + } + } + pub fn end(&mut self, s: &Stats, tsc: u64, qpc: i64, uptime: f64) { + self.put(b"E"); + self.put(&s.samples.to_le_bytes()); + self.put(&s.threads.to_le_bytes()); + for v in [s.stops, s.unchanged, s.failed, s.sampler_tsc, s.longest_stop_tsc, s.stops_tsc, s.late, tsc] { + self.put(&v.to_le_bytes()); + } + self.put(&qpc.to_le_bytes()); + self.put(&uptime.to_le_bytes()); + } + pub fn flush(&mut self) { + if self.ok && self.w.flush().is_err() { + self.ok = false; + } + } +} + +/// The counts of a sampling. +#[derive(Default, Clone, Debug, PartialEq)] +pub(crate) struct Stats { + pub samples: u32, + pub threads: u32, + pub stops: u64, + pub unchanged: u64, + pub failed: u64, + pub sampler_tsc: u64, + pub longest_stop_tsc: u64, + pub stops_tsc: u64, + pub late: u64, +} + +/// x64 CONTEXT's 16 integer registers, in register-number order (Rax, Rcx, Rdx, Rbx, Rsp, Rbp, +/// Rsi, Rdi, R8..R15: the CONTEXT keeps them in that order, one u64 after the other). +fn regs(c: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> *mut u64 { + std::ptr::addr_of_mut!(c.Rax) +} + +/// Registers pointing into the original stack span [lo, lo + len) point into the copy at `copy`. +unsafe fn rebase(c: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, lo: u64, len: u64, copy: u64) { + let r = regs(c); + for i in 0..16 { + let v = *r.add(i); + if v >= lo && v < lo + len { + *r.add(i) = v - lo + copy; + } + } +} + +/// The frame written in place of the rest of a walk stopped by `frame_extent` (a frame larger +/// than the stack copy, or unwind data it cannot bound): never a code address (`walk` ends at +/// any RIP below 0x10000), so a reader shows it as an unknown frame. +pub(crate) const TRUNCATED: u64 = 1; + +/// The most stack bytes, from the frame's base up, that unwinding one frame of the function whose +/// UNWIND_INFO is at `base + ua` can read: every push, allocation and machine frame added up, plus +/// the farthest register save, for this UNWIND_INFO and each one it chains to, plus the return +/// address. The base is RSP, or FrameReg - 16 x FrameOffset once the prolog has set the frame +/// register: `RtlVirtualUnwind` reads nothing else of the stack (a prolog step, an epilogue's pops +/// and `ret`, and the machine frame all lie in that span). Over-counts (allocations done after the +/// frame register is set are added although `RtlVirtualUnwind` reads nothing for them). +/// None: unwind data it does not bound (an unknown or obsolete code, a code after a machine +/// frame, a truncated code array, chains deeper than 32), or an UNWIND_INFO version other than 1 +/// and 2: the walk stops there. `ua` odd: the RUNTIME_FUNCTION at `base + (ua & !1)` gives it. +/// Reads only the module's unwind data: no lock, no heap. +unsafe fn frame_extent(base: u64, mut ua: u32) -> Option { + let mut need = 8u64; // the return address + let mut machine_frame = false; + for _ in 0..32 { + if ua & 1 != 0 { + // an indirect entry: the RUNTIME_FUNCTION { begin, end, unwind info } it names + ua = ((base + (ua & !1) as u64) as *const u32).add(2).read_unaligned(); + continue; + } + let info = (base + ua as u64) as *const u8; + let (version, flags, count) = (*info & 7, *info >> 3, *info.add(2) as usize); + if version != 1 && version != 2 { + return None; + } + let codes = info.add(4) as *const u16; + let slot = |i: usize| codes.add(i).read_unaligned() as u64; + let mut i = 0; + if version == 2 { + // the epilogue descriptors come first, each slot of them with operation 6 (UWOP_EPILOG): + // they read nothing + while i < count && (slot(i) >> 8) & 0xF == 6 { + i += 1; + } + } + let (mut size, mut saves) = (0u64, 0u64); + while i < count { + if machine_frame { + // a code after a machine frame reads from the RSP it gave: not bounded here + return None; + } + let (op, op_info) = ((slot(i) >> 8) & 0xF, slot(i) >> 12); + // (stack bytes the code moves RSP by, slots it takes); a save's farthest byte in `saves` + let (bytes, slots) = match op { + // UWOP_PUSH_NONVOL + 0 => (8, 1), + // UWOP_ALLOC_LARGE: size / 8 in one slot, or the size in two + 1 if op_info == 0 && i + 1 < count => (slot(i + 1) * 8, 2), + 1 if op_info == 1 && i + 2 < count => (slot(i + 1) | slot(i + 2) << 16, 3), + // UWOP_ALLOC_SMALL + 2 => (op_info * 8 + 8, 1), + // UWOP_SET_FPREG + 3 => (0, 1), + // UWOP_SAVE_NONVOL (offset / 8) and _FAR (offset) + 4 if i + 1 < count => { + saves = saves.max(slot(i + 1) * 8 + 8); + (0, 2) + } + 5 if i + 2 < count => { + saves = saves.max((slot(i + 1) | slot(i + 2) << 16) + 8); + (0, 3) + } + // UWOP_SAVE_XMM128 (offset / 16) and _FAR (offset) + 8 if i + 1 < count => { + saves = saves.max(slot(i + 1) * 16 + 16); + (0, 2) + } + 9 if i + 2 < count => { + saves = saves.max((slot(i + 1) | slot(i + 2) << 16) + 16); + (0, 3) + } + // UWOP_PUSH_MACHFRAME: RIP, CS, EFLAGS, RSP, SS (and an error code first) + 10 => { + machine_frame = true; + (if op_info == 0 { 40 } else { 48 }, 1) + } + _ => return None, + }; + size += bytes; + i += slots; + } + need = need.checked_add(size)?.checked_add(saves)?; + if flags & 4 == 0 { + return Some(need); + } + // UNW_FLAG_CHAININFO: the RUNTIME_FUNCTION after the (even-rounded) code array + ua = (codes.add((count + 1) & !1) as *const u32).add(2).read_unaligned(); + } + None +} + +/// RIP and the return addresses of up to `max - 1` frames, unwound from `c` whose stack +/// registers were moved into the copy [copy, copy + len) (`lo`: the original address of the copy's +/// first byte). A step that could read outside the copy is not taken: the walk ends there, with +/// `TRUNCATED` as its last frame when the step's unwind data says more than the copy holds. +/// Before each `RtlVirtualUnwind`, `frame_extent`'s bytes must lie in the copy from RSP and, for a +/// function with a frame register, from FrameReg - 16 x FrameOffset too: whichever base +/// `RtlVirtualUnwind` takes for the frame, everything it reads of the stack is then in the copy. +/// (A check of the new RSP after the step would come too late: the reads are in the step.) No lock, +/// no heap: `out` has room for `max`. +unsafe fn walk(c: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, lo: u64, copy: u64, len: u64, max: usize, out: &mut Vec) { + use windows_sys::Win32::System::Diagnostics::Debug::{RtlLookupFunctionEntry, RtlVirtualUnwind, UNW_FLAG_NHANDLER}; + let inside = |v: u64, bytes: u64| v >= copy && v.checked_add(bytes).is_some_and(|e| e <= copy + len); + // RtlVirtualUnwind restores UWOP_SAVE_XMM128 registers with 16-byte aligned moves, from the + // copy into the CONTEXT: a misaligned one is a #GP, an access violation at + // 0xffffffffffffffff. The CONTEXT must be 16-aligned and the copy at the original stack's + // alignment mod 16; else RIP alone. + if (c as *const _ as u64) & 15 != 0 || (copy ^ lo) & 15 != 0 { + out.push(c.Rip); + return; + } + while out.len() < max { + let rip = c.Rip; + if rip < 0x10000 { + break; + } + out.push(rip); + if out.len() == max || !inside(c.Rsp, 8) { + break; + } + let mut base = 0u64; + let f = RtlLookupFunctionEntry(rip, &mut base, std::ptr::null_mut()); + if f.is_null() { + // no unwind data (a leaf, or code made at run time): the return address at RSP + c.Rip = (c.Rsp as *const u64).read_unaligned(); + c.Rsp += 8; + continue; + } + let ua = (*f).Anonymous.UnwindInfoAddress; + let Some(need) = frame_extent(base, ua) else { + out.push(TRUNCATED); + break; + }; + if !inside(c.Rsp, need) { + out.push(TRUNCATED); + break; + } + // a frame register (UNWIND_INFO byte 3: register in the low nibble, offset / 16 in the high + // one; an indirect entry's own UNWIND_INFO holds it) must give a base with the frame in the + // copy too (it is the caller's value in a prolog before the register is set: the walk ends) + let mut ui = ua; + for _ in 0..32 { + if ui & 1 == 0 { + break; + } + ui = ((base + (ui & !1) as u64) as *const u32).add(2).read_unaligned(); + } + if ui & 1 != 0 { + out.push(TRUNCATED); + break; + } + let fb = *((base + ui as u64) as *const u8).add(3); + let fr = (fb & 0xF) as usize; + if fr != 0 { + let frame_base = (*regs(c).add(fr)).wrapping_sub(16 * (fb >> 4) as u64); + if !inside(frame_base, need) { + if inside(*regs(c).add(fr), 8) { + out.push(TRUNCATED); + } + break; + } + } + let mut data = std::ptr::null_mut(); + let mut frame = 0u64; + RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, rip, f, c, &mut data, &mut frame, std::ptr::null_mut()); + // registers restored from the copy hold original stack addresses + rebase(c, lo, len, copy); + } +} + +#[link(name = "kernel32")] +extern "system" { + fn QueryThreadCycleTime(thread: *mut c_void, cycles: *mut u64) -> i32; +} + +/// [base, base + SizeOfImage) of a loaded module (0, 0: none). +unsafe fn image_span(base: usize) -> (u64, u64) { + if base == 0 { + return (0, 0); + } + let pe = base + (base as *const u8).add(0x3C).cast::().read_unaligned() as usize; + // PE signature (4) + file header (20) + SizeOfImage's offset in the optional header (56) + let size = (pe as *const u8).add(0x18 + 56).cast::().read_unaligned(); + (base as u64, size as u64) +} + +unsafe fn module_span(name: &str) -> (u64, u64) { + let w: Vec = name.encode_utf16().chain(Some(0)).collect(); + image_span(windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(w.as_ptr()) as usize) +} + +fn tsc() -> u64 { + unsafe { core::arch::x86_64::_rdtsc() } +} + +fn qpc() -> i64 { + let mut v = 0i64; + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) }; + v +} + +struct Thread { + h: *mut c_void, + name: String, + cycles: u64, + /// the last stop's RIP was in a wait (ntdll / win32u) + waiting: bool, + unchanged_in_row: u32, + alive: bool, +} + +/// The modules: the loader's (toolhelp) and the images XCL mapped; each base once. +unsafe fn write_modules(out: &mut Out, seen: &mut std::collections::HashSet) { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Module32FirstW, Module32NextW, MODULEENTRY32W, TH32CS_SNAPMODULE}; + let own = windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null()) as u64; + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); + if snap != INVALID_HANDLE_VALUE { + let mut me: MODULEENTRY32W = std::mem::zeroed(); + me.dwSize = std::mem::size_of::() as u32; + let mut ok = Module32FirstW(snap, &mut me) != 0; + while ok { + let base = me.modBaseAddr as u64; + if seen.insert(base) { + // the full path: scripts/thread_sample.py reads the DLLs' export tables from it + let n = me.szExePath.iter().position(|&c| c == 0).unwrap_or(me.szExePath.len()); + out.module(base, me.modBaseSize as u64, u8::from(base == own), &String::from_utf16_lossy(&me.szExePath[..n])); + } + ok = Module32NextW(snap, &mut me) != 0; + } + CloseHandle(snap); + } + for m in crate::modules::mapped_modules() { + if seen.insert(m.base as u64) { + out.module(m.base as u64, m.size as u64, 2, &m.name); + } + } +} + +/// The thread's start address (NtQueryInformationThread, ThreadQuerySetWin32StartAddress). +unsafe fn start_address(h: *mut c_void) -> u64 { + type F = unsafe extern "system" fn(*mut c_void, u32, *mut c_void, u32, *mut u32) -> i32; + static F: std::sync::OnceLock = std::sync::OnceLock::new(); + let f = *F.get_or_init(|| { + let ntdll: Vec = "ntdll.dll\0".encode_utf16().collect(); + let m = windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(ntdll.as_ptr()); + windows_sys::Win32::System::LibraryLoader::GetProcAddress(m, c"NtQueryInformationThread".as_ptr().cast()).map_or(0, |p| p as usize) + }); + if f == 0 { + return 0; + } + let mut a = 0u64; + let st = std::mem::transmute::(f)(h, 9, (&mut a as *mut u64).cast(), 8, std::ptr::null_mut()); + if st >= 0 { + a + } else { + 0 + } +} + +/// The ids of the other threads of this process. +unsafe fn thread_ids(me: u32) -> Vec { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32}; + let pid = windows_sys::Win32::System::Threading::GetCurrentProcessId(); + let mut out = Vec::new(); + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snap == INVALID_HANDLE_VALUE { + return out; + } + let mut te: THREADENTRY32 = std::mem::zeroed(); + te.dwSize = std::mem::size_of::() as u32; + let mut ok = Thread32First(snap, &mut te) != 0; + while ok { + if te.th32OwnerProcessID == pid && te.th32ThreadID != me { + out.push(te.th32ThreadID); + } + ok = Thread32Next(snap, &mut te) != 0; + } + CloseHandle(snap); + out +} + +/// Run the sampling of `c` on this thread into `out` (from log time `c.from`); the counts. +pub(crate) fn run(c: Config, out: &mut Out) -> Stats { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Diagnostics::Debug::{GetThreadContext, CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64}; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, GetExitCodeThread, OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, + }; + let left = c.from - crate::log::uptime(); + if left > 0.0 { + std::thread::sleep(std::time::Duration::from_secs_f64(left)); + } + let mut st = Stats::default(); + unsafe { + let me = GetCurrentThreadId(); + let mut qpf = 0i64; + windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut qpf); + out.header(&c, GetCurrentProcessId(), crate::log::uptime(), tsc(), qpc(), qpf); + let mut modules = std::collections::HashSet::new(); + write_modules(out, &mut modules); + let waits = [module_span("ntdll.dll"), module_span("win32u.dll")]; + let in_wait = |rip: u64| waits.iter().any(|&(b, n)| rip >= b && rip < b + n); + let mut threads: HashMap = HashMap::new(); + let mut ids: Vec = Vec::new(); + // u128: 16-aligned, as the stack it copies (see walk) + let mut copy = vec![0u128; COPY_BYTES / 16]; + let mut frames: Vec = Vec::with_capacity(FRAMES); + let mut rows: Vec<(u32, u8, u64, [u64; FRAMES], u8)> = Vec::new(); + let period = std::time::Duration::from_millis(c.period_ms as u64); + let mut t0 = std::time::Instant::now(); + for i in 0..c.count { + // on time: the i-th sample at t0 + i periods; more than a period late, from now on + let due = t0 + period * i; + let now = std::time::Instant::now(); + if now < due { + std::thread::sleep(due - now); + } else if now - due > period { + st.late += 1; + t0 = now - period * i; + } + let pass = tsc(); + if i % REFRESH_THREADS == 0 { + ids = thread_ids(me); + for &tid in &ids { + if threads.contains_key(&tid) { + continue; + } + let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, tid); + if h.is_null() { + continue; + } + let name = crate::eh::thread_name(h); + out.thread(tid, start_address(h), &name); + let mut cy = 0u64; + QueryThreadCycleTime(h, &mut cy); + threads.insert(tid, Thread { h, name, cycles: cy, waiting: false, unchanged_in_row: 0, alive: true }); + } + st.threads = threads.len() as u32; + } + if i % REFRESH_NAMES == REFRESH_NAMES - 1 { + for (&tid, t) in threads.iter_mut().filter(|t| t.1.alive) { + let name = crate::eh::thread_name(t.h); + if name != t.name { + out.thread(tid, start_address(t.h), &name); + t.name = name; + } + } + } + if i % REFRESH_MODULES == REFRESH_MODULES - 1 { + write_modules(out, &mut modules); + } + rows.clear(); + for &tid in &ids { + let Some(t) = threads.get_mut(&tid) else { continue }; + if !t.alive { + continue; + } + let mut cy = 0u64; + let have_cy = QueryThreadCycleTime(t.h, &mut cy) != 0; + let ran = cy.wrapping_sub(t.cycles); + if have_cy && ran < WAKE_NOISE_CYCLES && t.waiting && t.unchanged_in_row < MAX_UNCHANGED { + t.unchanged_in_row += 1; + st.unchanged += 1; + t.cycles = cy; + rows.push((tid, UNCHANGED, ran, [0; FRAMES], 0)); + continue; + } + #[repr(align(16))] + struct Aligned(CONTEXT); + let mut ctx: Aligned = std::mem::zeroed(); + ctx.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let (mut lo, mut len) = (0u64, 0u64); + // stopped only for its registers and the copy of its stack top: no lock, no heap + let s0 = tsc(); + let got = SuspendThread(t.h) != u32::MAX && { + let ok = GetThreadContext(t.h, &mut ctx.0) != 0; + if ok { + // from a 16-aligned address: the copy keeps the stack's alignment (walk) + let sp = ctx.0.Rsp & !15; + let mut q: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if sp != 0 + && VirtualQuery(sp as *const c_void, &mut q, std::mem::size_of::()) != 0 + && q.State == MEM_COMMIT + && q.Protect & 0x104 == 0x4 + { + let end = q.BaseAddress as u64 + q.RegionSize as u64; + len = (end - sp).min(COPY_BYTES as u64); + lo = sp; + std::ptr::copy_nonoverlapping(sp as *const u8, copy.as_mut_ptr().cast::(), len as usize); + } + } + ResumeThread(t.h); + ok + }; + let stop = tsc().wrapping_sub(s0); + if !got { + st.failed += 1; + let mut code = 0u32; + if GetExitCodeThread(t.h, &mut code) != 0 && code != 259 { + t.alive = false; + } + rows.push((tid, FAILED, if have_cy { ran } else { 0 }, [0; FRAMES], 0)); + continue; + } + st.stops += 1; + st.stops_tsc += stop; + st.longest_stop_tsc = st.longest_stop_tsc.max(stop); + frames.clear(); + let rip = ctx.0.Rip; + if len >= 8 { + let base = copy.as_ptr() as u64; + rebase(&mut ctx.0, lo, len, base); + walk(&mut ctx.0, lo, base, len, FRAMES, &mut frames); + } else { + frames.push(rip); + } + t.waiting = in_wait(rip); + t.unchanged_in_row = 0; + if have_cy { + t.cycles = cy; + } + let mut f = [0u64; FRAMES]; + f[..frames.len()].copy_from_slice(&frames); + rows.push((tid, STOPPED, if have_cy { ran } else { 0 }, f, frames.len() as u8)); + } + out.sample(i, crate::log::uptime(), pass, rows.len() as u16); + for (tid, state, cy, f, n) in &rows { + out.entry(*tid, *state, *cy, &f[..*n as usize]); + } + st.samples += 1; + st.sampler_tsc += tsc().wrapping_sub(pass); + if i % 200 == 199 { + out.flush(); + } + if !out.ok { + break; + } + } + write_modules(out, &mut modules); + out.end(&st, tsc(), qpc(), crate::log::uptime()); + out.flush(); + for t in threads.values() { + CloseHandle(t.h); + } + } + st +} + +/// `XCL_THREAD_SAMPLE` set: the sampler's thread. +pub fn start_from_env() { + let Ok(v) = std::env::var("XCL_THREAD_SAMPLE") else { return }; + let Some(c) = parse(&v) else { + crate::xlog_warn!("thread sample: XCL_THREAD_SAMPLE={v} is not ,,: off"); + return; + }; + let file = std::env::var_os("XCL_THREAD_SAMPLE_FILE").map_or_else(|| std::env::temp_dir().join("xcl-thread-sample.bin"), std::path::PathBuf::from); + let _ = std::thread::Builder::new().name("xcl-thread-sample".into()).spawn(move || { + crate::xlog_info!("thread sample: from {} s every {} ms, {} samples, to {}", c.from, c.period_ms, c.count, file.display()); + let f = match std::fs::File::create(&file) { + Ok(f) => f, + Err(e) => { + crate::xlog_warn!("thread sample: cannot create {}: {e}", file.display()); + return; + } + }; + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_HIGHEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + } + let mut out = Out::new(std::io::BufWriter::with_capacity(1 << 20, f)); + let t0 = (crate::log::uptime(), tsc()); + let s = run(c, &mut out); + let t1 = (crate::log::uptime(), tsc()); + let hz = (t1.1 - t0.1) as f64 / (t1.0 - t0.0).max(1e-9); + let us = |t: u64| t as f64 * 1e6 / hz.max(1.0); + crate::xlog_info!( + "thread sample: done: {} samples, {} threads, {} stops (mean {:.1} us, longest {:.0} us), {} unchanged, {} failed, {} late; sampler {:.0} us a sample; {} ({})", + s.samples, + s.threads, + s.stops, + us(s.stops_tsc) / s.stops.max(1) as f64, + us(s.longest_stop_tsc), + s.unchanged, + s.failed, + s.late, + us(s.sampler_tsc) / s.samples.max(1) as f64, + file.display(), + if out.ok { "ok" } else { "WRITE FAILED" } + ); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the file holds, read back (the reader scripts/thread_sample.py has, in Rust). + #[derive(Debug, Default)] + struct File { + period_ms: u32, + count: u32, + modules: Vec<(u64, u64, u8, String)>, + threads: Vec<(u32, u64, String)>, + samples: Vec<(u32, f64, u64, Vec<(u32, u8, u64, Vec)>)>, + end: Option<(u32, u32, Vec)>, + } + + struct Reader<'a> { + b: &'a [u8], + p: usize, + } + + impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let s = self.b.get(self.p..self.p + n)?; + self.p += n; + Some(s) + } + } + + fn read(b: &[u8]) -> Option { + let mut r = Reader { b, p: 0 }; + let mut take = |n: usize| r.take(n); + macro_rules! u { + ($t:ty) => { + <$t>::from_le_bytes(take(std::mem::size_of::<$t>())?.try_into().ok()?) + }; + } + if take(8)? != MAGIC || u!(u32) != VERSION { + return None; + } + let mut f = File { period_ms: u!(u32), ..Default::default() }; + let _from = u!(f64); + f.count = u!(u32); + let (_pid, _up, _tsc, _qpc, _qpf) = (u!(u32), u!(f64), u!(u64), u!(i64), u!(i64)); + loop { + let Some(tag) = take(1) else { break }; + match tag[0] { + b'M' => { + let (base, size, kind) = (u!(u64), u!(u64), take(1)?[0]); + let n = u!(u16) as usize; + f.modules.push((base, size, kind, String::from_utf8_lossy(take(n)?).into_owned())); + } + b'T' => { + let (tid, start) = (u!(u32), u!(u64)); + let n = u!(u16) as usize; + f.threads.push((tid, start, String::from_utf8_lossy(take(n)?).into_owned())); + } + b'S' => { + let (i, up, t, n) = (u!(u32), u!(f64), u!(u64), u!(u16)); + let mut es = Vec::new(); + for _ in 0..n { + let tid = u!(u32); + let (state, nf) = (take(1)?[0], take(1)?[0]); + let cy = u!(u64); + let fr = (0..nf).map(|_| Some(u!(u64))).collect::>>()?; + es.push((tid, state, cy, fr)); + } + f.samples.push((i, up, t, es)); + } + b'E' => { + let (s, t) = (u!(u32), u!(u32)); + let v = (0..8).map(|_| Some(u!(u64))).collect::>>()?; + let (_q, _u) = (u!(i64), u!(f64)); + f.end = Some((s, t, v)); + } + _ => return None, + } + } + Some(f) + } + + #[test] + fn the_switch_takes_a_start_a_period_and_a_count() { + assert_eq!(parse("360,5,12000"), Some(Config { from: 360.0, period_ms: 5, count: 12000 })); + assert_eq!(parse(" 0.5 , 1 , 1 "), Some(Config { from: 0.5, period_ms: 1, count: 1 })); + assert_eq!(parse("360,5"), None); + assert_eq!(parse("360,5,12000,1"), None); + assert_eq!(parse("360,0,10"), None); + assert_eq!(parse("360,1001,10"), None); + assert_eq!(parse("360,5,0"), None); + assert_eq!(parse("-1,5,10"), None); + assert_eq!(parse("x,5,10"), None); + assert_eq!(parse(""), None); + } + + #[test] + fn the_file_reads_back_record_by_record() { + let mut out = Out::new(Vec::new()); + let c = Config { from: 12.5, period_ms: 5, count: 2 }; + out.header(&c, 77, 12.6, 1000, 2000, 10_000_000); + out.module(0x1_4000_0000, 0x10_0000, 1, "xcl.exe"); + out.module(0x7ff8_0000_0000, 0x20_0000, 0, "ntdll.dll"); + out.thread(42, 0x1_4000_1234, "submit"); + out.thread(43, 0, ""); + out.sample(0, 12.7, 5000, 2); + out.entry(42, STOPPED, 123_456, &[0x1_4000_2000, 0x1_4000_3000]); + out.entry(43, UNCHANGED, 0, &[]); + out.sample(1, 12.71, 6000, 1); + out.entry(43, FAILED, 9, &[]); + let s = Stats { samples: 2, threads: 2, stops: 1, unchanged: 1, failed: 1, sampler_tsc: 10, longest_stop_tsc: 3, stops_tsc: 3, late: 0 }; + out.end(&s, 7000, 3000, 12.8); + out.flush(); + assert!(out.ok); + let f = read(&out.w).expect("the file parses"); + assert_eq!((f.period_ms, f.count), (5, 2)); + assert_eq!(f.modules[0], (0x1_4000_0000, 0x10_0000, 1, "xcl.exe".into())); + assert_eq!(f.threads, vec![(42, 0x1_4000_1234, "submit".into()), (43, 0, String::new())]); + assert_eq!(f.samples.len(), 2); + assert_eq!(f.samples[0].3[0], (42, STOPPED, 123_456, vec![0x1_4000_2000, 0x1_4000_3000])); + assert_eq!(f.samples[0].3[1], (43, UNCHANGED, 0, vec![])); + assert_eq!(f.samples[1].3, vec![(43, FAILED, 9, vec![])]); + assert_eq!(f.end, Some((2, 2, vec![1, 1, 1, 10, 3, 3, 0, 7000]))); + // a truncated file stops at its last whole record + assert!(read(&out.w[..out.w.len() - 3]).is_none()); + } + + /// An unwind code slot: prolog offset, operation, operation info. + fn code(at: u8, op: u8, info: u8) -> u16 { + at as u16 | ((op | info << 4) as u16) << 8 + } + + /// A fake image with UNWIND_INFOs (version | flags << 3, prolog size, code count, frame + /// register) at the given offsets, each followed by its codes and, chained, a RUNTIME_FUNCTION. + struct Image(Vec); + + impl Image { + fn new() -> Self { + Image(vec![0u64; 0x200]) + } + fn put(&mut self, at: usize, b: &[u8]) { + let p = self.0.as_mut_ptr().cast::(); + assert!(at + b.len() <= self.0.len() * 8); + unsafe { std::ptr::copy_nonoverlapping(b.as_ptr(), p.add(at), b.len()) }; + } + /// UNWIND_INFO at `at`; `chain`: the UNWIND_INFO offset its chained RUNTIME_FUNCTION names + fn info(&mut self, at: usize, version: u8, frame: u8, codes: &[u16], chain: Option) { + let flags = if chain.is_some() { 4 } else { 0 }; + self.put(at, &[version | flags << 3, 0, codes.len() as u8, frame]); + let mut b: Vec = codes.iter().flat_map(|c| c.to_le_bytes()).collect(); + if let Some(u) = chain { + if codes.len() % 2 == 1 { + b.extend([0, 0]); + } + b.extend([0x1000u32, 0x1100, u].iter().flat_map(|v| v.to_le_bytes())); + } + self.put(at + 4, &b); + } + fn extent(&self, ua: u32) -> Option { + unsafe { frame_extent(self.0.as_ptr() as u64, ua) } + } + } + + /// `frame_extent` adds up what one unwind step can read, for each unwind code, chained and + /// indirect entries and version 2's epilogue descriptors, and refuses what it cannot bound. + #[test] + fn the_frame_extent_counts_every_byte_an_unwind_step_may_read() { + let mut m = Image::new(); + // a frame the sampler once died on: xmm15 saved at 0x249f0, 0x24a08 + // allocated, 8 pushes + let mut codes = vec![code(115, 8, 15), 0x249f, code(25, 1, 0), (0x24a08 / 8) as u16]; + codes.extend((0..8).map(|k| code(12 - k, 0, 3))); + m.info(0x100, 1, 0, &codes, None); + assert_eq!(m.extent(0x100), Some(8 + 0x24a08 + 64 + 0x249f0 + 16)); + // a 32-bit ALLOC_LARGE, SAVE_NONVOL_FAR, SET_FPREG (no bytes), ALLOC_SMALL + m.info(0x200, 1, 0x25, &[code(20, 5, 3), 0x0010, 0x0002, code(16, 3, 0), code(12, 1, 1), 0x3458, 0x0012, code(4, 2, 3)], None); + assert_eq!(m.extent(0x200), Some(8 + 0x12_3458 + 32 + 0x2_0010 + 8)); + // chained: the child's 16-byte allocation, then the parent's two pushes and a save + m.info(0x300, 1, 0, &[code(4, 2, 1)], Some(0x340)); + m.info(0x340, 1, 0, &[code(6, 4, 3), 0x0004, code(2, 0, 5), code(1, 0, 6)], None); + assert_eq!(m.extent(0x300), Some(8 + 16 + 16 + 0x20 + 8)); + // an indirect entry (odd address): the RUNTIME_FUNCTION at 0x380 names 0x300 + m.put(0x380, &[0x1000u32, 0x1100, 0x300].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + assert_eq!(m.extent(0x381), m.extent(0x300)); + // version 2: the epilogue descriptors read nothing + m.info(0x400, 2, 0, &[code(1, 6, 1), code(2, 6, 0), code(4, 2, 6)], None); + assert_eq!(m.extent(0x400), Some(8 + 56)); + // a machine frame alone (with an error code) + m.info(0x440, 1, 0, &[code(0, 10, 1)], None); + assert_eq!(m.extent(0x440), Some(8 + 48)); + // refused: a code after the machine frame, version 1's obsolete 6 / 7, unknown 11, a + // truncated ALLOC_LARGE, ALLOC_LARGE info 2, versions 0 and 3, a chain into itself + m.info(0x480, 1, 0, &[code(0, 10, 0), code(0, 0, 3)], None); + assert_eq!(m.extent(0x480), None); + for (k, codes) in [vec![code(4, 6, 0), 0x10], vec![code(4, 7, 0), 0x10, 0], vec![code(4, 11, 0)], vec![code(4, 1, 0)], vec![code(4, 1, 2), 1, 1]].iter().enumerate() { + let at = 0x500 + 0x40 * k; + m.info(at, 1, 0, codes, None); + assert_eq!(m.extent(at as u32), None, "codes {codes:x?}"); + } + m.info(0x700, 3, 0, &[code(4, 2, 3)], None); + assert_eq!(m.extent(0x700), None); + m.info(0x740, 0, 0, &[code(4, 2, 3)], None); + assert_eq!(m.extent(0x740), None); + m.info(0x780, 1, 0, &[code(4, 2, 3)], Some(0x780)); + assert_eq!(m.extent(0x780), None); + } + + /// A copy of `len` bytes that ends exactly at an inaccessible page: reading past it faults. + struct Guarded { + at: *mut u8, + copy: u64, + } + + impl Guarded { + fn new(len: usize) -> Self { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + let body = len.div_ceil(0x1000) * 0x1000; + let size = body + 0x1000; + unsafe { + let at = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast::(); + assert!(!at.is_null()); + let mut old = 0; + assert_ne!(VirtualProtect(at.add(body).cast(), 0x1000, PAGE_NOACCESS, &mut old), 0); + Guarded { at, copy: at.add(body - len) as u64 } + } + } + } + + impl Drop for Guarded { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + unsafe { VirtualFree(self.at.cast(), 0, MEM_RELEASE) }; + } + } + + #[repr(align(16))] + struct Ctx(windows_sys::Win32::System::Diagnostics::Debug::CONTEXT); + + /// Calls `f` with the registers of a point inside a function whose frame holds 64 KiB. + #[inline(never)] + fn in_a_big_frame(f: &mut dyn FnMut(&windows_sys::Win32::System::Diagnostics::Debug::CONTEXT)) { + let mut big = [0u8; 64 << 10]; + std::hint::black_box(&mut big); + let mut c: Ctx = unsafe { std::mem::zeroed() }; + unsafe { windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureContext(&mut c.0) }; + f(&c.0); + std::hint::black_box(&big); + } + + /// The walk from a stack copy smaller than the frame it starts in stops at that frame with + /// `TRUNCATED` and reads nothing past the copy (it ends at an inaccessible page: a read there + /// would end the test process); with the whole stack copied it unwinds into the caller. + #[test] + fn a_walk_stops_at_a_frame_larger_than_the_stack_copy() { + use windows_sys::Win32::System::Diagnostics::Debug::RtlLookupFunctionEntry; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION}; + let own = unsafe { image_span(windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null()) as usize) }; + let in_own = |a: u64| a >= own.0 && a < own.0 + own.1; + let mut runs = Vec::new(); + in_a_big_frame(&mut |c| unsafe { + // 16-aligned, as `run`'s copy (walk unwinds only a copy at the stack's alignment) + let sp = c.Rsp & !15; + let mut q: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(sp as *const c_void, &mut q, std::mem::size_of::()), 0); + let avail = (q.BaseAddress as u64 + q.RegionSize as u64 - sp) as usize; + let mut base = 0u64; + let f = RtlLookupFunctionEntry(c.Rip, &mut base, std::ptr::null_mut()); + assert!(!f.is_null(), "the big frame has unwind data"); + let need = frame_extent(base, (*f).Anonymous.UnwindInfoAddress).expect("bounded"); + assert!(need > (64 << 10) as u64 && need > COPY_BYTES as u64, "the frame is larger than the sampler's copy ({need} B)"); + for len in [COPY_BYTES, avail.min(1 << 20)] { + let g = Guarded::new(len); + std::ptr::copy_nonoverlapping(sp as *const u8, g.copy as *mut u8, len); + let mut ctx = Ctx(*c); + rebase(&mut ctx.0, sp, len as u64, g.copy); + let mut frames = Vec::with_capacity(FRAMES); + walk(&mut ctx.0, sp, g.copy, len as u64, FRAMES, &mut frames); + runs.push((len, need, frames)); + } + }); + eprintln!("walks: {runs:x?}"); + let (len, need, small) = &runs[0]; + assert_eq!(*len, COPY_BYTES); + assert_eq!(small.len(), 2, "RIP, then the marker: {small:x?}"); + assert!(in_own(small[0])); + assert_eq!(small[1], TRUNCATED); + let (len, _, whole) = &runs[1]; + assert!(*len as u64 >= *need, "the stack holds the frame"); + assert!(whole.len() >= 2 && whole[1] != TRUNCATED && in_own(whole[1]), "the caller is unwound: {whole:x?}"); + assert_eq!(whole[0], small[0]); + } + + #[inline(never)] + fn spin(stop: &std::sync::atomic::AtomicBool) -> u64 { + let mut x = 0u64; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + x = std::hint::black_box(x.wrapping_mul(6364136223846793005).wrapping_add(1)); + } + x + } + + /// This process sampled: a spinning thread is stopped and found running in this binary with + /// its caller unwound, its cycle time moving; a thread blocked in a wait is found in ntdll + /// and then left unchanged; the sampler's own thread is never in the file. + /// `XCL_THREAD_SAMPLE_TEST_OUT=` keeps the file (for scripts/thread_sample.py). + #[test] + fn a_sampling_of_this_process_finds_the_spinning_and_the_waiting_thread() { + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + let stop = Arc::new(AtomicBool::new(false)); + let s2 = stop.clone(); + let spinner = std::thread::Builder::new().name("ts-spinner".into()).spawn(move || spin(&s2)).unwrap(); + let (tx, rx) = std::sync::mpsc::channel::<()>(); + let waiter = std::thread::Builder::new().name("ts-waiter".into()).spawn(move || rx.recv().ok()).unwrap(); + // Rust names its threads with SetThreadDescription; wait until both are running + std::thread::sleep(std::time::Duration::from_millis(50)); + let (sp_id, wt_id) = unsafe { + use std::os::windows::io::AsRawHandle; + let id = |h: *mut c_void| windows_sys::Win32::System::Threading::GetThreadId(h); + (id(spinner.as_raw_handle()), id(waiter.as_raw_handle())) + }; + let mut out = Out::new(Vec::new()); + let c = Config { from: 0.0, period_ms: 2, count: 150 }; + let (me, st) = std::thread::scope(|s| { + s.spawn(|| (unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }, run(c, &mut out))).join().unwrap() + }); + stop.store(true, Ordering::Relaxed); + drop(tx); + spinner.join().unwrap(); + waiter.join().unwrap(); + assert!(out.ok); + if let Some(p) = std::env::var_os("XCL_THREAD_SAMPLE_TEST_OUT") { + std::fs::write(p, &out.w).unwrap(); + } + let f = read(&out.w).expect("the file parses"); + eprintln!("thread sample test: {st:?}; {} threads, {} modules", f.threads.len(), f.modules.len()); + assert_eq!(f.samples.len(), 150); + assert_eq!(st.samples, 150); + assert!(f.end.is_some()); + let own = f.modules.iter().find(|m| m.2 == 1).expect("the test binary is a kind 1 module").clone(); + let ntdll = f.modules.iter().find(|m| m.3.to_ascii_lowercase().ends_with("\\ntdll.dll")).expect("ntdll is listed").clone(); + let inside = |a: u64, m: &(u64, u64, u8, String)| a >= m.0 && a < m.0 + m.1; + assert!(f.threads.iter().any(|t| t.0 == sp_id && t.2 == "ts-spinner"), "the spinner's name"); + assert!(f.threads.iter().all(|t| t.0 != me), "the sampler is not sampled"); + let mut spin_stopped = 0; + let mut spin_in_own = 0; + let mut spin_with_caller = 0; + let mut spin_cycles = 0u64; + let (mut wait_stopped, mut wait_in_ntdll, mut wait_unchanged) = (0, 0, 0); + let mut wait_noise_max = 0u64; + for (_, _, _, es) in &f.samples { + assert!(es.iter().all(|e| e.0 != me)); + for e in es { + if e.0 == sp_id { + spin_cycles += e.2; + if e.1 == STOPPED { + spin_stopped += 1; + spin_in_own += usize::from(inside(e.3[0], &own)); + spin_with_caller += usize::from(e.3.len() >= 2 && inside(e.3[1], &own)); + } + } + if e.0 == wt_id { + match e.1 { + STOPPED => { + wait_stopped += 1; + wait_in_ntdll += usize::from(inside(e.3[0], &ntdll)); + } + UNCHANGED => { + wait_unchanged += 1; + wait_noise_max = wait_noise_max.max(e.2); + } + _ => {} + } + } + } + } + eprintln!( + "spinner: {spin_stopped} stopped, {spin_in_own} in this binary, {spin_with_caller} with a caller, {spin_cycles} cycles; waiter: {wait_stopped} stopped ({wait_in_ntdll} in ntdll), {wait_unchanged} unchanged (at most {wait_noise_max} cycles between two)" + ); + // the spinner runs all along: stopped at every sample (its cycles move), in spin() + assert!(spin_stopped >= 140, "the spinner was stopped at nearly every sample"); + assert!(spin_in_own * 10 >= spin_stopped * 9, "the spinner's RIP is in this binary"); + assert!(spin_with_caller * 10 >= spin_stopped * 9, "its caller was unwound"); + assert!(spin_cycles > 0, "its cycle time moved"); + // the waiter: in ntdll when stopped, and mostly left unchanged + assert!(wait_stopped >= 1 && wait_in_ntdll == wait_stopped, "the waiter waits in ntdll"); + assert!(wait_unchanged >= 100, "a thread that does not run is not stopped again"); + } +} From f6cdc835c0f7a46baf8460019950211d7d80a284 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:17:54 +0100 Subject: [PATCH 2/3] Scripts: thread_sample.py reads an XCL_THREAD_SAMPLE file Per thread group (the thread's name, else its start address): CPU as a share of one core from the exact cycle times, the samples split into user code, a system call at work and a wait, the share of each module, and for the busiest groups (and always the thread that submits command lists) the top functions inclusive and self and the ntdll / win32u leaves. xcl.exe is named through its PDB (dbghelp via ctypes), other DLLs through the export table of the file at the recorded path. The title's own images are printed only as title.exe / title-dll plus a 4 KiB page offset, never by name or path. --log takes an xcl.log of a run with XCL_ACTIVITY=1 and gives ms per frame from its presents. The sampler's TRUNCATED frame (1) is printed as the callers past the stack copy. --selftest writes a synthetic file over the real ntdll (and xcl.exe with its PDB when XCL_EXE or target/release has one) and checks the shares, the names, the waits and that no title name is printed. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- scripts/thread_sample.py | 605 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 608 insertions(+), 1 deletion(-) create mode 100644 scripts/thread_sample.py diff --git a/README.md b/README.md index 0e0a8bbf2b..8097e33bd2 100644 --- a/README.md +++ b/README.md @@ -475,7 +475,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. its registers and copy the top of its stack. Written to a binary file (`XCL_THREAD_SAMPLE_FILE=`, else `xcl-thread-sample.bin` in the temp folder); `xcl.log` gets a line when it starts and one with its totals (stops, their mean and longest time) at - the end. + the end. `python scripts/thread_sample.py [--log xcl.log]` reads it: CPU per thread, + user code against system calls and waits, the top functions (xcl.exe by its PDB, DLLs by + their exports, the title's own images only as offsets). - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised (read, write or execute, the address, some registers and the callers on the stack), before the title's own handlers see them – for a title whose crash filter ends the process without a trace. diff --git a/scripts/thread_sample.py b/scripts/thread_sample.py new file mode 100644 index 0000000000..b416c03bca --- /dev/null +++ b/scripts/thread_sample.py @@ -0,0 +1,605 @@ +#!/usr/bin/env python3 +"""Reads an XCL_THREAD_SAMPLE file (crates/xcl/src/thread_sample.rs): where each thread's CPU +time goes, offline. + + python -I scripts/thread_sample.py [--log ] [--top 30] [--threads 8] + [--exe-dir DIR] (where xcl.exe + xcl.pdb are, if not at the recorded path) + +Per thread group (the name, else the start address): CPU (cycle time, exact) as % of one core, +the samples split in user code / a system call that works / a wait, the share of each module, +and for the busiest groups (and always the submit thread: the one whose stacks hold +q_execute_command_lists) the top functions inclusive and self, and the ntdll Nt* leaves. +Names: xcl.exe through its PDB (dbghelp, ctypes), ntdll / kernelbase / win32u / d3d12 / nvidia / +any DLL through the export table of the file at the recorded path (an address far from any +export: module+4 KiB page), the title's images as title.exe / title-dll + 4 KiB page (no +names). --log: presents in the sampled window from the 'activity (2 s)' lines of a run with +XCL_ACTIVITY=1, to give ms per frame. Never prints a title image's name or path. + python -I scripts/thread_sample.py --selftest writes a synthetic file from real modules and checks the result +""" +import bisect +import ctypes +import os +import re +import struct +import sys +from collections import Counter, defaultdict + +MAGIC = b'XCLTSMP1' +STOPPED, UNCHANGED, FAILED = 0, 1, 2 +# the walk's last frame when the next one's unwind data reaches past the stack copy (thread_sample.rs) +TRUNCATED = 1 +WAITS = re.compile(r'^(Nt|Zw)(WaitFor|Wait|DelayExecution|RemoveIoCompletion|SignalAndWait|ReplyWaitReceivePort|AlertThreadByThreadIdEx?$)|^NtUserMsgWaitForMultipleObjectsEx$|^NtUserGetMessage$|^NtUserWaitMessage$|^NtWaitForWorkViaWorkerFactory$|^NtWaitForAlertByThreadId$') +# ntdll's heap and lock functions: code that runs (an allocation, a spin before a lock's wait), never a +# wait even with 'Wait' in the name (the wait itself is the Nt* leaf under them). Counted as user, and +# shown apart as heap/lock. Internal names (Rtlp*) only show with ntdll symbols; the exported ones +# resolve from the export table. +HEAPLOCK = re.compile(r'^Rtlp?(AllocateHeap|FreeHeap|ReAllocateHeap|SizeHeap|LockHeap|UnlockHeap|WalkHeap|CompactHeap|' + r'AllocateHeapInternal|FreeHeapInternal|LowFragHeap\w*|Lfh\w*|Hp\w*|' + r'EnterCriticalSection|LeaveCriticalSection|TryEnterCriticalSection|WaitOnCriticalSection|' + r'EnterCriticalSectionContended|UnWaitCriticalSection|' + r'AcquireSRWLock\w*|ReleaseSRWLock\w*|TryAcquireSRWLock\w*|' + r'SleepConditionVariable\w*|WakeConditionVariable|WakeAllConditionVariable|WaitOnAddress|WakeAddress\w*|' + r'RunOnceExecuteOnce|RunOnceBeginInitialize)$') + + +# ---------------------------------------------------------------- the file +def read(path): + b = open(path, 'rb').read() + p = 0 + + def take(fmt): + nonlocal p + n = struct.calcsize(fmt) + if p + n > len(b): + raise EOFError + v = struct.unpack_from(fmt, b, p) + p += n + return v + + def name(): + (n,) = take(' len(b): + raise EOFError + s = b[p:p + n].decode('utf-8', 'replace') + p += n + return s + + if b[:8] != MAGIC: + raise SystemExit('%s: not an XCL_THREAD_SAMPLE file' % path) + p = 8 + ver, period, frm, count, pid, up, tsc, qpc, qpf = take('') + continue + if ch == '>': + depth = max(0, depth - 1) + continue + if depth == 0: + out.append(ch) + s = ''.join(out) + return s[5:] if s.startswith('xcl::') else s + + +class Symbols: + def __init__(self, f, exe_dir=None): + self.mods = [] # (base, end, label, kind, path) + title_dlls = 0 + # run_main (loader.rs) points PEB.ImageBaseAddress at the title, so the sampler's + # GetModuleHandleW(NULL) test marks xcl.exe kind 0: take it back by its file name + own_by_name = not any(k == 1 for (_, k, _) in f['modules'].values()) + for base in sorted(f['modules']): + size, kind, path = f['modules'][base] + if own_by_name and kind == 0 and path.replace('/', '\\').split('\\')[-1].lower() == 'xcl.exe': + kind = 1 + bn = os.path.basename(path.replace('/', '\\').split('\\')[-1]) or path + if kind == 2: + if bn.lower().endswith('.exe'): + label = 'title.exe' + else: + title_dlls += 1 + label = 'title-dll%d' % title_dlls + elif kind == 1: + label = 'xcl.exe' + else: + label = bn + self.mods.append((base, base + size, label, kind, path)) + self.bases = [m[0] for m in self.mods] + self.exports = {} + self.pdb = None + own = [m for m in self.mods if m[3] == 1] + if own: + base, end, _, _, path = own[0] + exe = path + if exe_dir: + exe = os.path.join(exe_dir, os.path.basename(path.replace('/', '\\').split('\\')[-1])) + self.pdb = Dbghelp(exe, base, end - base) + self.cache = {} + + def module(self, a): + i = bisect.bisect_right(self.bases, a) - 1 + if i >= 0 and a < self.mods[i][1]: + return self.mods[i] + return None + + def sym(self, a): + """(module label, category, function key, exact name or None)""" + if a in self.cache: + return self.cache[a] + m = self.module(a) + if a == TRUNCATED: + r = ('?', 'other', '[callers past the stack copy]', None) + elif m is None: + r = ('?', 'other', 'unknown 0x%x' % (a & ~0xFFF), None) + else: + base, end, label, kind, path = m + rva = a - base + cat = category(label, kind) + if kind == 2: + r = (label, cat, '%s+0x%x' % (label, rva & ~0xFFF), None) + elif kind == 1: + n = self.pdb.name(a) if self.pdb else None + r = (label, cat, 'xcl!' + short(n) if n else 'xcl.exe+0x%x' % (rva & ~0xFFF), n) + else: + if path not in self.exports: + self.exports[path] = pe_exports(path) + rv, names = self.exports[path] + j = bisect.bisect_right(rv, rva) - 1 + if j >= 0 and rva - rv[j] < 0x800: + r = (label, cat, '%s!%s' % (label.rsplit('.', 1)[0], names[j]), names[j]) + else: + r = (label, cat, '%s+0x%x' % (label, rva & ~0xFFF), None) + self.cache[a] = r + return r + + +def category(label, kind): + l = label.lower() + if kind == 1: + return 'xcl.exe' + if kind == 2: + return 'title' + if l == 'ntdll.dll': + return 'ntdll' + if l == 'win32u.dll': + return 'win32u' + if l in ('kernelbase.dll', 'kernel32.dll'): + return 'kernel32/base' + if l.startswith('d3d12'): + return 'd3d12' + if l.startswith('nv'): + return 'nvidia' + if l.startswith('dxgi') or l.startswith('dxcore'): + return 'dxgi' + if l.startswith('ucrtbase') or l.startswith('vcruntime') or l.startswith('msvcp'): + return 'crt' + return 'other' + + +# ---------------------------------------------------------------- the profile +def profile(f, syms): + """per tid: dict(ms, cycles, cls Counter, mods Counter, incl Counter, self Counter, nt Counter, n)""" + last = {} + per = defaultdict(lambda: dict(ms=0.0, cycles=0, cls=Counter(), flag=Counter(), mods=Counter(), incl=Counter(), self=Counter(), nt=Counter(), n=0, submit=0.0)) + prev_up = None + for i, up, t, es in f['samples']: + dt = (up - prev_up) * 1000.0 if prev_up is not None else f['period_ms'] + if dt <= 0 or dt > 50 * f['period_ms']: + dt = f['period_ms'] + prev_up = up + for tid, st, cy, fr in es: + d = per[tid] + d['cycles'] += cy + d['n'] += 1 + d['ms'] += dt + if st == STOPPED: + last[tid] = fr + elif st == FAILED: + d['cls']['failed'] += dt + continue + fr = last.get(tid) + if not fr: + d['cls']['failed'] += dt + continue + ss = [syms.sym(a) for a in fr] + leaf = ss[0] + nt = leaf[1] in ('ntdll', 'win32u') and leaf[3] + if nt and HEAPLOCK.match(leaf[3]): + cls = 'user' + d['flag']['heaplock'] += dt + elif nt and WAITS.match(leaf[3]): + cls = 'wait' + elif leaf[1] in ('ntdll', 'win32u') and leaf[3] and (leaf[3].startswith('Nt') or leaf[3].startswith('Zw')): + cls = 'syscall' + else: + cls = 'user' + d['cls'][cls] += dt + # a stack carried (not stopped again) whose leaf is not a wait: the sampler took it as one only + # because its RIP was in ntdll / win32u (thread_sample.rs' leaf-module rule), so short bursts + # of that thread between two samples are charged to this old stack + if st == UNCHANGED and cls != 'wait': + d['flag']['stale'] += dt + d['mods'][leaf[1]] += dt + d['self'][leaf[2]] += dt + if leaf[1] in ('ntdll', 'win32u') and leaf[3]: + d['nt'][leaf[3]] += dt + seen = set() + for s in ss: + if s[2] not in seen: + seen.add(s[2]) + d['incl'][s[2]] += dt + if any(s[3] and 'q_execute_command_lists' in s[3] for s in ss): + d['submit'] += dt + return per + + +def main(argv): + if '--selftest' in argv: + return selftest() + args = {'--top': '30', '--threads': '8'} + pos = [] + it = iter(argv) + for a in it: + if a in ('--log', '--top', '--threads', '--exe-dir'): + args[a] = next(it) + else: + pos.append(a) + if not pos: + print(__doc__) + return 2 + f = read(pos[0]) + syms = Symbols(f, args.get('--exe-dir')) + top, nthreads = int(args['--top']), int(args['--threads']) + ss = f['samples'] + if not ss: + print('no samples') + return 1 + e = f['end'] + t_end_qpc = e['qpc'] if e else None + wall = ss[-1][1] - ss[0][1] + tsc_hz = None + if e and e['qpc'] > f['qpc'] and f['qpf']: + tsc_hz = (e['tsc'] - f['tsc']) / ((e['qpc'] - f['qpc']) / f['qpf']) + print('== thread sample: %d samples from %.1f to %.1f s (%.1f s, mean period %.2f ms, asked %d ms)%s' % ( + len(ss), ss[0][1], ss[-1][1], wall, 1000 * wall / max(1, len(ss) - 1), f['period_ms'], ' TRUNCATED (no end record)' if f['truncated'] or not e else '')) + if e and tsc_hz: + us = lambda t: t * 1e6 / tsc_hz + print(' %d threads seen; %d stops (mean %.1f us, longest %.0f us), %d unchanged (not stopped), %d failed, %d late; sampler %.0f us a sample = %.1f %% of a core' % ( + e['threads'], e['stops'], us(e['stops_tsc']) / max(1, e['stops']), us(e['longest_stop_tsc']), e['unchanged'], e['failed'], e['late'], + us(e['sampler_tsc']) / max(1, e['samples']), 100 * us(e['sampler_tsc']) / 1e6 / max(1e-9, wall))) + print(' TSC %.3f GHz (cycle times converted with it)' % (tsc_hz / 1e9)) + print(' xcl.exe symbols: %s' % ('PDB loaded' if syms.pdb and syms.pdb.ok else 'NOT loaded (xcl.exe+page only)')) + frames = None + if '--log' in args: + frames = presents_between(args['--log'], ss[0][1], ss[-1][1]) + if frames: + print(' presents in the window (activity lines, interpolated): %.1f -> %.1f ms a frame' % (frames, 1000 * wall / frames)) + else: + print(' presents in the window: unknown (no activity lines around it; run with XCL_ACTIVITY=1)') + per = profile(f, syms) + # groups + groups = defaultdict(list) + for tid in per: + start, nm = f['threads'].get(tid, (0, '')) + key = nm if nm else 'start ' + (syms.sym(start)[2] if start else '?') + groups[key].append(tid) + rows = [] + for key, tids in groups.items(): + g = dict(ms=0.0, cycles=0, cls=Counter(), flag=Counter(), mods=Counter(), incl=Counter(), self=Counter(), nt=Counter(), submit=0.0) + for t in tids: + for k in ('ms', 'cycles', 'submit'): + g[k] += per[t][k] + for k in ('cls', 'flag', 'mods', 'incl', 'self', 'nt'): + g[k].update(per[t][k]) + rows.append((key, tids, g)) + cpu = lambda g: g['cycles'] / tsc_hz if tsc_hz else 0.0 + rows.sort(key=lambda r: -cpu(r[2])) + total_cpu = sum(cpu(r[2]) for r in rows) + print('\n== threads by CPU (cycle time over the %.1f s; %% of one core, all threads of the group; samples: user / syscall / wait / failed, then heap/lock (in user) and stale (carried from a leaf that is not a wait); leaf module shares of all samples)' % wall) + print(' all threads: %.1f cores busy on average' % (total_cpu / max(1e-9, wall))) + for key, tids, g in rows[:max(nthreads * 3, 25)]: + ms = max(1e-9, g['ms']) + c = g['cls'] + mods = ', '.join('%s %.0f%%' % (m, 100 * v / ms) for m, v in g['mods'].most_common(5)) + print(' %6.1f %% %-40s %2d thr user %3.0f%% sys %3.0f%% wait %3.0f%% fail %2.0f%% heap/lock %3.0f%% stale %3.0f%% | %s%s' % ( + 100 * cpu(g) / max(1e-9, wall), label(key), len(tids), 100 * c['user'] / ms, 100 * c['syscall'] / ms, 100 * c['wait'] / ms, + 100 * c['failed'] / ms, 100 * g['flag']['heaplock'] / ms, 100 * g['flag']['stale'] / ms, mods, ' <- SUBMIT' if g['submit'] > 0.05 * ms else '')) + busy = [r for r in rows if r[2]['submit'] > 0.05 * r[2]['ms']] + busy += [r for r in rows[:nthreads] if r not in busy] + for key, tids, g in busy: + ms = max(1e-9, g['ms']) + per_frame = (lambda v: ' %7.2f ms/frame' % (v / len(tids) / frames)) if frames else (lambda v: '') + print('\n== %s%s (%d thread(s) %s): CPU %.1f %% of a core each; times = samples x period, summed over its threads%s' % ( + label(key), ' [SUBMIT]' if g['submit'] > 0.05 * ms else '', len(tids), ','.join(map(str, tids[:8])), 100 * cpu(g) / max(1e-9, wall) / len(tids), + '; ms/frame = per thread' if frames else '')) + print(' samples: user %.0f %%, syscall %.0f %%, wait %.0f %%, failed %.0f %%' % tuple(100 * g['cls'][k] / ms for k in ('user', 'syscall', 'wait', 'failed'))) + if g['flag']['heaplock'] or g['flag']['stale']: + print(' of which: heap/lock (user) %.0f %%; stale %.0f %% (stacks carried from a leaf that is not a wait: short bursts may hide there)' % ( + 100 * g['flag']['heaplock'] / ms, 100 * g['flag']['stale'] / ms)) + print(' leaf modules: ' + ', '.join('%s %.1f%%' % (m, 100 * v / ms) for m, v in g['mods'].most_common())) + print(' -- top %d inclusive (any of the first 8 frames)' % top) + for fn, v in g['incl'].most_common(top): + print(' %5.1f %% %8.0f ms%s %s' % (100 * v / ms, v, per_frame(v), fn)) + print(' -- top %d self (leaf)' % top) + for fn, v in g['self'].most_common(top): + print(' %5.1f %% %8.0f ms%s %s' % (100 * v / ms, v, per_frame(v), fn)) + if g['nt']: + print(' -- ntdll / win32u leaves (system calls, waits included)') + for fn, v in g['nt'].most_common(top): + print(' %5.1f %% %8.0f ms%s %s%s' % (100 * v / ms, v, per_frame(v), fn, ' (heap/lock)' if HEAPLOCK.match(fn) else ' (wait)' if WAITS.match(fn) else '')) + return 0 + + +def label(key): + return key if len(key) <= 40 else key[:37] + '...' + + +def presents_between(log, t0, t1): + # xcl.log lines start with the log time: `[ 12.345][ tid][INFO] activity (2 s): 120 presents, ...` + pts = [] + rx = re.compile(r'^\[\s*([0-9.]+)\].*\bactivity \(2 s\): ([0-9]+) presents') + total = 0 + for line in open(log, encoding='utf-8', errors='replace'): + m = rx.search(line) + if m: + total += int(m.group(2)) + pts.append((float(m.group(1)), total)) + if len(pts) < 2: + return None + + def at(t): + for (a, pa), (b, pb) in zip(pts, pts[1:]): + if a <= t <= b: + return pa + (pb - pa) * (t - a) / max(1e-9, b - a) + return None + a, b = at(t0), at(t1) + return (b - a) if a is not None and b is not None and b > a else None + + +# ---------------------------------------------------------------- self test +def selftest(): + """A synthetic file on real modules: a 'submit' thread 60 % in xcl.exe's dump_threads (any + function the PDB names) under q_execute_command_lists-free frames, 30 % in ntdll's + NtGetWriteWatch, 10 % waiting in NtWaitForSingleObject; a 'waiter' always unchanged in + NtWaitForAlertByThreadId; a title-image thread; an 'allocator' stopped in RtlAllocateHeap and later + in RtlEnterCriticalSection, carried unchanged after each (user and heap/lock, never a wait; the + carried samples stale). Checks the shares and names printed.""" + import tempfile + sysdir = os.path.join(os.environ.get('SystemRoot', r'C:\Windows'), 'System32') + ntdll = os.path.join(sysdir, 'ntdll.dll') + rv, names = pe_exports(ntdll) + assert names, 'ntdll exports read' + rva = dict((n, r) for r, n in zip(rv, names)) + for n in ('NtGetWriteWatch', 'NtWaitForSingleObject', 'NtWaitForAlertByThreadId', 'NtProtectVirtualMemory', 'NtQueryVirtualMemory', + 'RtlAllocateHeap', 'RtlEnterCriticalSection'): + assert n in rva, n + # an xcl.exe with its xcl.pdb next to it (XCL_EXE, else this tree's release build): its names are checked too + exe = os.environ.get('XCL_EXE', os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'target', 'release', 'xcl.exe')) + xbase, xsize = 0x7FF6_0000_0000, 0x0200_0000 + nbase, nsize = 0x7FFC_0000_0000, 0x0020_0000 + tbase, tsize = 0x0001_4000_0000, 0x1000_0000 + dh = Dbghelp(exe, xbase, xsize) if os.path.exists(exe) else None + fa = dh.address('xcl::eh::dump_threads') if dh and dh.ok else None + print('selftest: xcl.exe %s, PDB %s, dump_threads at %s' % (exe, 'loaded' if dh and dh.ok else 'NOT loaded', hex(fa) if fa else None)) + out = bytearray() + out += MAGIC + struct.pack(' Date: Sun, 29 Nov 2026 00:57:30 +0100 Subject: [PATCH 3/3] Scripts: thread_sample.py gives CPU shares for a capture without its end record The TSC rate the cycle times are converted with came only from the end record ('E'), so a capture still being written, or one from a run that ended before the sampler wrote it, showed every thread at 0.0 % of a core although its samples hold all the cycle deltas (andrewDoing on #3232). Without the end record the rate is now taken from the first and last sample's TSC over their log uptime, said as approximate; with fewer than two timed samples the shares are said to be unavailable and the cycles are shown. --selftest: the synthetic samples carry real TSC values, and the same file without its end record gives the same ~91 % for the busy thread. Co-Authored-By: Claude Opus 5.5 --- scripts/thread_sample.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/scripts/thread_sample.py b/scripts/thread_sample.py index b416c03bca..3a744e1134 100644 --- a/scripts/thread_sample.py +++ b/scripts/thread_sample.py @@ -404,6 +404,15 @@ def main(argv): tsc_hz = (e['tsc'] - f['tsc']) / ((e['qpc'] - f['qpc']) / f['qpf']) print('== thread sample: %d samples from %.1f to %.1f s (%.1f s, mean period %.2f ms, asked %d ms)%s' % ( len(ss), ss[0][1], ss[-1][1], wall, 1000 * wall / max(1, len(ss) - 1), f['period_ms'], ' TRUNCATED (no end record)' if f['truncated'] or not e else '')) + if tsc_hz is None: + # no end record (a capture still being written, or a run that ended before it): the TSC + # rate from the first and last sample's TSC over their log uptime, approximate + pts = [(up, t) for _, up, t, _ in ss] + if len(pts) >= 2 and pts[-1][0] > pts[0][0] and pts[-1][1] > pts[0][1]: + tsc_hz = (pts[-1][1] - pts[0][1]) / (pts[-1][0] - pts[0][0]) + print(' no end record: TSC %.3f GHz estimated from the first and last sample (TSC over log uptime): CPU shares approximate' % (tsc_hz / 1e9)) + else: + print(' no end record and fewer than two timed samples: CPU shares unavailable, cycles shown instead') if e and tsc_hz: us = lambda t: t * 1e6 / tsc_hz print(' %d threads seen; %d stops (mean %.1f us, longest %.0f us), %d unchanged (not stopped), %d failed, %d late; sampler %.0f us a sample = %.1f %% of a core' % ( @@ -438,21 +447,23 @@ def main(argv): rows.sort(key=lambda r: -cpu(r[2])) total_cpu = sum(cpu(r[2]) for r in rows) print('\n== threads by CPU (cycle time over the %.1f s; %% of one core, all threads of the group; samples: user / syscall / wait / failed, then heap/lock (in user) and stale (carried from a leaf that is not a wait); leaf module shares of all samples)' % wall) - print(' all threads: %.1f cores busy on average' % (total_cpu / max(1e-9, wall))) + share = lambda g: '%6.1f %%' % (100 * cpu(g) / max(1e-9, wall)) if tsc_hz else '%5.2f Gcy' % (g['cycles'] / 1e9) + print(' all threads: %s' % ('%.1f cores busy on average' % (total_cpu / max(1e-9, wall)) if tsc_hz else 'CPU share unavailable (%.2f G cycles)' % (sum(r[2]['cycles'] for r in rows) / 1e9))) for key, tids, g in rows[:max(nthreads * 3, 25)]: ms = max(1e-9, g['ms']) c = g['cls'] mods = ', '.join('%s %.0f%%' % (m, 100 * v / ms) for m, v in g['mods'].most_common(5)) - print(' %6.1f %% %-40s %2d thr user %3.0f%% sys %3.0f%% wait %3.0f%% fail %2.0f%% heap/lock %3.0f%% stale %3.0f%% | %s%s' % ( - 100 * cpu(g) / max(1e-9, wall), label(key), len(tids), 100 * c['user'] / ms, 100 * c['syscall'] / ms, 100 * c['wait'] / ms, + print(' %s %-40s %2d thr user %3.0f%% sys %3.0f%% wait %3.0f%% fail %2.0f%% heap/lock %3.0f%% stale %3.0f%% | %s%s' % ( + share(g), label(key), len(tids), 100 * c['user'] / ms, 100 * c['syscall'] / ms, 100 * c['wait'] / ms, 100 * c['failed'] / ms, 100 * g['flag']['heaplock'] / ms, 100 * g['flag']['stale'] / ms, mods, ' <- SUBMIT' if g['submit'] > 0.05 * ms else '')) busy = [r for r in rows if r[2]['submit'] > 0.05 * r[2]['ms']] busy += [r for r in rows[:nthreads] if r not in busy] for key, tids, g in busy: ms = max(1e-9, g['ms']) per_frame = (lambda v: ' %7.2f ms/frame' % (v / len(tids) / frames)) if frames else (lambda v: '') - print('\n== %s%s (%d thread(s) %s): CPU %.1f %% of a core each; times = samples x period, summed over its threads%s' % ( - label(key), ' [SUBMIT]' if g['submit'] > 0.05 * ms else '', len(tids), ','.join(map(str, tids[:8])), 100 * cpu(g) / max(1e-9, wall) / len(tids), + print('\n== %s%s (%d thread(s) %s): CPU %s of a core each; times = samples x period, summed over its threads%s' % ( + label(key), ' [SUBMIT]' if g['submit'] > 0.05 * ms else '', len(tids), ','.join(map(str, tids[:8])), + '%.1f %%' % (100 * cpu(g) / max(1e-9, wall) / len(tids)) if tsc_hz else 'unavailable', '; ms/frame = per thread' if frames else '')) print(' samples: user %.0f %%, syscall %.0f %%, wait %.0f %%, failed %.0f %%' % tuple(100 * g['cls'][k] / ms for k in ('user', 'syscall', 'wait', 'failed'))) if g['flag']['heaplock'] or g['flag']['stale']: @@ -558,11 +569,12 @@ def thr(tid, start, nm): es.append((4, STOPPED, 1000, (nbase + rva['RtlAllocateHeap' if i == 0 else 'RtlEnterCriticalSection'] + 0x10, caller))) else: es.append((4, UNCHANGED, 1000, ())) - rec = b'S' + struct.pack('