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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions d3d12/crates/leonida-loader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
203 changes: 185 additions & 18 deletions d3d12/crates/leonida-loader/src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,41 @@ 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<u64>,
last: u64,
now: u64,
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<u64> {
// 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.
/// `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;
Expand All @@ -76,7 +92,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<u32, Thread> = HashMap::new();
let mut chosen: Vec<u32> = Vec::new();
let mut counts: HashMap<(u32, u32, Vec<u64>), u64> = HashMap::new();
Expand Down Expand Up @@ -105,9 +121,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}");
}
}

Expand All @@ -119,22 +135,29 @@ fn choose(threads: &mut HashMap<u32, Thread>, chosen: &mut Vec<u32>) {
// 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() { 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,
}
});
}
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) {
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));
t.last = t.now;
}
ran.sort_unstable_by(|a, b| b.cmp(a));
Expand Down Expand Up @@ -169,11 +192,8 @@ fn write(
}
let mut names: HashMap<u64, String> = 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) };
}
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} ")?;
Expand Down Expand Up @@ -207,4 +227,151 @@ 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: 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());
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:?}");
assert!(text.contains("thread 8 mod+0x20 0 1 no-first"), "{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: Some(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:?}");
}
}
Loading
Loading