Skip to main content

oxdock_process/
child.rs

1use anyhow::Result;
2#[cfg(windows)]
3use std::os::windows::io::OwnedHandle;
4#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
5use std::process::{Child, ExitStatus};
6use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
7use std::sync::{Arc, Mutex};
8
9use crate::contract::BackgroundHandle;
10
11/// Shared inner state for `ChildHandle`, enabling safe cloning.
12/// The OS PID is stored separately so `kill()` can signal
13/// the process without needing `&mut Child`, avoiding undefined behavior.
14#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
15struct ChildInner {
16    child: Option<Child>,
17    io_threads: Vec<std::thread::JoinHandle<()>>,
18    reaped: bool,
19    exit_status: Option<ExitStatus>,
20    killed: AtomicBool,
21}
22
23#[derive(Clone)]
24#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
25pub struct ChildHandle {
26    inner: Arc<Mutex<ChildInner>>,
27    /// OS process ID: the reap sentinel guarding `kill` on both platforms,
28    /// and the process-group kill key on Unix.
29    pid: Arc<AtomicU32>,
30    /// Windows job covering the whole spawn tree; shared across clones.
31    #[cfg(windows)]
32    job: Arc<OwnedHandle>,
33}
34
35impl ChildHandle {
36    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
37    pub(crate) fn new(
38        child: Child,
39        stdin_thread: Option<std::thread::JoinHandle<()>>,
40        io_threads: Vec<std::thread::JoinHandle<()>>,
41    ) -> Result<Self> {
42        // The stdin feeder is deliberately detached, never joined (see
43        // below): it blocks reading the producer pipe, whose writers may
44        // legitimately outlive a short-lived child (a session pump feeding
45        // the next command), so joining would hang `wait()` forever : the
46        // same reason `Drop` below never joins pump threads. The detached
47        // thread ends on pipe EOF or write failure and releases its
48        // handles then; it holds no lock anyone else needs (fresh reader
49        // handle per spawn).
50        let _ = stdin_thread;
51        let pid = child.id();
52        #[cfg(windows)]
53        let job = match assign_job(&child) {
54            Ok(job) => Arc::new(job),
55            Err(err) => {
56                // A live child with no job would escape teardown: end it
57                // before surfacing the failed spawn.
58                let mut child = child;
59                let _ = child.kill();
60                return Err(err);
61            }
62        };
63        Ok(Self {
64            inner: Arc::new(Mutex::new(ChildInner {
65                child: Some(child),
66                io_threads,
67                reaped: false,
68                exit_status: None,
69                killed: AtomicBool::new(false),
70            })),
71            pid: Arc::new(AtomicU32::new(pid)),
72            #[cfg(windows)]
73            job,
74        })
75    }
76}
77
78impl BackgroundHandle for ChildHandle {
79    fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
80        let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
81        if let Some(ref mut child) = guard.child {
82            match child.try_wait()? {
83                Some(status) => {
84                    // Same post-reap sweep as `wait`: an escapee that
85                    // outlived the kill keeps the group (and the pump
86                    // EOF it holds open) alive until this fires.
87                    #[cfg(unix)]
88                    if guard.killed.load(Ordering::SeqCst) {
89                        sweep_process_group(self.pid.load(Ordering::SeqCst));
90                    }
91                    guard.reaped = true;
92                    guard.exit_status = Some(status);
93                    // Zero PID to prevent killing recycled PIDs
94                    self.pid.store(0, Ordering::SeqCst);
95                    // Join output pumps only: their EOF is guaranteed by
96                    // child exit, while the stdin feeder may legitimately
97                    // outlive it (the stdin feeder is detached in `new`).
98                    for thread in guard.io_threads.drain(..) {
99                        let _ = thread.join();
100                    }
101                    guard.child = None;
102                    Ok(Some(status))
103                }
104                None => Ok(None),
105            }
106        } else if guard.reaped {
107            // Process already reaped : return cached exit status
108            Ok(Some(
109                guard
110                    .exit_status
111                    .unwrap_or_else(|| exit_status_from_code(0)),
112            ))
113        } else {
114            // wait() is executing on another thread : process is still running
115            Ok(None)
116        }
117    }
118
119    fn wait(&mut self) -> Result<ExitStatus> {
120        // Take the child out of the mutex. This ensures only one thread
121        // performs the blocking OS wait, preventing ECHILD from dual waitpid.
122        let child_opt = {
123            let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
124            guard.child.take()
125        };
126
127        if let Some(mut child) = child_opt {
128            let status = child.wait()?;
129            // Re-acquire lock to store result and join IO threads.
130            // Output pumps only: the stdin feeder is detached in `new`
131            // since its producer may outlive the child.
132            let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
133            // Sweep after the leader is reaped: a grandchild forked
134            // between the kill's group enumeration and the leader's
135            // death escaped that signal, and the group stays
136            // addressable at the same pgid while any such member
137            // lives. Without the sweep the pump join below stalls on
138            // the escapee's inherited pipe write ends until it exits.
139            #[cfg(unix)]
140            if guard.killed.load(Ordering::SeqCst) {
141                sweep_process_group(self.pid.load(Ordering::SeqCst));
142            }
143            // Zero PID to prevent killing recycled PIDs
144            self.pid.store(0, Ordering::SeqCst);
145            for thread in guard.io_threads.drain(..) {
146                let _ = thread.join();
147            }
148            guard.reaped = true;
149            guard.exit_status = Some(status);
150            Ok(status)
151        } else {
152            // Already reaped : return cached exit status
153            let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
154            Ok(guard
155                .exit_status
156                .unwrap_or_else(|| exit_status_from_code(0)))
157        }
158    }
159
160    fn kill(&mut self) -> Result<()> {
161        let pid = self.pid.load(Ordering::SeqCst);
162        if pid == 0 {
163            return Ok(());
164        }
165        // Flag before signaling: the reaper reads `killed` after the
166        // leader dies, and must see the post-reap sweep as required even
167        // if it wins the inner lock before this thread stores the flag.
168        self.inner
169            .lock()
170            .unwrap_or_else(|e| e.into_inner())
171            .killed
172            .store(true, Ordering::SeqCst);
173        #[cfg(unix)]
174        kill_tree(pid);
175        #[cfg(windows)]
176        terminate_job(self.job.as_ref());
177        Ok(())
178    }
179}
180
181/// Kill the whole tree rooted at `pid` via its process group: a background
182/// child owns its group (see `run_prepared`), so orphaned grandchildren
183/// die with the direct child instead of holding pipe write ends open past
184/// the kill and stalling pump EOF. Best-effort: a fully exited tree
185/// reports ESRCH, which is the already-dead outcome teardown wants.
186#[cfg(unix)]
187fn kill_tree(pid: u32) {
188    // Negative PID signals the whole process group.
189    let group = -(pid as i32);
190    let rc = unsafe { libc::kill(group, libc::SIGKILL) };
191    if rc != 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) {
192        unsafe {
193            libc::kill(pid as i32, libc::SIGKILL);
194        }
195    }
196}
197
198/// Create an unnamed job object and assign `child` to it. Assignment
199/// happens after spawn because std exposes no `CREATE_SUSPENDED` with a
200/// resume handle, so a grandchild the child forks before this call would
201/// join only by inheritance from an already-assigned member; the window
202/// is bounded by the caller's post-spawn setup and is the same class of
203/// bound std users accept. No `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`:
204/// natural completion must leave `RUN "daemon &"` grandchildren alive,
205/// matching Unix, where a post-reap kill is a no-op.
206#[cfg(windows)]
207#[allow(clippy::disallowed_types)]
208fn assign_job(child: &Child) -> Result<OwnedHandle> {
209    use std::os::windows::io::{AsRawHandle, FromRawHandle};
210    use windows_sys::Win32::System::JobObjects::{AssignProcessToJobObject, CreateJobObjectW};
211
212    let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
213    if raw.is_null() {
214        return Err(
215            anyhow::Error::new(std::io::Error::last_os_error()).context("CreateJobObjectW failed")
216        );
217    }
218    let job = unsafe { OwnedHandle::from_raw_handle(raw) };
219    if unsafe { AssignProcessToJobObject(job.as_raw_handle(), child.as_raw_handle()) } == 0 {
220        return Err(anyhow::Error::new(std::io::Error::last_os_error())
221            .context("AssignProcessToJobObject failed"));
222    }
223    Ok(job)
224}
225
226/// Terminate every current member of the job in one kernel call, and
227/// mark it terminating so members created afterwards die at creation:
228/// no enumeration, so the Unix fork-during-kill race class has no
229/// Windows counterpart and no post-reap sweep is needed.
230#[cfg(windows)]
231fn terminate_job(job: &OwnedHandle) {
232    use std::os::windows::io::AsRawHandle;
233    use windows_sys::Win32::System::JobObjects::TerminateJobObject;
234
235    unsafe {
236        TerminateJobObject(job.as_raw_handle(), 1);
237    }
238}
239
240/// Signal a killed child's process group once more after its leader has
241/// been reaped. Signal delivery to the leader is deferred to its next
242/// kernel transition, so a grandchild the leader forked after the first
243/// kill's group enumeration escapes that signal while the leader still
244/// dies. The group persists at the same pgid as long as any such member
245/// lives, so this reaches the escapees that would otherwise stall pump
246/// EOF. Group only, never the raw pid: the leader's pid may already be
247/// recycled. Probes first with signal 0, so an already-empty group is
248/// left alone instead of risking a recycled pgid.
249#[cfg(unix)]
250fn sweep_process_group(pid: u32) {
251    if pid == 0 {
252        return;
253    }
254    let group = -(pid as i32);
255    if unsafe { libc::kill(group, 0) } != 0 {
256        return;
257    }
258    unsafe {
259        libc::kill(group, libc::SIGKILL);
260    }
261}
262
263impl Drop for ChildHandle {
264    fn drop(&mut self) {
265        // Only the last clone (when Arc refcount is 1) runs the actual cleanup.
266        if Arc::strong_count(&self.inner) > 1 {
267            return;
268        }
269        let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
270        if guard.reaped {
271            return;
272        }
273        let running = guard
274            .child
275            .as_mut()
276            .is_some_and(|child| matches!(child.try_wait(), Ok(None)));
277        if running {
278            // Tree kill, not `child.kill()`: a direct-child-only kill
279            // leaves orphaned grandchildren holding inherited pipe write
280            // ends open, and whoever joins the pumps then stalls until
281            // they exit on their own.
282            guard.killed.store(true, Ordering::SeqCst);
283            #[cfg(unix)]
284            kill_tree(self.pid.load(Ordering::SeqCst));
285            #[cfg(windows)]
286            terminate_job(self.job.as_ref());
287            if let Some(child) = guard.child.as_mut() {
288                let _ = child.wait();
289            }
290        }
291        // Sweep when killed even if the leader already exited: an
292        // escapee forked during the kill's enumeration outlives the
293        // leader and keeps the group alive. Matches wait and try_wait.
294        #[cfg(unix)]
295        if guard.killed.load(Ordering::SeqCst) {
296            sweep_process_group(self.pid.load(Ordering::SeqCst));
297        }
298        guard.reaped = true;
299        // `io_threads` are deliberately NOT joined: a grandchild inheriting
300        // the pipe can keep pump threads alive indefinitely. They terminate
301        // on pipe EOF after the kill and only ever write into Arc'd buffers.
302    }
303}
304
305/// Helper to create an exit status from a raw code. Used for synthetic statuses.
306fn exit_status_from_code(code: i32) -> ExitStatus {
307    #[cfg(unix)]
308    {
309        use std::os::unix::process::ExitStatusExt;
310        ExitStatus::from_raw(code << 8)
311    }
312    #[cfg(windows)]
313    {
314        use std::os::windows::process::ExitStatusExt;
315        ExitStatus::from_raw(code as u32)
316    }
317}
318
319#[cfg(all(test, unix))]
320mod tests {
321    use super::sweep_process_group;
322    use std::os::unix::process::CommandExt;
323    use std::time::{Duration, Instant};
324
325    /// The post-escape state: the leader is reaped, but a grandchild it
326    /// forked after the first kill's group enumeration still lives and
327    /// keeps the group addressable. The sweep must end that group, which
328    /// is what unblocks pump EOF in `wait`/`try_wait`.
329    #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
330    #[test]
331    fn sweep_process_group_kills_escapee_that_outlives_the_leader() {
332        #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
333        let mut leader = std::process::Command::new("sh")
334            .arg("-c")
335            // Background the sleeper so the shell can announce it: once
336            // "started" is read the grandchild is guaranteed to exist in
337            // the leader's group (no job control under `sh -c`, so `&`
338            // keeps the same group). `wait` holds the shell alive.
339            .arg("sleep 30 & echo started; wait")
340            .process_group(0)
341            .stdout(std::process::Stdio::piped())
342            .spawn()
343            .expect("spawn leader");
344        let pid = leader.id();
345        {
346            use std::io::BufRead;
347            let mut line = String::new();
348            let stdout = leader.stdout.as_mut().expect("leader stdout");
349            std::io::BufReader::new(stdout)
350                .read_line(&mut line)
351                .expect("read readiness line");
352            assert_eq!(line.trim(), "started");
353        }
354        // Leader-only signal: the sleeper escapes, exactly as it would
355        // when the first group kill's enumeration raced the shell's
356        // fork of it.
357        unsafe {
358            libc::kill(pid as i32, libc::SIGKILL);
359        }
360        let _ = leader.wait();
361        assert_eq!(
362            unsafe { libc::kill(-(pid as i32), 0) },
363            0,
364            "orphaned sleeper should keep the group alive"
365        );
366        sweep_process_group(pid);
367        let deadline = Instant::now() + Duration::from_secs(5);
368        while unsafe { libc::kill(-(pid as i32), 0) } == 0 && Instant::now() < deadline {
369            std::thread::sleep(Duration::from_millis(10));
370        }
371        assert_eq!(
372            unsafe { libc::kill(-(pid as i32), 0) },
373            -1,
374            "sweep must end the escapee's process group"
375        );
376    }
377}
378
379#[cfg(all(test, windows))]
380mod windows_tests {
381    use super::ChildHandle;
382    use crate::CommandBuilder;
383    use crate::contract::BackgroundHandle;
384    use std::os::windows::io::AsRawHandle;
385    use std::time::{Duration, Instant};
386    use windows_sys::Win32::System::JobObjects::{
387        JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JobObjectBasicAccountingInformation,
388        QueryInformationJobObject,
389    };
390
391    fn active_processes(handle: &ChildHandle) -> u32 {
392        let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
393        let ok = unsafe {
394            QueryInformationJobObject(
395                handle.job.as_raw_handle(),
396                JobObjectBasicAccountingInformation,
397                &mut info as *mut _ as *mut _,
398                std::mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
399                std::ptr::null_mut(),
400            )
401        };
402        assert_ne!(
403            ok,
404            0,
405            "QueryInformationJobObject failed: {}",
406            std::io::Error::last_os_error()
407        );
408        info.ActiveProcesses
409    }
410
411    /// Assignment lands the whole tree in the job: `cmd` keeps running
412    /// its own foreground ping while `start /b` backgrounds a second
413    /// ping, so the job holds leader plus grandchild. The kill must end
414    /// both; a direct-child-only kill would leave the orphaned ping
415    /// running and ActiveProcesses nonzero past the deadline.
416    #[cfg_attr(miri, ignore = "spawns a real child process, unsupported under Miri")]
417    #[test]
418    fn kill_terminates_grandchild_that_outlives_the_leader() {
419        let mut handle = CommandBuilder::new("cmd")
420            .args(["/c", "start /b ping -n 30 127.0.0.1 & ping -n 30 127.0.0.1"])
421            .spawn()
422            .expect("spawn");
423        let deadline = Instant::now() + Duration::from_secs(5);
424        while active_processes(&handle) < 2 && Instant::now() < deadline {
425            std::thread::sleep(Duration::from_millis(50));
426        }
427        assert!(
428            active_processes(&handle) >= 2,
429            "leader and grandchild should both be in the job"
430        );
431        handle.kill().expect("kill");
432        handle.wait().expect("wait");
433        let deadline = Instant::now() + Duration::from_secs(5);
434        while active_processes(&handle) != 0 && Instant::now() < deadline {
435            std::thread::sleep(Duration::from_millis(50));
436        }
437        assert_eq!(
438            active_processes(&handle),
439            0,
440            "job kill must terminate the grandchild too"
441        );
442    }
443}