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