use crate::containment::{ContainMode, ContainRequest, Containment, Nesting};
use crate::error::Error;
pub(crate) struct Prepared {
pub mode: Option<ContainMode>,
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>,
#[cfg(windows)]
pub graceful: crate::graceful::GracefulMechanism,
#[cfg(windows)]
pub frozen: bool,
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ChildHandle<'a> {
pub(crate) pid: u32,
pub(crate) pidfd: std::os::fd::BorrowedFd<'a>,
}
impl Prepared {
pub(crate) fn graceful_mechanism(&self) -> crate::graceful::GracefulMechanism {
#[cfg(windows)]
return self.graceful;
#[cfg(not(windows))]
return crate::graceful::GracefulMechanism::Process;
}
pub(crate) fn settle_verdict(
&mut self,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
#[cfg(not(target_os = "linux"))] pid: u32,
) {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut().filter(|leaf| leaf.holds_verdict_to_take()) {
if let Err(e) = leaf.take_placement(child) {
log::debug!("cgroup v2: a failed spawn's child is not placed in its leaf: {e}");
}
}
#[cfg(not(target_os = "linux"))]
let _ = pid;
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only the tokio spawn path can lose a handle before a verdict is settled"
)
)]
pub(crate) fn abandon_before_verdict(
&mut self,
front: bool,
#[cfg(target_os = "linux")] handshake: Option<std::os::fd::OwnedFd>,
) -> AbandonedChild {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut() {
use crate::containment::cgroup::Abandoned;
return match leaf.abandon_before_verdict(front, handshake) {
Abandoned::Ended => AbandonedChild::Ended,
Abandoned::MaybeUnreaped => AbandonedChild::MaybeUnreaped,
Abandoned::OutOfReach => AbandonedChild::MaybeUnreachable,
Abandoned::Front(fate) => AbandonedChild::Front(fate),
};
}
#[cfg(not(target_os = "linux"))]
let _ = front;
AbandonedChild::MaybeUnreachable
}
pub(crate) fn watch_front(&mut self, pid: u32) {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut() {
leaf.watch_front(pid);
}
#[cfg(not(target_os = "linux"))]
let _ = pid;
}
}
#[cfg_attr(
not(all(target_os = "linux", feature = "tokio")),
allow(
dead_code,
reason = "only a Linux leaf under tokio produces more than MaybeUnreachable"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AbandonedChild {
Ended,
MaybeUnreaped,
MaybeUnreachable,
Front(crate::child::spawn::FrontFate),
}
pub(crate) struct Attachment {
pub containment: Containment,
pub attached: Attached,
pub graceful: crate::graceful::GracefulMechanism,
}
#[cfg(windows)]
impl Attachment {
pub(crate) fn uac_elevated() -> Attachment {
Attachment {
containment: Containment::None,
attached: Attached::None,
graceful: crate::graceful::GracefulMechanism::Unknown,
}
}
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) enum RootView {
Reaped,
Unknown(std::io::Error),
Unpinned,
Trusted,
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) struct DropView {
pub(crate) root_pid: u32,
pub(crate) root: RootView,
pub(crate) tree_killed: bool,
}
#[cfg(unix)]
impl DropView {
pub(crate) fn read(
label: &str,
id: crate::identity::ProcessId,
root: impl FnOnce() -> crate::signal::RootState,
tree_killed: &TreeKilled,
) -> DropView {
use crate::signal::RootState;
let root_pid = id.pid();
let now = crate::child::root_identity_now(root_pid);
let state = root();
let handle_reaped = matches!(state, RootState::Reaped);
let root = if crate::child::root_reaped(handle_reaped, id, now) {
match &state {
RootState::Unknown(e) => log::debug!(
"{label}: the root's own handle could not say whether it was reaped ({e}), but its number shows it reaped"
),
RootState::Unpinned => log::debug!(
"{label}: the root is not pinned by this process, but its number shows it reaped"
),
RootState::Unreaped | RootState::Reaped => {}
}
RootView::Reaped
} else {
match state {
RootState::Unreaped => RootView::Trusted,
RootState::Unknown(e) => RootView::Unknown(e),
RootState::Unpinned => RootView::Unpinned,
RootState::Reaped => RootView::Reaped,
}
};
let view = DropView {
root_pid,
root,
tree_killed: tree_killed.is_set(),
};
if now.is_unknown() && !handle_reaped {
if view.unsettled() {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read either; kills by that number are skipped"
);
} else {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read; treating the root as not reaped"
);
}
}
view
}
pub(crate) fn unsettled(&self) -> bool {
matches!(self.root, RootView::Unknown(_) | RootView::Unpinned)
}
pub(crate) fn number_untrusted(&self) -> bool {
!matches!(self.root, RootView::Trusted)
}
pub(crate) fn unpinned_root(&self) -> bool {
matches!(self.root, RootView::Unpinned)
}
pub(crate) fn leaves_root_alone(&self) -> bool {
matches!(self.root, RootView::Reaped | RootView::Unpinned)
}
pub(crate) fn why_number_untrusted(&self) -> String {
match &self.root {
RootView::Unknown(e) => format!("the root could not be shown to be unreaped (RootState::Unknown: {e})"),
RootView::Unpinned => format!(
"the root is not pinned by this process (RootState::Unpinned: {})",
crate::signal::UNPINNED_WHY
),
RootView::Reaped => "the root is already reaped".to_owned(),
RootView::Trusted => {
debug_assert!(false, "a trusted root's number is not untrusted");
"the root's number is trusted".to_owned()
}
}
}
pub(crate) fn skipped_action(&self, attached: &Attached) -> Option<String> {
attached
.named_by_root_number(self.root_pid, "kill")
.filter(|_| self.number_untrusted())
}
}
#[derive(Debug, Default)]
pub(crate) struct TreeKilled(std::sync::atomic::AtomicBool);
impl TreeKilled {
pub(crate) fn mark(&self) {
self.0.store(true, std::sync::atomic::Ordering::Release);
}
#[cfg_attr(not(unix), allow(dead_code, reason = "read only by the Unix drop decision"))]
pub(crate) fn is_set(&self) -> bool {
self.0.load(std::sync::atomic::Ordering::Acquire)
}
}
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, Copy)]
pub(crate) enum TreeSignal {
Kill,
Term,
}
#[cfg(unix)]
pub(crate) struct DropKill {
pub(crate) result: Result<(), Error>,
pub(crate) skipped: Option<String>,
}
#[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 {
#[cfg(unix)]
pub(crate) fn teardown_subject(&self) -> String {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return format!("cgroup leaf {}", leaf.path().display());
}
format!("{self:?}")
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup reads it")
)]
pub(crate) fn kill_reaches_across_credentials(
&self,
pid: u32,
pidfd: Option<std::os::fd::BorrowedFd<'_>>,
) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return leaf.holds_member(pid, pidfd);
}
Ok(false)
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup reads it")
)]
pub(crate) fn cgroup_names(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return leaf.names(pid, pidfd);
}
Ok(false)
}
pub(crate) fn hard_kill(&self) -> Result<(), crate::error::Error> {
self.hard_kill_report().0
}
pub(crate) fn hard_kill_marking(&self, killed: &TreeKilled) -> Result<(), crate::error::Error> {
let (result, complete) = self.hard_kill_report();
if result.is_ok() && complete {
killed.mark();
}
result
}
fn hard_kill_report(&self) -> (Result<(), crate::error::Error>, bool) {
let result = 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(),
#[cfg(windows)]
Attached::JobObject(job) => job.hard_kill().map_err(Error::Io),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.hard_kill(),
Attached::TreeWalk(root) => {
return match crate::containment::treewalk::hard_kill(*root) {
Ok(complete) => (Ok(()), complete),
Err(e) => (Err(e), false),
};
}
};
let complete = result.is_ok();
(result, complete)
}
pub(crate) fn hard_kill_refused_to_walk(&self, result: &Result<(), crate::error::Error>) -> bool {
matches!(self, Attached::TreeWalk(_)) && result.is_err()
}
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 honor_kill_on_drop(&self, kill_on_drop: bool) {
if !kill_on_drop {
self.disarm();
}
}
pub(crate) fn disarm(&self) {
match self {
Attached::None | Attached::Delegated => {}
#[cfg(unix)]
Attached::ProcessGroup(_) => {} #[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.disarm(), #[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,
}
}
#[cfg(unix)]
fn named_by_root_number(&self, root_pid: u32, verb: &str) -> Option<String> {
match self {
Attached::ProcessGroup(pgid) => Some(format!("{verb} its process group (pgid {pgid})")),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => {
let walk = format!("walk the process table from the root's pid (root pid {root_pid})");
Some(match m.pgid() {
Some(pgid) => format!("{verb} its process group (pgid {pgid}) or {walk}"),
None => walk,
})
}
Attached::TreeWalk(_) => Some(format!(
"walk the process table from the root's pid (root pid {root_pid})"
)),
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn hard_kill_for_drop(&self, view: &DropView) -> DropKill {
let Some(skipped) = view.skipped_action(self) else {
return DropKill {
result: self.hard_kill(),
skipped: None,
};
};
let why = view.why_number_untrusted();
let left_behind = if view.tree_killed {
log::debug!(
"Child::drop: {why} and this handle already killed the tree, \
so this drop does not {skipped}"
);
None
} else {
if !matches!(view.root, RootView::Reaped) {
log::debug!("Child::drop: {why}, so this drop does not {skipped}");
}
Some(skipped)
};
let result = match self {
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.hard_kill_holders_only(view.unpinned_root().then(|| m.root())),
_ => Ok(()),
};
DropKill {
result,
skipped: left_behind,
}
}
#[cfg(target_os = "macos")]
pub(crate) fn signal_tree_untrusted(
&self,
signal: TreeSignal,
root: &crate::signal::RootState,
root_pid: u32,
op: &str,
earlier: Option<&str>,
killed: &TreeKilled,
) -> Option<Result<(), Error>> {
let verb = match signal {
TreeSignal::Kill => "kill",
TreeSignal::Term => "signal",
};
let skipped = self.named_by_root_number(root_pid, verb)?;
let why = crate::signal::why_untrusted(root);
let Attached::FdMarker(m) = self else {
let earlier = earlier.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
return Some(Err(Error::Unassessable {
detail: format!(
"pid {root_pid}: {why}; {op} sent nothing{earlier}: its signals are all named by the root's \
number, so it did not {skipped}"
),
source: None,
}));
};
let except = matches!(root, crate::signal::RootState::Unpinned).then(|| m.root());
log::debug!("{op}: {why}, so it does not {skipped}; it signals the marker holders");
let result = match signal {
TreeSignal::Kill => m.hard_kill_holders_only(except),
TreeSignal::Term => m.terminate_holders_only(except),
};
if result.is_ok() && matches!(signal, TreeSignal::Kill) {
killed.mark();
}
Some(result)
}
#[cfg(target_os = "macos")]
pub(crate) fn names_tree_by_identity(&self) -> bool {
matches!(self, Attached::FdMarker(_))
}
#[cfg(unix)]
pub(crate) fn hard_kill_marking_unless_reaped(
&self,
view: &DropView,
killed: &TreeKilled,
) -> Result<Option<String>, crate::error::Error> {
let Some(skipped) = view.skipped_action(self) else {
return self.hard_kill_marking(killed).map(|()| None);
};
match self {
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.hard_kill_holders_only(view.unpinned_root().then(|| m.root()))?,
_ => {}
}
Ok(Some(format!(
"{}, so its number may name another process, and the kill would {skipped}",
view.why_number_untrusted()
)))
}
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,
}
}
#[cfg(feature = "tokio")]
pub(crate) fn release_without_waiting(self) {
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.release_without_waiting(),
other => drop(other),
}
}
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> {
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("waiting for the contained tree to drain");
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_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS leaves a child unverified")
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RootIdentity {
Gone,
Unknown,
}
#[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(windows),
allow(
unused_variables,
reason = "only Windows can honour the caller's creation-flag request"
)
)]
flags: &crate::command::flags::FlagsRequest,
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "drives the macOS fd-marker install only")
)]
reserved_fds: &[i32],
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "drives the macOS fd-marker install only")
)]
marker_suppressed: bool,
#[cfg_attr(
not(windows),
allow(unused_variables, reason = "only the Windows path composes env ops into the request")
)]
env_ops: &[crate::command::EnvOp],
) -> Result<Prepared, Error> {
let mode = req.mode;
#[cfg(windows)]
let snapshot = crate::child::spawn::windows_raw::env_snapshot::EnvSnapshot::read()?;
#[cfg(windows)]
let marker_present = snapshot
.var(std::ffi::OsStr::new(crate::containment::NESTED_ENV))
.is_some();
#[cfg(not(windows))]
let marker_present = std::env::var_os(crate::containment::NESTED_ENV).is_some();
let is_root = !is_nested(marker_present);
#[cfg(windows)]
let graceful = {
use std::os::windows::process::CommandExt;
let spawn =
crate::command::flags::windows_spawn(req, *flags, is_root, crate::command::flags::SpawnBackend::Std)?;
std_cmd.creation_flags(spawn.creation_flags);
crate::containment::windows::mechanism_from_flags(spawn.creation_flags)
};
if mode.is_none() {
return Ok(Prepared {
mode: None,
is_root: false,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker: None,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
});
}
let marker_env = is_root && req.nesting == Nesting::Mark;
#[cfg(windows)]
{
use crate::child::spawn::windows_raw::{child_ops, resolve::ChildEnv};
let env = ChildEnv::capture(&snapshot, &child_ops(env_ops, marker_env));
std_cmd.env_clear();
std_cmd.envs(env.captured_vars().expect("a capture is never inherited"));
}
#[cfg(not(windows))]
if marker_env {
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 Ok(Prepared {
mode,
is_root,
cgroup_leaf: None, });
}
UnixSetup::None => {
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None,
});
}
UnixSetup::ProcessGroup => {
crate::containment::unix::set_process_group(std_cmd);
}
}
let leaf = match crate::containment::cgroup::try_create_leaf() {
Ok(leaf) => Some(leaf),
Err(e) => {
crate::containment::cgroup::log_degrade(&e);
None
}
};
if let Some(ref l) = leaf {
let procs_fd = l.procs_fd();
let slot = l.placement_slot();
unsafe {
use std::os::unix::process::CommandExt;
std_cmd.pre_exec(move || crate::containment::cgroup::placement_hook(procs_fd, slot));
}
}
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: leaf,
});
}
return Ok(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)]
crate::containment::windows::clear_std_handle_inheritance();
#[cfg_attr(
target_os = "linux",
expect(unreachable_code, reason = "the linux block above returns on every path")
)]
Ok(Prepared {
mode,
is_root,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
})
}
pub(crate) fn attach(
id: crate::identity::ProcessId,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<Attachment, Error> {
let graceful = prepared.graceful_mechanism();
let (containment, attached) = attach_tree(
id,
#[cfg(target_os = "linux")]
child,
#[cfg(windows)]
proc_handle,
prepared,
)?;
Ok(Attachment {
containment,
attached,
graceful,
})
}
fn attach_tree(
id: crate::identity::ProcessId,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<(Containment, Attached), Error> {
#[cfg(unix)]
let pid = id.pid();
#[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(id)));
}
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(mut leaf) = prepared.cgroup_leaf {
match leaf.take_placement(child) {
Ok(()) => return Ok((Containment::CgroupV2, Attached::Cgroup(leaf))),
Err(reason) => {
crate::containment::cgroup::log_degrade(&reason);
leaf.remove_unentered();
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 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, id, pgid)),
));
}
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(id)));
}
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(id)));
}
if prepared.frozen {
return match crate::containment::windows::assign_held(proc_handle) {
Ok(job) => Ok((Containment::JobObject, Attached::JobObject(job))),
Err(e) => Err(Error::Containment { detail: e.to_string() }),
};
}
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(id)));
}
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;