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;
#[cfg(not(target_os = "linux"))]
use std::os::unix::process::CommandExt;
use super::fd_map;
#[cfg(target_os = "linux")]
use super::fork_exec::Reporter;
#[derive(Default)]
pub(crate) struct InChild {
#[cfg(target_os = "linux")]
stdio: Option<fd_map::Plan>,
enter: Option<CString>,
#[cfg(target_os = "linux")]
process_group: bool,
#[cfg(target_os = "linux")]
sigpipe_default: bool,
session: bool,
#[cfg(target_os = "linux")]
placement: Option<(RawFd, bool)>,
#[cfg(target_os = "macos")]
preserved: Vec<OwnedFd>,
fd_map: Option<fd_map::Plan>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Step {
#[cfg(target_os = "linux")]
Stdio,
Enter,
#[cfg(target_os = "linux")]
ProcessGroup,
#[cfg(target_os = "linux")]
SigpipeDefault,
Session,
#[cfg(target_os = "linux")]
Placement,
#[cfg(target_os = "macos")]
Preserve,
FdMap,
}
impl Step {
fn failed(self, error: io::Error) -> StepError {
StepError { step: self, error }
}
}
#[derive(Debug)]
pub(crate) struct StepError {
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn reports which step failed")
)]
pub(super) step: Step,
pub(super) error: io::Error,
}
impl InChild {
#[cfg(target_os = "linux")]
pub(super) fn map_stdio(&mut self, plan: fd_map::Plan) {
debug_assert!(self.stdio.is_none(), "a spawn has one stdio plan");
self.stdio = Some(plan);
self.sigpipe_default = true;
}
#[cfg(target_os = "linux")]
pub(crate) fn process_group(&mut self) {
debug_assert!(!self.process_group, "a spawn asks for its process group once");
self.process_group = true;
}
#[cfg(target_os = "linux")]
pub(crate) fn mapped_fds(&self) -> Vec<RawFd> {
self.fd_map
.as_ref()
.map_or_else(Vec::new, |plan| plan.child_fds().to_vec())
}
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, refusing: bool) {
debug_assert!(self.placement.is_none(), "a spawn places its child once");
self.placement = Some((procs_fd, refusing));
}
#[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);
}
#[cfg(not(target_os = "linux"))]
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().map_err(|failed| failed.error)) };
}
#[cfg(not(target_os = "linux"))]
fn is_empty(&self) -> bool {
let Self {
enter,
session,
#[cfg(target_os = "macos")]
preserved,
fd_map,
} = self;
#[cfg(target_os = "macos")]
let other = preserved.is_empty();
#[cfg(not(target_os = "macos"))]
let other = true;
enter.is_none() && !session && other && fd_map.is_none()
}
pub(super) fn run(&mut self, #[cfg(target_os = "linux")] reporter: Reporter) -> Result<(), StepError> {
#[cfg(target_os = "linux")]
if let Some(plan) = &mut self.stdio {
plan.apply().map_err(|error| Step::Stdio.failed(error))?;
}
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(Step::Enter.failed(io::Error::last_os_error()));
}
}
#[cfg(target_os = "linux")]
if self.process_group && unsafe { libc::setpgid(0, 0) } == -1 {
return Err(Step::ProcessGroup.failed(io::Error::last_os_error()));
}
#[cfg(target_os = "linux")]
if self.sigpipe_default {
if unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) } == libc::SIG_ERR {
return Err(Step::SigpipeDefault.failed(io::Error::last_os_error()));
}
}
if self.session && unsafe { libc::setsid() } == -1 {
return Err(Step::Session.failed(io::Error::last_os_error()));
}
#[cfg(target_os = "linux")]
if let Some((procs_fd, refusing)) = self.placement {
unsafe { crate::containment::cgroup::placement_step(procs_fd, refusing, reporter) }
.map_err(|error| Step::Placement.failed(error))?;
}
#[cfg(target_os = "macos")]
fd_map::preserve(&self.preserved).map_err(|error| Step::Preserve.failed(error))?;
if let Some(plan) = &mut self.fd_map {
plan.apply().map_err(|error| Step::FdMap.failed(error))?;
}
Ok(())
}
}
#[cfg(all(test, not(target_os = "linux")))]
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(all(test, target_os = "linux"))]
pub(super) fn spawn_sh(script: &str, steps: &mut InChild) -> io::Result<super::fork_spawn::Started> {
spawn_sh_placed(script, steps, None)
}
#[cfg(all(test, target_os = "linux"))]
pub(super) fn spawn_sh_placed(
script: &str,
steps: &mut InChild,
leaf: Option<&mut crate::containment::cgroup::CgroupLeaf>,
) -> io::Result<super::fork_spawn::Started> {
use std::ffi::OsStr;
let argv = [OsStr::new("sh"), OsStr::new("-c"), OsStr::new(script)];
let program = super::fork_exec::Program::new(&[OsStr::new("/bin/sh")], &argv, std::env::vars_os()).expect("no NUL");
let lock = super::spawn_lock();
super::fork_spawn::start(
&program,
steps,
crate::identity::spawn_kernel(crate::identity::HostKernel),
super::fork_spawn::OnFailure {
policy: super::policy::SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement: leaf,
refusing_placement: false,
},
&lock,
)
.map_err(|failure| failure.expect_not_started().into_io())
}
#[cfg(all(test, target_os = "linux"))]
pub(super) fn exit_code(started: &super::fork_spawn::Started) -> Option<i32> {
use crate::child::owned::ChildWaitOutcome;
use crate::os_process::child::ExitRecord;
match started.owned.wait(None).expect("wait") {
ChildWaitOutcome::Exited(ExitRecord::Status(status)) => status.code(),
other => panic!("the child did not exit with a status: {other:?}"),
}
}
#[cfg(test)]
#[path = "in_child_tests.rs"]
mod in_child_tests;