From 4b8ae4582fb22101da43c263146c785905b57db9 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:36:54 -0600 Subject: [PATCH 1/2] d3d12-loader: close thread handles on drop, guard cpu delta, avoid stderr panics (D3D12-LOADER-PROFILE-AND-STACKS-SAFETY) --- d3d12/crates/leonida-loader/src/profile.rs | 180 +++++++++++++++++++-- d3d12/crates/leonida-loader/src/stacks.rs | 90 +++++++++-- 2 files changed, 242 insertions(+), 28 deletions(-) diff --git a/d3d12/crates/leonida-loader/src/profile.rs b/d3d12/crates/leonida-loader/src/profile.rs index 62e2a16878..6ba0737ec7 100644 --- a/d3d12/crates/leonida-loader/src/profile.rs +++ b/d3d12/crates/leonida-loader/src/profile.rs @@ -49,14 +49,27 @@ struct Thread { samples: u64, } -fn cpu(thread: HANDLE) -> u64 { +impl Drop for Thread { + fn drop(&mut self) { + if !self.handle.is_null() { + // SAFETY: opened by `choose` (or a test); closed once on drop so + // failed `write` calls or unwinds never leak thread handles. + unsafe { CloseHandle(self.handle) }; + self.handle = std::ptr::null_mut(); + } + } +} + +fn cpu(thread: HANDLE) -> Option { // SAFETY: zeroed is a valid FILETIME, and the calls write them. let mut t: [FILETIME; 4] = unsafe { std::mem::zeroed() }; let [a, b, c, d] = &mut t; // SAFETY: an open thread; the pointers are to the structures above. - unsafe { GetThreadTimes(thread, a, b, c, d) }; + if unsafe { GetThreadTimes(thread, a, b, c, d) } == 0 { + return None; + } let of = |f: &FILETIME| u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime); - of(&t[2]) + of(&t[3]) + Some(of(&t[2]).saturating_add(of(&t[3]))) } /// Reads `LEONIDA_PROFILE` and, if set, starts the thread that samples. @@ -76,7 +89,7 @@ pub fn profile_on_schedule(phase: fn() -> u32) { fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) { std::thread::sleep(from.saturating_sub(start.elapsed())); - eprintln!("Leonida: the profile begins"); + let _ = writeln!(std::io::stderr(), "Leonida: the profile begins"); let mut threads: HashMap = HashMap::new(); let mut chosen: Vec = Vec::new(); let mut counts: HashMap<(u32, u32, Vec), u64> = HashMap::new(); @@ -105,9 +118,9 @@ fn profile((from, to, every, file): (Duration, Duration, Duration, String), star } choose(&mut threads, &mut chosen); if let Err(e) = write(&file, &threads, &counts, &phases, rounds) { - eprintln!("Leonida: the profile was not written: {e}"); + let _ = writeln!(std::io::stderr(), "Leonida: the profile was not written: {e}"); } else { - eprintln!("Leonida: the profile is in {file}"); + let _ = writeln!(std::io::stderr(), "Leonida: the profile is in {file}"); } } @@ -119,7 +132,7 @@ fn choose(threads: &mut HashMap, chosen: &mut Vec) { // profile's life, so the id stays its own. let handle = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) }; - let first = if handle.is_null() { 0 } else { cpu(handle) }; + let first = if handle.is_null() { 0 } else { cpu(handle).unwrap_or(0) }; Thread { handle, start: if handle.is_null() { String::new() } else { locate(start_of(handle)) }, @@ -133,8 +146,10 @@ fn choose(threads: &mut HashMap, chosen: &mut Vec) { } let mut ran: Vec<(u64, u32)> = Vec::new(); for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) { - t.now = cpu(t.handle); - ran.push((t.now - t.last, id)); + if let Some(now) = cpu(t.handle) { + t.now = now.max(t.now); + } + ran.push((t.now.saturating_sub(t.last), id)); t.last = t.now; } ran.sort_unstable_by(|a, b| b.cmp(a)); @@ -169,11 +184,14 @@ fn write( } let mut names: HashMap = HashMap::new(); for (id, t) in threads { - writeln!(out, "thread {id} {} {} {} {}", t.start, (t.now - t.first) / 10_000, t.samples, t.name)?; - if !t.handle.is_null() { - // SAFETY: opened by `choose`. - unsafe { CloseHandle(t.handle) }; - } + writeln!( + out, + "thread {id} {} {} {} {}", + t.start, + t.now.saturating_sub(t.first) / 10_000, + t.samples, + t.name + )?; } for ((id, phase, frames), n) in counts { write!(out, "stack {id} {phase} {n} ")?; @@ -207,4 +225,138 @@ mod tests { assert_eq!(asked("-1,160,5,x"), None); assert_eq!(asked("1,160,0,x"), None); } + + #[test] + fn cpu_handles_invalid_handle_and_write_saturates_underflow() { + assert_eq!(cpu(std::ptr::null_mut()), None); + let mut threads = HashMap::new(); + threads.insert( + 7, + Thread { + handle: std::ptr::null_mut(), + start: "mod+0x10".to_string(), + name: "worker".to_string(), + first: 50_000, + last: 50_000, + now: 10_000, + samples: 2, + }, + ); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let path = std::env::temp_dir().join(format!( + "leonida-profile-saturate-{}-{nanos}.txt", + std::process::id(), + )); + write( + path.to_str().expect("utf8 path"), + &threads, + &HashMap::new(), + &HashMap::new(), + 1, + ) + .expect("write profile"); + let text = std::fs::read_to_string(&path).expect("read profile"); + let _ = std::fs::remove_file(&path); + assert!(text.contains("thread 7 mod+0x10 0 2 worker"), "{text:?}"); + } + + #[test] + fn profile_writes_file_and_closes_handles_when_stderr_pipe_is_closed() { + use std::path::PathBuf; + use windows_sys::Win32::Foundation::GetHandleInformation; + use windows_sys::Win32::System::Threading::GetCurrentThreadId; + const CHILD_DIR_ENV: &str = "PROFILE_CLOSED_STDERR_DIR"; + if let Some(dir) = std::env::var_os(CHILD_DIR_ENV) { + let mut buf = [0u8; 1]; + let _ = std::io::Read::read(&mut std::io::stdin(), &mut buf); + assert!( + writeln!(std::io::stderr(), "probe").is_err(), + "expected writing to a closed stderr pipe to fail" + ); + let dir = PathBuf::from(dir); + let out_file = dir.join("profile.txt"); + profile( + ( + Duration::ZERO, + Duration::from_millis(20), + Duration::from_millis(5), + out_file.to_string_lossy().into_owned(), + ), + Instant::now(), + || 0, + ); + // Verify Drop closes thread handles even when write() fails early. + // SAFETY: opens a real handle to the current thread. + let raw = unsafe { OpenThread(THREAD_QUERY_INFORMATION, 0, GetCurrentThreadId()) }; + assert!(!raw.is_null()); + { + let mut threads = HashMap::new(); + threads.insert( + 1, + Thread { + handle: raw, + start: String::new(), + name: String::new(), + first: 0, + last: 0, + now: 0, + samples: 0, + }, + ); + let missing = dir.join("nonexistent-dir").join("profile.txt"); + assert!(write( + missing.to_str().expect("utf8"), + &threads, + &HashMap::new(), + &HashMap::new(), + 0, + ) + .is_err()); + } + let mut flags = 0u32; + // SAFETY: single-threaded child process; querying whether `raw` was closed by Drop. + assert_eq!(unsafe { GetHandleInformation(raw, &mut flags) }, 0); + return; + } + struct TempDir(PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let dir = TempDir(std::env::temp_dir().join(format!( + "leonida-profile-closed-stderr-{}-{nanos}", + std::process::id(), + ))); + std::fs::create_dir_all(&dir.0).expect("create temp dir"); + let exe = std::env::current_exe().expect("current test executable"); + let mut child = std::process::Command::new(exe) + .env(CHILD_DIR_ENV, &dir.0) + .args([ + "--exact", + "profile::tests::profile_writes_file_and_closes_handles_when_stderr_pipe_is_closed", + "--nocapture", + ]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn closed-stderr child"); + drop(child.stderr.take()); + drop(child.stdin.take()); + let output = child.wait_with_output().expect("wait for child"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "profile failed on closed stderr (status={:?}, stdout={stdout})", + output.status, + ); + let written = std::fs::read_to_string(dir.0.join("profile.txt")).expect("profile.txt"); + assert!(written.contains("rounds "), "{written:?}"); + } } diff --git a/d3d12/crates/leonida-loader/src/stacks.rs b/d3d12/crates/leonida-loader/src/stacks.rs index dcfd1eb5bc..e984957845 100644 --- a/d3d12/crates/leonida-loader/src/stacks.rs +++ b/d3d12/crates/leonida-loader/src/stacks.rs @@ -97,35 +97,50 @@ pub(crate) fn other_threads() -> Vec { ids } -/// Prints every other thread's stack to stderr. Each thread is suspended -/// only while its context is read and unwound into a buffer allocated -/// beforehand (it may hold the heap lock). +struct ThreadHandle(HANDLE); + +impl Drop for ThreadHandle { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: opened by `OpenThread`; closed once on drop. + unsafe { CloseHandle(self.0) }; + self.0 = std::ptr::null_mut(); + } + } +} + +/// Prints every other thread's stack to stderr without panicking if stderr +/// fails (e.g. a closed pipe at shutdown). Each thread is suspended only while +/// its context is read and unwound into a buffer allocated beforehand (it may +/// hold the heap lock). pub fn dump_stacks() { + use std::io::Write as _; let ids = other_threads(); - eprintln!("Leonida: stacks of {} threads", ids.len()); + let _ = writeln!(std::io::stderr(), "Leonida: stacks of {} threads", ids.len()); for id in ids { // SAFETY: opens a thread of our own process. - let thread = unsafe { + let handle = unsafe { OpenThread( THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id, ) }; - if thread.is_null() { + if handle.is_null() { continue; } - let (frames, (priority, base, affinity)) = frames_of(thread); - eprintln!( - " thread {id} \"{}\" start {} priority {priority} (base {base}) affinity {affinity:#x}", - name_of(thread), - locate(start_of(thread)) + let thread = ThreadHandle(handle); + let (frames, (priority, base, affinity)) = frames_of(thread.0); + let name = name_of(thread.0); + let start = locate(start_of(thread.0)); + drop(thread); + let _ = writeln!( + std::io::stderr(), + " thread {id} \"{name}\" start {start} priority {priority} (base {base}) affinity {affinity:#x}", ); for (i, pc) in frames.into_iter().enumerate() { - eprintln!(" #{i:<2} {}", locate(pc as usize)); + let _ = writeln!(std::io::stderr(), " #{i:<2} {}", locate(pc as usize)); } - // SAFETY: we opened it. - unsafe { CloseHandle(thread) }; } } @@ -255,4 +270,51 @@ mod tests { assert_eq!(secs("30, 5,x,-2,inf,NaN,1e20"), [0.0, 5.0, 30.0]); assert!(schedule("").is_empty()); } + + #[test] + fn dump_stacks_does_not_panic_when_stderr_pipe_is_closed() { + use std::io::Write as _; + const CHILD_ENV: &str = "STACKS_CLOSED_STDERR_TEST"; + if std::env::var_os(CHILD_ENV).is_some() { + let mut buf = [0u8; 1]; + let _ = std::io::Read::read(&mut std::io::stdin(), &mut buf); + assert!( + writeln!(std::io::stderr(), "probe").is_err(), + "expected writing to a closed stderr pipe to fail" + ); + let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>(); + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let parked = std::thread::spawn(move || { + let _ = ready_tx.send(()); + let _ = stop_rx.recv(); + }); + let _ = ready_rx.recv(); + dump_stacks(); + let _ = stop_tx.send(()); + let _ = parked.join(); + return; + } + let exe = std::env::current_exe().expect("current test executable"); + let mut child = std::process::Command::new(exe) + .env(CHILD_ENV, "1") + .args([ + "--exact", + "stacks::tests::dump_stacks_does_not_panic_when_stderr_pipe_is_closed", + "--nocapture", + ]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn closed-stderr child"); + drop(child.stderr.take()); + drop(child.stdin.take()); + let output = child.wait_with_output().expect("wait for child"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "dump_stacks failed on closed stderr (status={:?}, stdout={stdout})", + output.status, + ); + } } From b07f64346a28bc55109643ef2b9d60631ac055b4 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:24:47 -0600 Subject: [PATCH 2/2] d3d12-loader: run profile/stacks tests in default workspace build, guard missing first cpu(), and test ThreadHandle drop --- d3d12/crates/leonida-loader/src/lib.rs | 4 +- d3d12/crates/leonida-loader/src/profile.rs | 45 ++++++++++++++-------- d3d12/crates/leonida-loader/src/stacks.rs | 13 +++++++ 3 files changed, 45 insertions(+), 17 deletions(-) diff --git a/d3d12/crates/leonida-loader/src/lib.rs b/d3d12/crates/leonida-loader/src/lib.rs index b41ca1945b..3008d422a3 100644 --- a/d3d12/crates/leonida-loader/src/lib.rs +++ b/d3d12/crates/leonida-loader/src/lib.rs @@ -37,9 +37,9 @@ pub mod natives; pub mod prepare; pub(crate) mod publish; pub mod resolve; -#[cfg(all(windows, feature = "diagnostics"))] +#[cfg(all(windows, any(feature = "diagnostics", test)))] mod profile; -#[cfg(all(windows, feature = "diagnostics"))] +#[cfg(all(windows, any(feature = "diagnostics", test)))] mod stacks; #[cfg(windows)] mod threads; diff --git a/d3d12/crates/leonida-loader/src/profile.rs b/d3d12/crates/leonida-loader/src/profile.rs index 6ba0737ec7..80b8cd8afb 100644 --- a/d3d12/crates/leonida-loader/src/profile.rs +++ b/d3d12/crates/leonida-loader/src/profile.rs @@ -42,8 +42,10 @@ struct Thread { handle: HANDLE, start: String, name: String, - /// Its processor time, 100 ns: at first, when last chosen, now. - first: u64, + /// Its processor time, 100 ns: at first successful sample (`None` until + /// `cpu()` succeeds so a failed initial query does not turn the next + /// sample into a lifetime total), when last chosen, and now. + first: Option, last: u64, now: u64, samples: u64, @@ -74,6 +76,7 @@ fn cpu(thread: HANDLE) -> Option { /// Reads `LEONIDA_PROFILE` and, if set, starts the thread that samples. /// `phase` is asked at each round. +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub fn profile_on_schedule(phase: fn() -> u32) { let Ok(list) = std::env::var("LEONIDA_PROFILE") else { return; @@ -132,14 +135,15 @@ fn choose(threads: &mut HashMap, chosen: &mut Vec) { // profile's life, so the id stays its own. let handle = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) }; - let first = if handle.is_null() { 0 } else { cpu(handle).unwrap_or(0) }; + let first = if handle.is_null() { None } else { cpu(handle) }; + let baseline = first.unwrap_or(0); Thread { handle, start: if handle.is_null() { String::new() } else { locate(start_of(handle)) }, name: if handle.is_null() { String::new() } else { name_of(handle) }, first, - last: first, - now: first, + last: baseline, + now: baseline, samples: 0, } }); @@ -147,6 +151,10 @@ fn choose(threads: &mut HashMap, chosen: &mut Vec) { let mut ran: Vec<(u64, u32)> = Vec::new(); for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) { if let Some(now) = cpu(t.handle) { + if t.first.is_none() { + t.first = Some(now); + t.last = now; + } t.now = now.max(t.now); } ran.push((t.now.saturating_sub(t.last), id)); @@ -184,14 +192,8 @@ fn write( } let mut names: HashMap = HashMap::new(); for (id, t) in threads { - writeln!( - out, - "thread {id} {} {} {} {}", - t.start, - t.now.saturating_sub(t.first) / 10_000, - t.samples, - t.name - )?; + let cpu_ms = t.first.map_or(0, |first| t.now.saturating_sub(first) / 10_000); + writeln!(out, "thread {id} {} {} {} {}", t.start, cpu_ms, t.samples, t.name)?; } for ((id, phase, frames), n) in counts { write!(out, "stack {id} {phase} {n} ")?; @@ -236,12 +238,24 @@ mod tests { handle: std::ptr::null_mut(), start: "mod+0x10".to_string(), name: "worker".to_string(), - first: 50_000, + first: Some(50_000), last: 50_000, now: 10_000, samples: 2, }, ); + threads.insert( + 8, + Thread { + handle: std::ptr::null_mut(), + start: "mod+0x20".to_string(), + name: "no-first".to_string(), + first: None, + last: 0, + now: 90_000, + samples: 1, + }, + ); let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_nanos()); @@ -260,6 +274,7 @@ mod tests { let text = std::fs::read_to_string(&path).expect("read profile"); let _ = std::fs::remove_file(&path); assert!(text.contains("thread 7 mod+0x10 0 2 worker"), "{text:?}"); + assert!(text.contains("thread 8 mod+0x20 0 1 no-first"), "{text:?}"); } #[test] @@ -299,7 +314,7 @@ mod tests { handle: raw, start: String::new(), name: String::new(), - first: 0, + first: Some(0), last: 0, now: 0, samples: 0, diff --git a/d3d12/crates/leonida-loader/src/stacks.rs b/d3d12/crates/leonida-loader/src/stacks.rs index e984957845..540a6ffadc 100644 --- a/d3d12/crates/leonida-loader/src/stacks.rs +++ b/d3d12/crates/leonida-loader/src/stacks.rs @@ -23,6 +23,7 @@ use crate::crash::{MAX_FRAMES, locate, unwind_into}; /// Reads `LEONIDA_STACKS` and, if set, starts a thread that prints every /// thread's stack at each listed time (seconds from now). +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub fn dump_stacks_on_schedule() { let Ok(list) = std::env::var("LEONIDA_STACKS") else { return; @@ -292,6 +293,18 @@ mod tests { dump_stacks(); let _ = stop_tx.send(()); let _ = parked.join(); + + // Verify ThreadHandle closes its OS handle on drop even before any + // stderr writes (single-threaded here, so the handle value cannot + // be recycled between Drop and GetHandleInformation). + use windows_sys::Win32::Foundation::GetHandleInformation; + // SAFETY: opens a real handle to the current thread. + let raw = unsafe { OpenThread(THREAD_QUERY_INFORMATION, 0, GetCurrentThreadId()) }; + assert!(!raw.is_null()); + drop(ThreadHandle(raw)); + let mut flags = 0u32; + // SAFETY: single-threaded child; verifies `Drop` closed `raw`. + assert_eq!(unsafe { GetHandleInformation(raw, &mut flags) }, 0); return; } let exe = std::env::current_exe().expect("current test executable");