Skip to main content

zebra_test/command/process_group/
unix.rs

1//! Owned Unix process groups for test commands.
2//!
3//! The leader must not be reaped outside this module until the group is retired. In particular,
4//! callers must not install a reaping SIGCHLD handler, SIG_IGN, or SA_NOCLDWAIT. Keeping an exited
5//! leader waitable reserves its PID until cleanup, so its group ID cannot refer to another group.
6//! Descendants that deliberately leave this group are outside its ownership boundary. Kernel signal
7//! permissions still apply, including when descendants change credentials.
8
9use std::{
10    io,
11    os::unix::process::CommandExt,
12    process::{Child, Command, ExitStatus},
13};
14
15use nix::{
16    errno::Errno,
17    sys::signal::{kill, Signal},
18    unistd::Pid,
19};
20
21#[cfg(any(target_os = "redox", target_os = "cygwin", target_os = "l4re"))]
22compile_error!("owned test process groups require a native waitid API with WNOWAIT support");
23
24/// A group whose leader's unreaped PID reserves the group ID until cleanup.
25#[derive(Debug)]
26pub(super) struct ProcessGroup {
27    /// `None` after cleanup, even if the caller has not yet reaped the leader.
28    leader: Option<Pid>,
29}
30
31/// Configure group ownership in the child before it executes the command.
32pub(super) fn spawn(command: &mut Command) -> io::Result<(Child, ProcessGroup)> {
33    let child = command.process_group(0).spawn()?;
34    // Unix allocated a positive pid_t; Child::id converts that native value to u32.
35    let leader = Pid::from_raw(child.id() as nix::libc::pid_t);
36    Ok((
37        child,
38        ProcessGroup {
39            leader: Some(leader),
40        },
41    ))
42}
43
44impl ProcessGroup {
45    /// Kill the owned group without reaping the leader. Repeated cleanup cannot reuse its ID.
46    pub(super) fn kill(&mut self, _child: &mut Child) -> io::Result<()> {
47        let Some(leader) = self.leader else {
48            return Ok(());
49        };
50        // Detect a lost ownership reservation before signalling any saved numeric ID.
51        self.observe_exit(leader)?;
52        self.terminate(leader)
53    }
54
55    /// Observe exit without reaping, clean up the group, then preserve the leader's actual status.
56    pub(super) fn try_wait(&mut self, child: &mut Child) -> io::Result<Option<ExitStatus>> {
57        let Some(leader) = self.leader else {
58            // Cleanup has retired the numeric ID, so std may safely reap or return cached status.
59            return child.try_wait();
60        };
61        if !self.observe_exit(leader)? {
62            return Ok(None);
63        }
64        self.terminate(leader)?;
65        child.wait().map(Some)
66    }
67
68    /// Preserve genuine observation failures; ECHILD also revokes permission to signal this ID.
69    fn observe_exit(&mut self, leader: Pid) -> io::Result<bool> {
70        match leader_exited(leader) {
71            Ok(exited) => Ok(exited),
72            Err(error) => {
73                if error == Errno::ECHILD {
74                    self.leader = None;
75                }
76                Err(error.into())
77            }
78        }
79    }
80
81    /// Signal only while the leader is still unreaped, then permanently retire the saved ID.
82    fn terminate(&mut self, leader: Pid) -> io::Result<()> {
83        // A spawned leader's PID is positive, so negating it selects exactly its process group.
84        match kill(Pid::from_raw(-leader.as_raw()), Signal::SIGKILL) {
85            Ok(()) | Err(Errno::ESRCH) => {
86                // ESRCH means the owned group has no signalable members, not a cleanup failure.
87                self.leader = None;
88                Ok(())
89            }
90            Err(error) => Err(error.into()),
91        }
92    }
93}
94
95/// Observe terminal presence without decoding real-time signals through nix's closed Signal enum.
96#[allow(unsafe_code)]
97fn leader_exited(leader: Pid) -> nix::Result<bool> {
98    use nix::libc;
99
100    let id = leader.as_raw().try_into().map_err(|_| Errno::EINVAL)?;
101    // SAFETY: siginfo_t is a C data structure whose fields admit an all-zero representation.
102    // Initialize it because older waitid implementations can leave it unchanged with WNOHANG.
103    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
104    // SAFETY: info is valid writable storage; P_PID selects only our unreaped child. WNOWAIT
105    // preserves its PID reservation, and WEXITED requests only terminal status information.
106    let result = unsafe {
107        libc::waitid(
108            libc::P_PID,
109            id,
110            &mut info,
111            libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
112        )
113    };
114    Errno::result(result)?;
115    // Successful exit observation sets si_signo to SIGCHLD; WNOHANG without exit leaves zero.
116    Ok(info.si_signo != 0)
117}