Skip to main content

oxdock_process/
child.rs

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