use std::ffi::CString;
use std::io;
#[cfg(target_os = "macos")]
use std::os::fd::OwnedFd;
#[cfg(target_os = "linux")]
use std::os::fd::RawFd;
use std::os::unix::process::CommandExt;
use super::fd_map;
#[cfg(target_os = "linux")]
use crate::containment::cgroup::ReportSlot;
#[derive(Default)]
pub(crate) struct InChild {
enter: Option<CString>,
session: bool,
#[cfg(target_os = "linux")]
placement: Option<(RawFd, ReportSlot)>,
#[cfg(target_os = "macos")]
preserved: Vec<OwnedFd>,
fd_map: Option<fd_map::Plan>,
}
impl InChild {
pub(crate) fn enter(&mut self, dir: CString) {
debug_assert!(self.enter.is_none(), "a spawn enters one directory");
self.enter = Some(dir);
}
pub(crate) fn session(&mut self) {
debug_assert!(!self.session, "a spawn asks for its session once");
self.session = true;
}
#[cfg(target_os = "linux")]
pub(crate) unsafe fn place(&mut self, procs_fd: RawFd, slot: ReportSlot) {
debug_assert!(self.placement.is_none(), "a spawn places its child once");
self.placement = Some((procs_fd, slot));
}
#[cfg(target_os = "macos")]
pub(crate) fn preserve(&mut self, fd: OwnedFd) {
self.preserved.push(fd);
}
pub(super) fn map_fds(&mut self, plan: fd_map::Plan) {
debug_assert!(self.fd_map.is_none(), "a spawn has one fd map");
self.fd_map = Some(plan);
}
pub(crate) fn register(self, cmd: &mut std::process::Command) {
if self.is_empty() {
return;
}
let mut steps = self;
unsafe { cmd.pre_exec(move || steps.run()) };
}
fn is_empty(&self) -> bool {
let Self {
enter,
session,
#[cfg(target_os = "linux")]
placement,
#[cfg(target_os = "macos")]
preserved,
fd_map,
} = self;
#[cfg(target_os = "linux")]
let other = placement.is_none();
#[cfg(target_os = "macos")]
let other = preserved.is_empty();
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let other = true;
enter.is_none() && !session && other && fd_map.is_none()
}
fn run(&mut self) -> io::Result<()> {
if let Some(dir) = &self.enter {
#[expect(
clippy::disallowed_methods,
reason = "this closure runs in the forked child, between fork and exec, so the chdir \
moves that child's cwd and never this process's — see `enter_in_child`'s doc"
)]
let status = unsafe { libc::chdir(dir.as_ptr()) };
if status != 0 {
return Err(io::Error::last_os_error());
}
}
if self.session && unsafe { libc::setsid() } == -1 {
return Err(io::Error::last_os_error());
}
#[cfg(target_os = "linux")]
if let Some((procs_fd, slot)) = self.placement {
unsafe { crate::containment::cgroup::placement_hook(procs_fd, slot) }?;
}
#[cfg(target_os = "macos")]
fd_map::preserve(&self.preserved)?;
if let Some(plan) = &mut self.fd_map {
plan.apply()?;
}
Ok(())
}
}
#[cfg(test)]
pub(crate) fn register_alone<R>(cmd: &mut std::process::Command, add: impl FnOnce(&mut InChild) -> R) -> R {
let mut steps = InChild::default();
let added = add(&mut steps);
steps.register(cmd);
added
}
#[cfg(test)]
#[path = "in_child_tests.rs"]
mod in_child_tests;