Skip to main content

agentmux_launcher/
host_hang_dump.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! SPEC_HOST_UI_THREAD_HANG_WATCHDOG_2026_08_14 §1–2 — capture evidence of a
5//! wedged host UI thread before anything (a person, usually) kills it.
6//!
7//! On 2026-08-14 the host's UI thread stopped pumping for ~16 minutes with a
8//! window open; it was killed by hand and nothing had captured a stack, so the
9//! deadlock's cause is still unknown. A deadlock raises no exception, so the
10//! crash handler path can't see it — the dump has to be taken EXTERNALLY by
11//! another process (what `procdump -h` does), here the launcher, which already
12//! supervises the host and probes its UI thread (`ui_liveness`).
13//!
14//! Detection + dump only. Automatically killing and respawning a wedged host
15//! (spec §1's last step) is a separate decision and not done here.
16
17use std::path::{Path, PathBuf};
18use std::sync::Mutex;
19use std::time::{Duration, Instant};
20
21/// Dump once the UI thread has missed this many consecutive liveness probes.
22/// The probe runs every 60 s (`supervisor/windows.rs`), so this is a UI thread
23/// silent for at least ~1–2 minutes. Two, not one: a laptop sleep can cost at
24/// most one miss (the first probe after resume is answered).
25pub const HOST_HANG_DUMP_MISSES: u32 = 2;
26
27/// Keep at most this many hang dumps; older ones are deleted.
28pub const MAX_DUMPS_KEPT: usize = 3;
29
30/// A dump older than this is deleted whenever a dump is written, even when fewer than the newest
31/// few are kept: a dump holds thread stacks, which can hold secrets that were in flight, so it is
32/// not kept for long. Age is read from the zero-padded seconds in the file's name.
33pub const DUMP_MAX_AGE_SECS: u64 = 7 * 24 * 60 * 60;
34
35/// How long a dump waits for another dump of this launcher to finish before it gives up. Under
36/// `srv_liveness::WEDGE_DUMP_BUDGET`, so a wedged srv is still killed on time.
37pub const DUMP_LOCK_WAIT: Duration = Duration::from_secs(3);
38
39/// Held while a minidump is written. `MiniDumpWriteDump` is documented as unsafe to call from two
40/// threads of one process at once, and a host hang dump and a srv wedge dump can be asked for at the
41/// same time, so every writer in this module takes this first.
42static DUMP_WRITER: Mutex<()> = Mutex::new(());
43
44/// Run `write` once `lock` is free, waiting at most `wait` for it. A dump that cannot get the lock in
45/// time is not written (`Err`): the caller carries on, and whoever holds it is writing a dump already.
46/// A lock a panicked writer left poisoned is taken all the same: it guards no data.
47#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
48fn with_writer_lock<T>(lock: &Mutex<()>, wait: Duration, write: impl FnOnce() -> T) -> Result<T, String> {
49    let deadline = Instant::now() + wait;
50    loop {
51        match lock.try_lock() {
52            Ok(_guard) => return Ok(write()),
53            Err(std::sync::TryLockError::Poisoned(p)) => {
54                let _guard = p.into_inner();
55                return Ok(write());
56            }
57            Err(std::sync::TryLockError::WouldBlock) => {
58                if Instant::now() >= deadline {
59                    return Err(format!("another minidump was still being written after {}s", wait.as_secs_f32()));
60                }
61                std::thread::sleep(Duration::from_millis(20));
62            }
63        }
64    }
65}
66
67/// One dump per hang episode. Feed it `ui_liveness::consecutive_misses()`
68/// after each probe tick; a reply resets the misses to 0, which re-arms it.
69#[derive(Default)]
70pub struct HangDumpLatch {
71    dumped_this_episode: bool,
72}
73
74impl HangDumpLatch {
75    /// True exactly once per episode, when the misses first reach the threshold.
76    pub fn observe(&mut self, consecutive_misses: u32) -> bool {
77        if consecutive_misses == 0 {
78            self.dumped_this_episode = false;
79            return false;
80        }
81        if consecutive_misses >= HOST_HANG_DUMP_MISSES && !self.dumped_this_episode {
82            self.dumped_this_episode = true;
83            return true;
84        }
85        false
86    }
87}
88
89/// `%LOCALAPPDATA%\CrashDumps\agentmux-host-hang\<instance_key>` — kept
90/// apart from crash dumps (a hang dump and a crash dump mean different things
91/// to triage), and one folder per instance (`instance_key` = the launcher's
92/// data-dir hash) so pruning never deletes another running instance's
93/// evidence (ReAgent P2 on #3913).
94pub fn dump_dir(instance_key: &str) -> Option<PathBuf> {
95    let base = std::env::var_os("LOCALAPPDATA")?;
96    dump_dir_under(Path::new(&base), instance_key)
97}
98
99/// `dump_dir` with an explicit base. `None` for a key that isn't a single
100/// plain path component — it is joined onto a path.
101pub fn dump_dir_under(base: &Path, instance_key: &str) -> Option<PathBuf> {
102    plain_component(instance_key).then(|| base.join("CrashDumps").join("agentmux-host-hang").join(instance_key))
103}
104
105/// Sortable by name: zero-padded timestamp first.
106pub fn dump_file_name(unix_secs: u64, pid: u32) -> String {
107    dump_file_name_with(HOST_FILE_PREFIX, unix_secs, pid)
108}
109
110/// File-name prefix of the host's hang dumps.
111const HOST_FILE_PREFIX: &str = "agentmux-host-hang-";
112
113/// `<prefix><zero-padded seconds>-pid<pid>.dmp`; the prefix ends with `-`.
114fn dump_file_name_with(prefix: &str, unix_secs: u64, pid: u32) -> String {
115    format!("{prefix}{unix_secs:012}-pid{pid}.dmp")
116}
117
118/// Srv wedge dumps kept per instance.
119pub const SRV_WEDGE_DUMPS_KEPT: usize = 3;
120
121/// `%LOCALAPPDATA%\CrashDumps\agentmux-srv-wedge\<instance_key>`: where a wedged srv's dump goes. It is
122/// the user's own profile folder, which Windows scopes to that user (and the system and administrators),
123/// so another account on the machine cannot read it; a machine-wide folder such as `C:\CrashDumps` is
124/// open to every local user, and a dump holds thread stacks that can hold secrets. One folder per
125/// instance, as for the host's hang dumps. `None` when there is no `LOCALAPPDATA` or the key is not a
126/// single plain path component.
127pub fn srv_wedge_dir(instance_key: &str) -> Option<PathBuf> {
128    let base = std::env::var_os("LOCALAPPDATA")?;
129    srv_wedge_dir_under(Path::new(&base), instance_key)
130}
131
132/// [`srv_wedge_dir`] with an explicit base.
133pub fn srv_wedge_dir_under(base: &Path, instance_key: &str) -> Option<PathBuf> {
134    plain_component(instance_key).then(|| base.join("CrashDumps").join("agentmux-srv-wedge").join(instance_key))
135}
136
137/// A key that is one plain path component: it is joined onto a path and put in a file name.
138fn plain_component(key: &str) -> bool {
139    !key.is_empty() && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
140}
141
142/// File-name prefix of one instance's srv wedge dumps (`agentmuxsrv-wedge-<instance_key>-`), so
143/// pruning one instance's dumps never deletes another running instance's. `None` for a key that is
144/// not a single plain path component.
145pub fn srv_wedge_prefix(instance_key: &str) -> Option<String> {
146    plain_component(instance_key).then(|| format!("agentmuxsrv-wedge-{instance_key}-"))
147}
148
149/// Delete the dumps with `prefix` in `dir` that are not among the newest `keep` or are older than
150/// [`DUMP_MAX_AGE_SECS`]. Best-effort.
151#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
152fn prune_old_dumps_with(dir: &Path, prefix: &str, keep: usize) {
153    prune_old_dumps_at(dir, prefix, keep, agentmux_common::time::now_secs_u64());
154}
155
156/// The seconds a dump's name carries: `<prefix><zero-padded seconds>-pid<pid>.dmp`.
157fn dump_secs(name: &str, prefix: &str) -> Option<u64> {
158    name.strip_prefix(prefix)?.split('-').next()?.parse().ok()
159}
160
161/// [`prune_old_dumps_with`] at a given time. A file with this prefix whose name carries no readable
162/// time is counted for the newest `keep` and never deleted for its age.
163fn prune_old_dumps_at(dir: &Path, prefix: &str, keep: usize, now_secs: u64) {
164    let Ok(entries) = std::fs::read_dir(dir) else {
165        return;
166    };
167    let mut dumps: Vec<PathBuf> = entries
168        .filter_map(|e| e.ok().map(|e| e.path()))
169        .filter(|p| {
170            p.file_name()
171                .and_then(|n| n.to_str())
172                .is_some_and(|n| n.starts_with(prefix) && n.ends_with(".dmp"))
173        })
174        .collect();
175    dumps.sort();
176    let excess = dumps.len().saturating_sub(keep);
177    for (i, old) in dumps.into_iter().enumerate() {
178        let too_many = i < excess;
179        let too_old = old
180            .file_name()
181            .and_then(|n| n.to_str())
182            .and_then(|n| dump_secs(n, prefix))
183            .is_some_and(|t| now_secs.saturating_sub(t) > DUMP_MAX_AGE_SECS);
184        if too_many || too_old {
185            let _ = std::fs::remove_file(old);
186        }
187    }
188}
189
190/// A copy of a process handle with the same rights, for a dump written off the supervisor's
191/// thread while the original stays with its `Child`. Close it with [`close_copy`].
192#[cfg(target_os = "windows")]
193pub fn copy_handle(raw: std::os::windows::io::RawHandle) -> Option<usize> {
194    use windows_sys::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE};
195    use windows_sys::Win32::System::Threading::GetCurrentProcess;
196    let mut out: HANDLE = std::ptr::null_mut();
197    // SAFETY: duplicates a handle this process owns into this process.
198    let ok = unsafe { DuplicateHandle(GetCurrentProcess(), raw as HANDLE, GetCurrentProcess(), &mut out, 0, 0, DUPLICATE_SAME_ACCESS) };
199    (ok != 0 && !out.is_null()).then_some(out as usize)
200}
201
202#[cfg(target_os = "windows")]
203pub fn close_copy(handle: usize) {
204    // SAFETY: `handle` came from [`copy_handle`] and is closed once.
205    unsafe { windows_sys::Win32::Foundation::CloseHandle(handle as windows_sys::Win32::Foundation::HANDLE) };
206}
207
208/// What a snapshot of the host keeps for the dump: its memory (cloned), handles with their names,
209/// threads and their registers.
210#[cfg(target_os = "windows")]
211const SNAPSHOT_CAPTURE: u32 = 0x1 | 0x4 | 0x8 | 0x10 | 0x20 | 0x80 | 0x100;
212
213#[cfg(all(target_os = "windows", target_arch = "aarch64"))]
214const THREAD_CONTEXT_ALL: u32 = windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_ALL_ARM64;
215#[cfg(all(target_os = "windows", not(target_arch = "aarch64")))]
216const THREAD_CONTEXT_ALL: u32 = windows_sys::Win32::System::Diagnostics::Debug::CONTEXT_ALL_AMD64;
217
218/// Tells the dump writer its process handle is a snapshot (callback type `IsProcessSnapshotCallback`
219/// answers `S_FALSE`).
220#[cfg(target_os = "windows")]
221unsafe extern "system" fn snapshot_callback(
222    _param: *mut core::ffi::c_void,
223    input: *const windows_sys::Win32::System::Diagnostics::Debug::MINIDUMP_CALLBACK_INPUT,
224    output: *mut windows_sys::Win32::System::Diagnostics::Debug::MINIDUMP_CALLBACK_OUTPUT,
225) -> windows_sys::Win32::Foundation::BOOL {
226    use windows_sys::Win32::System::Diagnostics::Debug::IsProcessSnapshotCallback;
227    // SAFETY: the dump writer passes valid pointers to packed structs; read and write unaligned.
228    unsafe {
229        let kind = std::ptr::addr_of!((*input).CallbackType).read_unaligned();
230        if kind == IsProcessSnapshotCallback as u32 {
231            std::ptr::addr_of_mut!((*output).Anonymous.Status).write_unaligned(windows_sys::Win32::Foundation::S_FALSE);
232        }
233    }
234    1
235}
236
237/// Write a minidump of process `pid` into `dir` from OUTSIDE the process —
238/// works while every thread of the target is blocked. Thread stacks + thread
239/// info + handles (for lock/wait analysis) + module lists; not full memory,
240/// which keeps it to a few MB and limits what user data it can contain.
241///
242/// `handle` is a handle to the process with the rights a dump needs (the one `CreateProcess`
243/// returned, or a copy of it): the host refuses other processes of the user those rights once it
244/// has hardened itself, so the launcher must not open it by pid. The caller keeps ownership of
245/// the handle. With `None` the process is opened by pid.
246#[cfg(target_os = "windows")]
247pub fn write_hang_dump(pid: u32, handle: Option<usize>, dir: &Path) -> Result<PathBuf, String> {
248    write_process_dump(pid, handle, dir, HOST_FILE_PREFIX, MAX_DUMPS_KEPT)
249}
250
251/// A wedged srv's dump, the same kind as [`write_hang_dump`], named with `prefix`
252/// (from [`srv_wedge_prefix`]) and keeping the newest [`SRV_WEDGE_DUMPS_KEPT`].
253#[cfg(target_os = "windows")]
254pub fn write_srv_wedge_dump(pid: u32, handle: Option<usize>, dir: &Path, prefix: &str) -> Result<PathBuf, String> {
255    write_process_dump(pid, handle, dir, prefix, SRV_WEDGE_DUMPS_KEPT)
256}
257
258/// One dump at a time in this process: the second waits for the first, for at most [`DUMP_LOCK_WAIT`].
259#[cfg(target_os = "windows")]
260fn write_process_dump(pid: u32, handle: Option<usize>, dir: &Path, prefix: &str, keep: usize) -> Result<PathBuf, String> {
261    with_writer_lock(&DUMP_WRITER, DUMP_LOCK_WAIT, || write_process_dump_locked(pid, handle, dir, prefix, keep))?
262}
263
264#[cfg(target_os = "windows")]
265fn write_process_dump_locked(pid: u32, handle: Option<usize>, dir: &Path, prefix: &str, keep: usize) -> Result<PathBuf, String> {
266    use std::os::windows::io::AsRawHandle;
267    use windows_sys::Win32::Foundation::CloseHandle;
268    use windows_sys::Win32::System::Diagnostics::Debug::{
269        MiniDumpWithHandleData, MiniDumpWithThreadInfo, MiniDumpWithUnloadedModules,
270        MiniDumpWriteDump, MINIDUMP_CALLBACK_INFORMATION,
271    };
272    use windows_sys::Win32::System::Diagnostics::ProcessSnapshotting::{PssCaptureSnapshot, PssFreeSnapshot};
273    use windows_sys::Win32::System::Threading::{
274        GetCurrentProcess, OpenProcess, PROCESS_DUP_HANDLE, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ,
275    };
276
277    // Owner-only where the platform has modes (nothing to do on Windows, whose per-user folder is scoped
278    // by the profile's access list); the folder itself is made next.
279    agentmux_common::data_paths::ensure_owner_only_dir(dir).map_err(|e| format!("make {} private: {e}", dir.display()))?;
280    std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
281    let secs = agentmux_common::time::now_secs_u64();
282    let path = dir.join(dump_file_name_with(prefix, secs, pid));
283    let file = std::fs::File::create(&path).map_err(|e| format!("create {}: {e}", path.display()))?;
284
285    // SAFETY: OpenProcess/MiniDumpWriteDump/CloseHandle with a handle we own
286    // and close on every path; the file handle stays valid for the call
287    // because `file` outlives it.
288    let ok = unsafe {
289        // DUP_HANDLE: MiniDumpWithHandleData silently omits the handle
290        // stream without it — and handles are how a deadlock dump shows
291        // which mutex/event each thread is waiting on.
292        let process = match handle {
293            Some(h) => h as windows_sys::Win32::Foundation::HANDLE,
294            None => OpenProcess(
295                PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_DUP_HANDLE,
296                0,
297                pid,
298            ),
299        };
300        if process.is_null() {
301            drop(file);
302            let _ = std::fs::remove_file(&path);
303            return Err(format!("OpenProcess({pid}) failed: {}", std::io::Error::last_os_error()));
304        }
305        let dump_type = MiniDumpWithThreadInfo | MiniDumpWithHandleData | MiniDumpWithUnloadedModules;
306        // The dump writer reads the process through its own handle to it, which a hardened process
307        // refuses; a snapshot taken through the handle we hold is a copy of the process in our own
308        // hands, and that it can dump.
309        let mut snapshot: windows_sys::Win32::System::Diagnostics::ProcessSnapshotting::HPSS = std::ptr::null_mut();
310        let from_snapshot = handle.is_some()
311            && PssCaptureSnapshot(process, SNAPSHOT_CAPTURE, THREAD_CONTEXT_ALL, &mut snapshot) == 0
312            && !snapshot.is_null();
313        let callbacks = MINIDUMP_CALLBACK_INFORMATION {
314            CallbackRoutine: Some(snapshot_callback),
315            CallbackParam: std::ptr::null_mut(),
316        };
317        let ok = MiniDumpWriteDump(
318            if from_snapshot { snapshot as _ } else { process },
319            pid,
320            file.as_raw_handle() as _,
321            dump_type,
322            std::ptr::null(),
323            std::ptr::null(),
324            if from_snapshot { &callbacks } else { std::ptr::null() },
325        );
326        let err = std::io::Error::last_os_error();
327        if from_snapshot {
328            PssFreeSnapshot(GetCurrentProcess(), snapshot);
329        }
330        if handle.is_none() {
331            CloseHandle(process);
332        }
333        if ok == 0 {
334            Err(err)
335        } else {
336            Ok(())
337        }
338    };
339    drop(file);
340    match ok {
341        Ok(()) => {
342            prune_old_dumps_with(dir, prefix, keep);
343            Ok(path)
344        }
345        Err(e) => {
346            let _ = std::fs::remove_file(&path);
347            Err(format!("MiniDumpWriteDump({pid}) failed: {e}"))
348        }
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn latch_fires_once_per_episode_at_the_threshold() {
358        let mut l = HangDumpLatch::default();
359        assert!(!l.observe(1), "one miss (e.g. a sleep/resume) is not a hang");
360        assert!(l.observe(2), "second consecutive miss → dump");
361        assert!(!l.observe(3), "still the same episode — no second dump");
362        assert!(!l.observe(9));
363    }
364
365    #[test]
366    fn latch_rearms_after_the_ui_thread_answers() {
367        let mut l = HangDumpLatch::default();
368        assert!(l.observe(2));
369        assert!(!l.observe(0), "a reply resets misses to 0");
370        assert!(!l.observe(1));
371        assert!(l.observe(2), "a new hang gets its own dump");
372    }
373
374    #[test]
375    fn each_instance_gets_its_own_dump_folder() {
376        let base = Path::new("base");
377        let a = dump_dir_under(base, "0123456789abcdef").unwrap();
378        let b = dump_dir_under(base, "fedcba9876543210").unwrap();
379        assert_ne!(a, b, "pruning in one must not touch the other");
380        assert_eq!(
381            a,
382            base.join("CrashDumps").join("agentmux-host-hang").join("0123456789abcdef")
383        );
384    }
385
386    #[test]
387    fn a_key_that_is_not_a_plain_component_is_rejected() {
388        let base = Path::new("base");
389        assert!(dump_dir_under(base, "").is_none());
390        assert!(dump_dir_under(base, "..").is_none());
391        assert!(dump_dir_under(base, "a/b").is_none());
392        assert!(dump_dir_under(base, "a\\b").is_none());
393    }
394
395    #[test]
396    fn file_names_sort_chronologically() {
397        let a = dump_file_name(999, 42);
398        let b = dump_file_name(1_000, 7);
399        assert!(a < b, "{a} should sort before {b}");
400        assert!(a.starts_with("agentmux-host-hang-") && a.ends_with(".dmp"));
401    }
402
403    #[test]
404    fn prune_keeps_only_the_newest_dumps_and_ignores_other_files() {
405        let dir = std::env::temp_dir().join(format!("amux-hang-prune-{}", std::process::id()));
406        let _ = std::fs::remove_dir_all(&dir);
407        std::fs::create_dir_all(&dir).unwrap();
408        for t in 1..=7u64 {
409            std::fs::write(dir.join(dump_file_name(t, 1)), b"x").unwrap();
410        }
411        std::fs::write(dir.join("notes.txt"), b"keep me").unwrap();
412
413        prune_old_dumps_at(&dir, HOST_FILE_PREFIX, 3, 10);
414
415        let mut left: Vec<String> = std::fs::read_dir(&dir)
416            .unwrap()
417            .map(|e| e.unwrap().file_name().into_string().unwrap())
418            .collect();
419        left.sort();
420        assert_eq!(
421            left,
422            vec![dump_file_name(5, 1), dump_file_name(6, 1), dump_file_name(7, 1), "notes.txt".into()]
423        );
424        let _ = std::fs::remove_dir_all(&dir);
425    }
426
427    #[test]
428    fn srv_wedge_pruning_keeps_three_per_instance_and_leaves_other_files_alone() {
429        assert!(srv_wedge_prefix("..").is_none() && srv_wedge_prefix("").is_none());
430        let (a, b) = (srv_wedge_prefix("aaaa").unwrap(), srv_wedge_prefix("bbbb").unwrap());
431        let dir = std::env::temp_dir().join(format!("amux-srv-wedge-prune-{}", std::process::id()));
432        let _ = std::fs::remove_dir_all(&dir);
433        std::fs::create_dir_all(&dir).unwrap();
434        for t in 1..=5u64 {
435            std::fs::write(dir.join(dump_file_name_with(&a, t, 1)), b"x").unwrap();
436        }
437        std::fs::write(dir.join(dump_file_name_with(&b, 1, 2)), b"x").unwrap();
438        std::fs::write(dir.join("agentmuxsrv-1-2.dmp"), b"crash monitor dump").unwrap();
439        std::fs::write(dir.join("monitor.sock"), b"s").unwrap();
440
441        prune_old_dumps_at(&dir, &a, SRV_WEDGE_DUMPS_KEPT, 10);
442
443        let mut left: Vec<String> =
444            std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
445        left.sort();
446        let mut want = vec![
447            dump_file_name_with(&a, 3, 1),
448            dump_file_name_with(&a, 4, 1),
449            dump_file_name_with(&a, 5, 1),
450            dump_file_name_with(&b, 1, 2),
451            "agentmuxsrv-1-2.dmp".into(),
452            "monitor.sock".into(),
453        ];
454        want.sort();
455        assert_eq!(left, want);
456        let _ = std::fs::remove_dir_all(&dir);
457    }
458
459    #[test]
460    fn at_most_three_hang_dumps_are_kept() {
461        assert_eq!(MAX_DUMPS_KEPT, 3);
462        assert_eq!(SRV_WEDGE_DUMPS_KEPT, 3);
463    }
464
465    #[test]
466    fn a_dump_older_than_a_week_is_deleted_even_when_fewer_than_the_newest_few_are_there() {
467        let dir = std::env::temp_dir().join(format!("amux-dump-age-{}", std::process::id()));
468        let _ = std::fs::remove_dir_all(&dir);
469        std::fs::create_dir_all(&dir).unwrap();
470        let now = 10 * DUMP_MAX_AGE_SECS;
471        let old = dump_file_name(now - DUMP_MAX_AGE_SECS - 1, 1);
472        let edge = dump_file_name(now - DUMP_MAX_AGE_SECS, 2);
473        let fresh = dump_file_name(now - 60, 3);
474        for n in [&old, &edge, &fresh] {
475            std::fs::write(dir.join(n), b"x").unwrap();
476        }
477        std::fs::write(dir.join("notes.txt"), b"keep me").unwrap();
478        // A file with the prefix whose name has no time in it is not aged out.
479        std::fs::write(dir.join("agentmux-host-hang-unreadable.dmp"), b"x").unwrap();
480
481        prune_old_dumps_at(&dir, HOST_FILE_PREFIX, 3, now);
482
483        let mut left: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
484        left.sort();
485        let mut want = vec![edge, fresh, "agentmux-host-hang-unreadable.dmp".into(), "notes.txt".into()];
486        want.sort();
487        assert_eq!(left, want, "only the dump past its week is gone");
488        let _ = std::fs::remove_dir_all(&dir);
489    }
490
491    #[test]
492    fn the_srv_wedge_dump_goes_to_the_users_own_folder_one_per_instance() {
493        let base = Path::new("base");
494        let a = srv_wedge_dir_under(base, "0123456789abcdef").unwrap();
495        let b = srv_wedge_dir_under(base, "fedcba9876543210").unwrap();
496        assert_ne!(a, b, "pruning in one must not touch the other");
497        assert_eq!(a, base.join("CrashDumps").join("agentmux-srv-wedge").join("0123456789abcdef"));
498        assert!(srv_wedge_dir_under(base, "").is_none());
499        assert!(srv_wedge_dir_under(base, "..").is_none());
500        assert!(srv_wedge_dir_under(base, "a/b").is_none());
501        assert!(srv_wedge_dir_under(base, "a\\b").is_none());
502        // Never the machine-wide folder the crash monitor uses.
503        assert!(!a.starts_with(r"C:\CrashDumps"));
504    }
505
506    #[test]
507    fn the_srv_wedge_dump_folder_follows_the_user_profile_variable() {
508        // Under the user's own LOCALAPPDATA when it is set (every Windows user session sets it).
509        if let Some(base) = std::env::var_os("LOCALAPPDATA") {
510            let dir = srv_wedge_dir("abc123").unwrap();
511            assert!(dir.starts_with(Path::new(&base)), "{}", dir.display());
512        }
513    }
514
515    #[test]
516    fn two_dump_writers_started_together_never_overlap() {
517        use std::sync::atomic::{AtomicUsize, Ordering};
518        let lock = Mutex::new(());
519        let inside = AtomicUsize::new(0);
520        let most = AtomicUsize::new(0);
521        let wrote = AtomicUsize::new(0);
522        std::thread::scope(|s| {
523            for _ in 0..4 {
524                s.spawn(|| {
525                    with_writer_lock(&lock, Duration::from_secs(10), || {
526                        let now = inside.fetch_add(1, Ordering::SeqCst) + 1;
527                        most.fetch_max(now, Ordering::SeqCst);
528                        std::thread::sleep(Duration::from_millis(60));
529                        inside.fetch_sub(1, Ordering::SeqCst);
530                        wrote.fetch_add(1, Ordering::SeqCst);
531                    })
532                    .unwrap();
533                });
534            }
535        });
536        assert_eq!(wrote.load(Ordering::SeqCst), 4, "every writer got its turn");
537        assert_eq!(most.load(Ordering::SeqCst), 1, "never two inside at once");
538    }
539
540    #[test]
541    fn a_writer_that_cannot_get_the_lock_in_time_gives_up_and_the_holder_is_not_disturbed() {
542        let lock = Mutex::new(());
543        let held = lock.lock().unwrap();
544        let started = Instant::now();
545        let r = with_writer_lock(&lock, Duration::from_millis(100), || panic!("must not write while another writes"));
546        assert!(r.unwrap_err().contains("another minidump"), "says why");
547        assert!(started.elapsed() < Duration::from_secs(5), "it waited about its limit, not forever");
548        drop(held);
549        assert_eq!(with_writer_lock(&lock, Duration::from_millis(100), || 7).unwrap(), 7, "free again once released");
550    }
551
552    #[test]
553    fn a_lock_a_panicked_writer_left_poisoned_still_lets_the_next_dump_through() {
554        let lock = Mutex::new(());
555        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
556            let _g = lock.lock().unwrap();
557            panic!("a writer died holding the lock");
558        }));
559        assert!(lock.is_poisoned());
560        assert_eq!(with_writer_lock(&lock, Duration::from_millis(100), || 1).unwrap(), 1);
561    }
562
563    /// The test binary itself as a child that has finished starting and then blocks on its stdin: the dump
564    /// of a process still loading (a `cmd` that has just been created) is cut short, and a killed `cmd`
565    /// leaves its `ping` running with the test's pipes. Returns the child, the line it printed that starts
566    /// with `ready`, and its output, which the caller keeps open until the child has ended.
567    #[cfg(target_os = "windows")]
568    fn spawn_helper(test: &str, ready: &str) -> (std::process::Child, String, impl Iterator<Item = std::io::Result<String>>) {
569        use std::io::{BufRead, BufReader};
570        use std::process::{Command, Stdio};
571        let mut child = Command::new(std::env::current_exe().unwrap())
572            .args(["--exact", test, "--ignored", "--nocapture"])
573            .env("AGENTMUX_HD_CHILD", "1")
574            .stdin(Stdio::piped())
575            .stdout(Stdio::piped())
576            .spawn()
577            .unwrap();
578        let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
579        let line = lines.by_ref().map(|l| l.unwrap()).find(|l| l.starts_with(ready));
580        (child, line.unwrap_or_default(), lines)
581    }
582
583    /// Real MiniDumpWriteDump against a live child process that is up and waiting.
584    #[cfg(target_os = "windows")]
585    #[test]
586    fn writes_a_readable_dump_of_another_process() {
587        let (mut child, ready, _output) = spawn_helper("host_hang_dump::tests::waiting_hang_child", "WAITING");
588        assert_eq!(ready, "WAITING", "the child came up");
589        let dir = std::env::temp_dir().join(format!("amux-hang-dump-{}", std::process::id()));
590        let _ = std::fs::remove_dir_all(&dir);
591
592        let result = write_hang_dump(child.id(), None, &dir);
593        drop(child.stdin.take());
594        let _ = child.wait();
595
596        let path = result.expect("dump written");
597        let bytes = std::fs::read(&path).unwrap();
598        assert_eq!(&bytes[..4], b"MDMP", "minidump signature");
599        // Stream directory: header u32 NumberOfStreams @8, u32 StreamDirectoryRva @12;
600        // each entry is (u32 StreamType, u32 DataSize, u32 Rva).
601        let u32_at = |o: usize| u32::from_le_bytes(bytes[o..o + 4].try_into().unwrap());
602        let (n, stream_dir) = (u32_at(8) as usize, u32_at(12) as usize);
603        let types: Vec<u32> = (0..n).map(|i| u32_at(stream_dir + 12 * i)).collect();
604        const THREAD_LIST: u32 = 3;
605        const HANDLE_DATA: u32 = 12;
606        assert!(types.contains(&THREAD_LIST), "thread stacks: {types:?}");
607        assert!(types.contains(&HANDLE_DATA), "handle data: {types:?}");
608        let _ = std::fs::remove_dir_all(&dir);
609    }
610
611    /// Runs only as the child of the previous test: says it is up and waits for its stdin to close.
612    #[cfg(target_os = "windows")]
613    #[test]
614    #[ignore = "runs as the child of writes_a_readable_dump_of_another_process"]
615    fn waiting_hang_child() {
616        use std::io::{Read, Write};
617        if std::env::var_os("AGENTMUX_HD_CHILD").is_none() {
618            return;
619        }
620        println!("WAITING");
621        std::io::stdout().flush().unwrap();
622        let _ = std::io::stdin().read_to_end(&mut Vec::new());
623    }
624
625    /// Runs only as the child of the next test: hardens itself and waits for its stdin to close.
626    #[cfg(target_os = "windows")]
627    #[test]
628    #[ignore = "runs as the child of dumps_a_hardened_process_through_the_handle_its_creator_holds"]
629    fn hardened_hang_child() {
630        use std::io::{Read, Write};
631        if std::env::var_os("AGENTMUX_HD_CHILD").is_none() {
632            return;
633        }
634        println!("HARDENED {}", agentmux_common::process_hardening::apply());
635        std::io::stdout().flush().unwrap();
636        let _ = std::io::stdin().read_to_end(&mut Vec::new());
637    }
638
639    /// The host hardens itself, so the launcher cannot open it by pid for a dump; it uses a copy of
640    /// the handle `CreateProcess` gave it.
641    #[cfg(target_os = "windows")]
642    #[test]
643    fn dumps_a_hardened_process_through_the_handle_its_creator_holds() {
644        use std::os::windows::io::AsRawHandle;
645        if agentmux_common::debug_privilege::refusal_cannot_be_observed("dumps_a_hardened_process_through_the_handle_its_creator_holds") {
646            return;
647        }
648        let (mut child, hardened, _output) = spawn_helper("host_hang_dump::tests::hardened_hang_child", "HARDENED ");
649        assert_eq!(hardened, "HARDENED true");
650        let dir = std::env::temp_dir().join(format!("amux-hang-dump-hardened-{}", std::process::id()));
651        let _ = std::fs::remove_dir_all(&dir);
652
653        let by_pid = write_hang_dump(child.id(), None, &dir);
654        assert!(by_pid.is_err(), "opening a hardened process by pid is refused: {by_pid:?}");
655
656        let copy = copy_handle(child.as_raw_handle()).expect("a copy of the creation handle");
657        let by_handle = write_hang_dump(child.id(), Some(copy), &dir);
658        close_copy(copy);
659        drop(child.stdin.take());
660        let _ = child.wait();
661
662        let path = by_handle.unwrap_or_else(|e| panic!("dump written through the held handle: {e}"));
663        let bytes = std::fs::read(&path).unwrap();
664        assert_eq!(&bytes[..4], b"MDMP", "minidump signature");
665        // Same streams as the dump taken by pid: thread stacks and the handle table survive the snapshot.
666        let u32_at = |o: usize| u32::from_le_bytes(bytes[o..o + 4].try_into().unwrap());
667        let (n, stream_dir) = (u32_at(8) as usize, u32_at(12) as usize);
668        let types: Vec<u32> = (0..n).map(|i| u32_at(stream_dir + 12 * i)).collect();
669        assert!(types.contains(&3), "thread stacks: {types:?}");
670        assert!(types.contains(&12), "handle data: {types:?}");
671        let _ = std::fs::remove_dir_all(&dir);
672    }
673}