use crate::containment::{ContainMode, ContainRequest, Containment, Nesting};
use crate::error::Error;
pub(crate) struct Prepared {
#[allow(dead_code)] pub mode: Option<ContainMode>,
#[allow(dead_code)] pub is_root: bool,
#[cfg(target_os = "linux")]
pub cgroup_leaf: Option<crate::containment::cgroup::CgroupLeaf>,
#[cfg(target_os = "macos")]
pub marker: Option<crate::containment::fdmarker::PreparedMarker>,
}
#[derive(Debug, Default)]
pub(crate) enum Attached {
#[default]
None,
Delegated,
#[cfg(unix)]
ProcessGroup(i32), #[cfg(target_os = "linux")]
Cgroup(crate::containment::cgroup::CgroupLeaf),
#[cfg(windows)]
JobObject(crate::containment::windows::JobHandle),
#[cfg(target_os = "macos")]
FdMarker(crate::containment::fdmarker::Marker),
TreeWalk(crate::identity::ProcessId),
}
#[cfg(target_os = "linux")]
impl std::fmt::Debug for crate::containment::cgroup::CgroupLeaf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CgroupLeaf").finish_non_exhaustive()
}
}
impl Attached {
pub(crate) fn hard_kill(&self) -> Result<(), crate::error::Error> {
match self {
Attached::None | Attached::Delegated => Ok(()),
#[cfg(unix)]
Attached::ProcessGroup(pgid) => crate::containment::unix::kill_group(*pgid),
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => {
leaf.hard_kill();
Ok(())
}
#[cfg(windows)]
Attached::JobObject(job) => {
job.hard_kill();
Ok(())
}
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.hard_kill(),
Attached::TreeWalk(root) => {
crate::containment::treewalk::hard_kill(*root);
Ok(())
}
}
}
pub(crate) fn terminate(&self, _child_pid: u32) -> Result<(), Error> {
match self {
Attached::None | Attached::Delegated => {
debug_assert!(
self.is_actionable(),
"Attached::terminate on a non-actionable mechanism"
);
Err(crate::error::Error::Unsupported {
op: "terminate on a non-actionable mechanism".into(),
platform: std::env::consts::OS,
detail: "internal invariant: a non-actionable mechanism reached terminate".into(),
})
}
#[cfg(unix)]
Attached::ProcessGroup(pgid) => crate::containment::unix::term_group(*pgid),
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.terminate().map_err(Error::Io),
#[cfg(windows)]
Attached::JobObject(_) => crate::containment::windows::terminate(_child_pid),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.terminate(),
Attached::TreeWalk(root) => crate::containment::treewalk::terminate(*root),
}
}
pub(crate) fn disarm(&self) {
match self {
Attached::None | Attached::Delegated => {}
#[cfg(unix)]
Attached::ProcessGroup(_) => {} #[cfg(target_os = "linux")]
Attached::Cgroup(_) => {} #[cfg(windows)]
Attached::JobObject(job) => job.disarm(), #[cfg(target_os = "macos")]
Attached::FdMarker(_) => {}
Attached::TreeWalk(_) => {} }
}
#[cfg(unix)]
pub(crate) fn carries_recyclable_pgid(&self) -> bool {
match self {
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.has_pgid(),
_ => false,
}
}
pub(crate) fn is_actionable(&self) -> bool {
match self {
Attached::None | Attached::Delegated => false,
#[cfg(unix)]
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "linux")]
Attached::Cgroup(_) => true,
#[cfg(windows)]
Attached::JobObject(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(_) => true,
Attached::TreeWalk(_) => true,
}
}
pub(crate) fn can_observe_drain(&self) -> bool {
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(_) => true,
#[cfg(windows)]
Attached::JobObject(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(_) => true,
_ => false,
}
}
pub(crate) fn wait_drained(
&self,
deadline: Option<Option<std::time::Instant>>,
) -> Result<crate::containment::TreeDrain, Error> {
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.wait_drained(deadline),
#[cfg(windows)]
Attached::JobObject(job) => job.wait_drained(deadline, None),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.wait_drained(deadline),
_ => Err(Error::Unsupported {
op: "wait for the contained tree to drain".into(),
platform: std::env::consts::OS,
detail: "this child's containment mechanism exposes no kernel edge for tree drain".into(),
}),
}
}
}
pub(crate) fn is_nested(marker_present: bool) -> bool {
marker_present
}
#[cfg(any(unix, windows))]
fn resolve_root_id(pid: u32) -> Result<crate::identity::ProcessId, Error> {
match crate::identity::ProcessId::of(pid) {
crate::identity::Resolved::Found(id) => Ok(id),
crate::identity::Resolved::Gone => Err(Error::Containment {
detail: "tree-walk root vanished before its identity could be read".into(),
}),
crate::identity::Resolved::Unknown => Err(Error::Unassessable {
detail: format!("tree-walk root pid {pid} identity could not be read"),
source: None,
}),
}
}
#[cfg(unix)]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum UnixSetup {
Session,
ProcessGroup,
None,
}
#[cfg(unix)]
pub(crate) fn unix_setup_for(mode: Option<ContainMode>) -> UnixSetup {
match mode {
Some(ContainMode::Session) => UnixSetup::Session,
Some(ContainMode::TreeWalk) => UnixSetup::None,
_ => UnixSetup::ProcessGroup,
}
}
#[cfg(windows)]
pub(crate) struct WindowsContain {
pub creation_flags: u32,
pub marker_env: bool,
}
#[cfg(windows)]
pub(crate) fn windows_contain_setup(req: &ContainRequest, is_root: bool) -> WindowsContain {
let Some(mode) = req.mode else {
return WindowsContain {
creation_flags: 0,
marker_env: false,
};
};
let creation_flags = if is_root && !matches!(mode, ContainMode::TreeWalk) {
crate::containment::windows::root_flags()
} else {
crate::containment::windows::group_flags()
};
WindowsContain {
creation_flags,
marker_env: is_root && req.nesting == Nesting::Mark,
}
}
pub(crate) fn prepare(
std_cmd: &mut std::process::Command,
req: &ContainRequest,
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] reserved_fds: &[i32],
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] marker_suppressed: bool,
) -> Prepared {
let mode = req.mode;
if mode.is_none() {
return Prepared {
mode: None,
is_root: false,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker: None,
};
}
let marker_present = std::env::var_os(crate::containment::NESTED_ENV).is_some();
let is_root = !is_nested(marker_present);
if is_root && req.nesting == Nesting::Mark {
std_cmd.env(crate::containment::NESTED_ENV, "1");
}
#[cfg(target_os = "linux")]
{
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => {
crate::containment::unix::set_session(std_cmd);
return Prepared {
mode,
is_root,
cgroup_leaf: None, };
}
UnixSetup::None => {
return Prepared {
mode,
is_root,
cgroup_leaf: None,
};
}
UnixSetup::ProcessGroup => {
crate::containment::unix::set_process_group(std_cmd);
}
}
let leaf = crate::containment::cgroup::try_create_leaf();
if let Some(ref l) = leaf {
let procs_fd = l.procs_fd();
unsafe {
use std::os::unix::process::CommandExt;
std_cmd.pre_exec(move || {
let _ = crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd);
Ok(())
});
}
}
return Prepared {
mode,
is_root,
cgroup_leaf: leaf,
};
}
return Prepared {
mode,
is_root,
cgroup_leaf: None,
};
}
#[cfg(all(unix, not(target_os = "linux")))]
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => crate::containment::unix::set_session(std_cmd),
UnixSetup::ProcessGroup => crate::containment::unix::set_process_group(std_cmd),
UnixSetup::None => {} }
}
#[cfg(target_os = "macos")]
let marker = if crate::containment::fdmarker::marker_wanted(mode, is_root, marker_suppressed) {
crate::containment::fdmarker::install(std_cmd, reserved_fds)
} else {
None
};
#[cfg(windows)]
if mode.is_some() {
use std::os::windows::process::CommandExt;
crate::containment::windows::clear_std_handle_inheritance();
let setup = windows_contain_setup(req, is_root);
std_cmd.creation_flags(setup.creation_flags);
}
#[allow(unreachable_code)]
Prepared {
mode,
is_root,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker,
}
}
pub(crate) fn attach(
pid: u32,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<(Containment, Attached), Error> {
#[cfg(target_os = "linux")]
{
if prepared.mode.is_some() {
if prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
if matches!(prepared.mode, Some(ContainMode::Session)) {
return Ok((Containment::Session, Attached::ProcessGroup(pgid)));
}
if let Some(leaf) = prepared.cgroup_leaf {
if leaf.contains_pid(raw_pid) {
return Ok((Containment::CgroupV2, Attached::Cgroup(leaf)));
}
drop(leaf);
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
}
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
} else {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
if prepared.mode.is_some() {
if prepared.is_root {
#[cfg(target_os = "macos")]
if let Some(marker) = prepared.marker {
let (root, root_denied) = match crate::identity::ProcessId::of(pid) {
crate::identity::Resolved::Found(id) => (Some(id), false),
crate::identity::Resolved::Gone => {
log::debug!(
"fd marker: the root exited before its identity could be read; \
the sweep runs without its ppid-walk channel (the marker and \
group channels do not need it)"
);
(None, false)
}
crate::identity::Resolved::Unknown => {
log::warn!(
"fd marker: the root's identity could not be read (access \
denied); the sweep runs without its ppid-walk channel, and \
every pass reports this marker as incomplete"
);
(None, true)
}
};
let pgid = match prepared.mode {
Some(ContainMode::TreeWalk) => None,
_ => {
debug_assert!(
pid <= i32::MAX as u32,
"pid {pid} exceeds i32::MAX; pgid cast would truncate"
);
Some(pid as i32)
}
};
return Ok((
Containment::FdMarker,
Attached::FdMarker(crate::containment::fdmarker::Marker::new(
marker,
root,
pgid,
root_denied,
)),
));
}
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
let containment = match prepared.mode {
Some(ContainMode::Session) => Containment::Session,
_ => Containment::ProcessGroup,
};
return Ok((containment, Attached::ProcessGroup(pgid)));
} else {
#[cfg(target_os = "macos")]
if prepared.marker.is_some() {
log::warn!(
"fd marker: a nested spawn's prepare() unexpectedly produced a marker; \
a nested member must inherit the root's marker, never create its own \
— discarding it"
);
debug_assert!(
false,
"a nested member inherits the root's marker and must never create one"
);
}
return Ok((Containment::Delegated, Attached::Delegated));
}
}
}
#[cfg(windows)]
{
if prepared.mode.is_some() && prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
match crate::containment::windows::attach_job(proc_handle) {
Ok(Some(job)) => return Ok((Containment::JobObject, Attached::JobObject(job))),
Ok(None) => {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
Err(e) => return Err(Error::Containment { detail: e.to_string() }),
}
} else if prepared.mode.is_some() {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
let _ = prepared;
Ok((Containment::None, Attached::None))
}
#[cfg(test)]
#[path = "dispatch_tests.rs"]
mod dispatch_tests;