use std::collections::BTreeMap;
use std::collections::VecDeque;
use serde::Deserialize;
use serde::Serialize;
use tracing::debug;
use tracing::info;
use super::Scheduler;
use crate::types::DetPid;
use crate::types::DetTid;
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct ChildExitSiginfo {
pub code: i32,
pub pid: i32,
pub uid: u32,
pub status: i32,
}
impl ChildExitSiginfo {
pub fn to_bytes(self) -> [u8; 128] {
let mut bytes = [0; 128];
bytes[0..4].copy_from_slice(&libc::SIGCHLD.to_ne_bytes());
bytes[8..12].copy_from_slice(&self.code.to_ne_bytes());
bytes[16..20].copy_from_slice(&self.pid.to_ne_bytes());
bytes[20..24].copy_from_slice(&self.uid.to_ne_bytes());
bytes[24..28].copy_from_slice(&self.status.to_ne_bytes());
bytes
}
}
pub fn siginfo_code_and_pid(bytes: &[u8; 128]) -> (i32, i32) {
let field = |at: usize| i32::from_ne_bytes(bytes[at..at + 4].try_into().expect("four bytes"));
(field(8), field(16))
}
pub const OWN_SIGCHLD_MARK: i32 = 0x4843_4c44;
pub fn marked_own_copy(tracer: u32, uid: u32) -> [u8; 128] {
let mut bytes = [0; 128];
bytes[0..4].copy_from_slice(&libc::SIGCHLD.to_ne_bytes());
bytes[8..12].copy_from_slice(&libc::SI_QUEUE.to_ne_bytes());
bytes[16..20].copy_from_slice(&tracer.to_ne_bytes());
bytes[20..24].copy_from_slice(&uid.to_ne_bytes());
bytes[24..28].copy_from_slice(&OWN_SIGCHLD_MARK.to_ne_bytes());
bytes
}
pub fn is_own_sigchld_mark(code: i32, pid: i32, value: i32, tracer: u32) -> bool {
(code == libc::SI_USER && pid as u32 == tracer)
|| (code == libc::SI_QUEUE && pid == 0 && value == OWN_SIGCHLD_MARK)
}
pub fn is_child_exit_code(code: i32) -> bool {
matches!(code, libc::CLD_EXITED | libc::CLD_KILLED | libc::CLD_DUMPED)
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum DequeuedCopy {
Kernel { child: DetPid },
Scheduler,
Other,
Unknown,
Thread,
}
pub fn dequeued_copy(info: &[u8; 128], tracer: u32) -> Option<DequeuedCopy> {
let (code, pid, value) = siginfo_code_pid_and_value(info);
Some(copy_of(code, pid, value, tracer))
}
fn siginfo_code_pid_and_value(info: &[u8; 128]) -> (i32, i32, i32) {
let (code, pid) = siginfo_code_and_pid(info);
let value = i32::from_ne_bytes(info[24..28].try_into().expect("four bytes"));
(code, pid, value)
}
fn copy_of(code: i32, pid: i32, value: i32, tracer: u32) -> DequeuedCopy {
if is_child_exit_code(code) {
DequeuedCopy::Kernel {
child: DetPid::from_raw(pid),
}
} else if is_own_sigchld_mark(code, pid, value, tracer) {
DequeuedCopy::Scheduler
} else if code == libc::SI_TKILL {
DequeuedCopy::Thread
} else {
DequeuedCopy::Other
}
}
pub fn taken_control(info: &[u8; 128], admits: bool) -> ChildExitSigchldControl {
let (code, pid, value) = siginfo_code_pid_and_value(info);
ChildExitSigchldControl::Taken {
code,
pid,
value,
admits,
}
}
pub fn control_for(info: &[u8; 128], tracer: u32, admits: bool) -> Option<ChildExitSigchldControl> {
Some(ChildExitSigchldControl::Dequeue {
copy: dequeued_copy(info, tracer)?,
admits,
})
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum ChildExitSigchldControl {
ExitStatus { code: i32, status: i32, uid: u32 },
ClaimKernelCopy { child: DetPid },
TakeOwnCopy,
Dequeue { copy: DequeuedCopy, admits: bool },
Flushed,
PlacedPending,
PrivateSent { target: DetTid },
SharedSent { target: DetPid },
WaitFaulted {
private_pending: bool,
shared_pending: bool,
},
SendFailed {
private: Option<DetTid>,
shared: Option<DetPid>,
},
RawExitStatus { code: i32, status: i32, uid: u32 },
PrivatePending,
WindowUnusable,
ClaimedDelivery,
Taken {
code: i32,
pid: i32,
value: i32,
admits: bool,
},
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum OwnCopy {
Deliver(ChildExitSiginfo),
Duplicate,
Unowned,
}
#[derive(PartialEq, Debug, Eq, Clone, Copy)]
pub(crate) enum WindowSend {
Child(DetPid),
Scheduler,
ParentDeath,
Guest,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChildExitSend {
NotOwned,
Nothing,
Sent(Option<DetTid>),
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum ChildExitSigchldAnswer {
Recorded,
Claimed(bool),
OwnCopy(OwnCopy),
ClaimedFor(ChildExitSiginfo),
Placed(bool),
}
#[derive(PartialEq, Debug, Eq, Clone, Copy)]
enum Notification {
Unsent(ChildExitSiginfo),
Sent(ChildExitSiginfo),
DeliveredBeforeSend,
DeliveredWhileSent,
Delivered,
}
#[derive(Debug, Default)]
pub(crate) struct ChildExitSigchldLedger {
pub(super) exit_status: BTreeMap<DetPid, ChildExitSiginfo>,
owned: BTreeMap<DetPid, BTreeMap<DetPid, Notification>>,
sent: BTreeMap<DetPid, VecDeque<DetPid>>,
cohorts: BTreeMap<DetPid, u64>,
window: BTreeMap<DetPid, Vec<WindowSend>>,
pub(super) attributed: std::collections::BTreeSet<DetTid>,
pub(super) private_sent: std::collections::BTreeSet<DetTid>,
pub(super) outside_takers: std::collections::BTreeSet<DetPid>,
pub(super) raw_exit_status: BTreeMap<DetTid, ChildExitSiginfo>,
}
#[derive(PartialEq, Debug, Eq, Clone, Copy)]
pub(crate) enum TimerSend {
Send,
Nothing,
}
impl ChildExitSigchldLedger {
pub(crate) fn own(&mut self, parent: DetPid, child: DetPid) -> bool {
let Some(info) = self.exit_status.remove(&child) else {
return false;
};
self.owned
.entry(parent)
.or_default()
.insert(child, Notification::Unsent(info));
true
}
pub(crate) fn forget_exit_status(&mut self, process: DetPid) {
self.exit_status.remove(&process);
}
fn state(&mut self, parent: DetPid, child: DetPid) -> Option<&mut Notification> {
self.owned.get_mut(&parent)?.get_mut(&child)
}
fn forget(&mut self, parent: DetPid, child: DetPid) {
self.cohorts.remove(&child);
if let Some(children) = self.owned.get_mut(&parent) {
children.remove(&child);
if children.is_empty() {
self.owned.remove(&parent);
}
}
}
pub(crate) fn timer(&mut self, parent: DetPid, child: DetPid) -> Option<TimerSend> {
match *self.state(parent, child)? {
Notification::Unsent(info) => {
*self.state(parent, child)? = Notification::Sent(info);
self.sent.entry(parent).or_default().push_back(child);
Some(TimerSend::Send)
}
Notification::DeliveredBeforeSend => {
self.forget(parent, child);
Some(TimerSend::Nothing)
}
_ => None,
}
}
pub(crate) fn stand_in(&mut self, parent: DetPid, child: DetPid) {
if let Some(state) = self.state(parent, child) {
*state = Notification::Delivered;
}
}
pub(crate) fn join_cohort(&mut self, child: DetPid, cohort: u64) {
self.cohorts.insert(child, cohort);
}
fn claim_for_cohort(&mut self, parent: DetPid, child: DetPid) -> Option<ChildExitSiginfo> {
let cohort = *self.cohorts.get(&child)?;
let (member, info) = self
.owned
.get(&parent)?
.iter()
.filter(|(member, _)| self.cohorts.get(member) == Some(&cohort))
.find_map(|(member, state)| match *state {
Notification::Unsent(info) | Notification::Sent(info) => Some((*member, info)),
_ => None,
})?;
let state = self.state(parent, member)?;
*state = match *state {
Notification::Unsent(_) => Notification::DeliveredBeforeSend,
_ => Notification::DeliveredWhileSent,
};
Some(info)
}
fn outstanding_info(&mut self, parent: DetPid, child: DetPid) -> Option<ChildExitSiginfo> {
match *self.state(parent, child)? {
Notification::Unsent(info) | Notification::Sent(info) => Some(info),
_ => None,
}
}
fn claim(&mut self, parent: DetPid, child: DetPid) -> bool {
let Some(state) = self.state(parent, child) else {
return false;
};
match *state {
Notification::Unsent(_) => {
*state = Notification::DeliveredBeforeSend;
false
}
Notification::Sent(_) => {
*state = Notification::DeliveredWhileSent;
false
}
Notification::Delivered => {
self.forget(parent, child);
true
}
Notification::DeliveredBeforeSend | Notification::DeliveredWhileSent => false,
}
}
fn take_own(&mut self, parent: DetPid) -> OwnCopy {
let Some(order) = self.sent.get(&parent) else {
return OwnCopy::Unowned;
};
let children = self.owned.get(&parent);
let state = |child: &DetPid| children.and_then(|children| children.get(child)).copied();
let pick = |wanted: fn(Notification) -> bool| {
order
.iter()
.position(|child| state(child).is_some_and(wanted))
};
if let Some(at) = pick(|state| matches!(state, Notification::Sent(_))) {
let child = self.sent.get_mut(&parent).unwrap().remove(at).unwrap();
let Some(Notification::Sent(info)) = self.state(parent, child).copied() else {
unreachable!("picked a sent child");
};
*self.state(parent, child).unwrap() = Notification::Delivered;
self.tidy_sent(parent);
return OwnCopy::Deliver(info);
}
if let Some(at) = pick(|state| matches!(state, Notification::DeliveredWhileSent)) {
let child = self.sent.get_mut(&parent).unwrap().remove(at).unwrap();
self.forget(parent, child);
self.tidy_sent(parent);
return OwnCopy::Duplicate;
}
OwnCopy::Unowned
}
fn tidy_sent(&mut self, parent: DetPid) {
if self.sent.get(&parent).is_some_and(VecDeque::is_empty) {
self.sent.remove(&parent);
}
}
fn owns(&self, parent: DetPid, child: DetPid) -> bool {
self.owned
.get(&parent)
.is_some_and(|children| children.contains_key(&child))
}
pub(crate) fn note_send(&mut self, parent: DetPid, child: Option<DetPid>) {
let send = child.map_or(WindowSend::Scheduler, WindowSend::Child);
self.window.entry(parent).or_default().push(send);
}
pub(crate) fn note_parent_death_send(&mut self, parent: DetPid) {
self.window
.entry(parent)
.or_default()
.push(WindowSend::ParentDeath);
}
pub(crate) fn note_guest_send(&mut self, parent: DetPid) {
self.window
.entry(parent)
.or_default()
.push(WindowSend::Guest);
}
pub(crate) fn unnote_guest_send(&mut self, parent: DetPid) {
if let Some(sends) = self.window.get_mut(&parent)
&& let Some(at) = sends.iter().rposition(|send| *send == WindowSend::Guest)
{
sends.remove(at);
}
}
pub(crate) fn window_open(&self, parent: DetPid) -> bool {
self.window
.get(&parent)
.is_some_and(|sends| !sends.is_empty())
}
fn settle_sends(&mut self, parent: DetPid, sends: &[WindowSend]) -> Option<ChildExitSiginfo> {
let mut oldest = None;
for child in sends.iter().filter_map(|send| match send {
WindowSend::Child(child) => Some(child),
_ => None,
}) {
let Some(state) = self.state(parent, *child).copied() else {
continue;
};
match state {
Notification::Sent(info) => {
oldest.get_or_insert(info);
*self.state(parent, *child).unwrap() = Notification::Delivered;
}
Notification::DeliveredWhileSent => self.forget(parent, *child),
_ => continue,
}
if let Some(order) = self.sent.get_mut(&parent) {
order.retain(|sent| sent != child);
}
}
self.tidy_sent(parent);
oldest
}
pub(crate) fn take_window(
&mut self,
parent: DetPid,
absorbed: Option<DetPid>,
) -> Option<Option<ChildExitSiginfo>> {
let sends = self
.window
.remove(&parent)
.filter(|sends| !sends.is_empty())?;
let deliver = self.settle_sends(parent, &sends);
let deliver = if matches!(
sends.first(),
Some(WindowSend::Guest | WindowSend::ParentDeath)
) {
None
} else {
deliver
};
if let Some(child) = absorbed
&& !sends.contains(&WindowSend::Child(child))
&& !self.cohorts.contains_key(&child)
&& matches!(self.state(parent, child), Some(Notification::Delivered))
{
self.forget(parent, child);
}
Some(deliver)
}
pub(crate) fn flush(&mut self, parent: DetPid) {
if let Some(sends) = self.window.remove(&parent) {
self.settle_sends(parent, &sends);
}
}
pub(crate) fn forget_window(&mut self, parent: DetPid) {
self.window.remove(&parent);
}
pub(crate) fn forget_process(&mut self, process: DetPid) {
self.forget_window(process);
self.outside_takers.remove(&process);
}
pub(crate) fn forget_parent(&mut self, parent: DetPid) {
if let Some(children) = self.owned.remove(&parent) {
for child in children.keys() {
self.cohorts.remove(child);
}
}
self.sent.remove(&parent);
}
pub(crate) fn settle_exit_grant(
&mut self,
thread: DetTid,
process: DetPid,
group: bool,
ends_process: bool,
) {
let raw = self.raw_exit_status.remove(&thread);
if ends_process
&& !group
&& let Some(raw) = raw
{
self.exit_status.insert(process, raw);
}
}
}
impl Scheduler {
pub(super) fn send_child_exit_sigchld(
&mut self,
parent: DetPid,
creator: DetTid,
child: DetPid,
) -> ChildExitSend {
match self.child_exit_sigchld.timer(parent, child) {
None => ChildExitSend::NotOwned,
Some(TimerSend::Nothing) => {
info!(
"[dpid {}] SIGCHLD for child {} was the kernel's, delivered before the timer.",
parent, child
);
ChildExitSend::Nothing
}
Some(TimerSend::Send) => {
let marked = self
.thread_tree
.pid_namespaces
.namespace_of(DetTid::from_raw(parent.as_raw()))
.is_some()
.then(|| marked_own_copy(std::process::id(), nix::unistd::getuid().as_raw()));
self.sending_child_exit = Some(child);
let receiver = self.fire_child_exit_alarm(parent, creator, marked);
self.sending_child_exit = None;
ChildExitSend::Sent(receiver)
}
}
}
pub(crate) fn child_exit_sigchld_control_for_receiver(
&mut self,
dtid: DetTid,
control: ChildExitSigchldControl,
) -> ChildExitSigchldAnswer {
let control = match control {
ChildExitSigchldControl::Taken {
code,
pid,
value,
admits,
} => ChildExitSigchldControl::Dequeue {
copy: copy_of(code, pid, value, std::process::id()),
admits,
},
other => other,
};
let Some(namespace) = self.thread_tree.pid_namespaces.namespace_of(dtid) else {
return self.child_exit_sigchld_control(dtid, control);
};
let control = match control {
ChildExitSigchldControl::ClaimKernelCopy { child } => {
match self
.thread_tree
.pid_namespaces
.resolve(Some(namespace), child.as_raw())
{
Some(task) => ChildExitSigchldControl::ClaimKernelCopy { child: task },
None => return ChildExitSigchldAnswer::Claimed(false),
}
}
ChildExitSigchldControl::Dequeue {
copy: DequeuedCopy::Kernel { child },
admits,
} => ChildExitSigchldControl::Dequeue {
copy: match self
.thread_tree
.pid_namespaces
.resolve(Some(namespace), child.as_raw())
{
Some(task) => DequeuedCopy::Kernel { child: task },
None => DequeuedCopy::Other,
},
admits,
},
other => other,
};
let localize = |scheduler: &Self, mut info: ChildExitSiginfo| {
if let Some(local) = scheduler
.thread_tree
.pid_namespaces
.localize(Some(namespace), DetTid::from_raw(info.pid))
{
info.pid = local;
}
info
};
match self.child_exit_sigchld_control(dtid, control) {
ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(info)) => {
ChildExitSigchldAnswer::OwnCopy(OwnCopy::Deliver(localize(self, info)))
}
ChildExitSigchldAnswer::ClaimedFor(info) => {
ChildExitSigchldAnswer::ClaimedFor(localize(self, info))
}
answer => answer,
}
}
pub(crate) fn child_exit_sigchld_control(
&mut self,
dtid: DetTid,
control: ChildExitSigchldControl,
) -> ChildExitSigchldAnswer {
match control {
ChildExitSigchldControl::ExitStatus { code, status, uid } => {
let process = self.sigchld_process(dtid);
self.child_exit_sigchld.exit_status.insert(
process,
ChildExitSiginfo {
code,
pid: process.as_raw(),
uid,
status,
},
);
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::ClaimKernelCopy { child } => {
self.claim_kernel_copy(dtid, child)
}
ChildExitSigchldControl::TakeOwnCopy => {
ChildExitSigchldAnswer::OwnCopy(self.take_own_copy(dtid))
}
ChildExitSigchldControl::Dequeue { copy, admits } => {
self.dequeue_sigchld(dtid, copy, admits)
}
ChildExitSigchldControl::Taken {
code,
pid,
value,
admits,
} => self.dequeue_sigchld(dtid, copy_of(code, pid, value, std::process::id()), admits),
ChildExitSigchldControl::Flushed => {
let parent = self.sigchld_process(dtid);
self.child_exit_sigchld.flush(parent);
let private = std::mem::take(&mut self.child_exit_sigchld.private_sent);
self.child_exit_sigchld.private_sent = private
.into_iter()
.filter(|thread| self.sigchld_process(*thread) != parent)
.collect();
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::PlacedPending => {
ChildExitSigchldAnswer::Placed(self.committed_sigchld_pending(dtid))
}
ChildExitSigchldControl::PrivatePending => {
ChildExitSigchldAnswer::Placed(self.private_sigchld(dtid) != 0)
}
ChildExitSigchldControl::ClaimedDelivery => {
self.blocked.sigchld_ready.insert(dtid);
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::WindowUnusable => ChildExitSigchldAnswer::Placed(
self.models_signal_targets
&& !self.sigchld_window_usable(self.sigchld_process(dtid))
&& !(self.recordreplay_modes && self.outside_call_may_take_sigchld(dtid)),
),
ChildExitSigchldControl::PrivateSent { target } => {
ChildExitSigchldAnswer::Placed(
self.models_signal_targets
&& self.child_exit_sigchld.private_sent.insert(target),
)
}
ChildExitSigchldControl::RawExitStatus { code, status, uid } => {
let process = self.sigchld_process(dtid);
self.child_exit_sigchld.raw_exit_status.insert(
dtid,
ChildExitSiginfo {
code,
pid: process.as_raw(),
uid,
status,
},
);
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::SendFailed { private, shared } => {
if let Some(target) = private {
self.child_exit_sigchld.private_sent.remove(&target);
}
if let Some(target) = shared {
self.child_exit_sigchld.unnote_guest_send(target);
}
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::SharedSent { target } => {
if self.models_signal_targets && self.sigchld_window_usable(target) {
self.child_exit_sigchld.note_guest_send(target);
}
ChildExitSigchldAnswer::Recorded
}
ChildExitSigchldControl::WaitFaulted {
private_pending,
shared_pending,
} => {
let parent = self.sigchld_process(dtid);
if self.child_exit_sigchld.private_sent.contains(&dtid) {
if !private_pending {
self.child_exit_sigchld.private_sent.remove(&dtid);
}
} else if !shared_pending && self.sigchld_window_usable(parent) {
self.child_exit_sigchld.take_window(parent, None);
}
ChildExitSigchldAnswer::Recorded
}
}
}
fn claim_kernel_copy(&mut self, dtid: DetTid, child: DetPid) -> ChildExitSigchldAnswer {
let parent = self.sigchld_process(dtid);
if !self.backend.reports_child_exit_publication
&& !self.child_exit_sigchld.cohorts.contains_key(&child)
&& let Some(info) = self.child_exit_sigchld.outstanding_info(parent, child)
{
if self.child_exit_sigchld.claim(parent, child) {
return ChildExitSigchldAnswer::Claimed(true);
}
return ChildExitSigchldAnswer::ClaimedFor(info);
}
if let Some(info) = self.child_exit_sigchld.claim_for_cohort(parent, child) {
debug!(
"[dtid {}] the kernel's SIGCHLD for child {} stands for child {}, its cohort's first",
dtid, child, info.pid
);
return ChildExitSigchldAnswer::ClaimedFor(info);
}
let claimed = self.child_exit_sigchld.claim(parent, child);
if claimed {
debug!(
"[dtid {}] dropping the kernel's SIGCHLD for child {}: one was delivered for that exit",
dtid, child
);
}
ChildExitSigchldAnswer::Claimed(claimed)
}
fn take_own_copy(&mut self, dtid: DetTid) -> OwnCopy {
let parent = self.sigchld_process(dtid);
let own = self.child_exit_sigchld.take_own(parent);
if own == OwnCopy::Duplicate {
debug!(
"[dtid {}] dropping the scheduler's SIGCHLD: the kernel's was delivered first",
dtid
);
}
own
}
fn dequeue_sigchld(
&mut self,
dtid: DetTid,
copy: DequeuedCopy,
admits: bool,
) -> ChildExitSigchldAnswer {
let parent = self.sigchld_process(dtid);
self.child_exit_sigchld.attributed.remove(&dtid);
if self.child_exit_sigchld.private_sent.remove(&dtid) {
if admits {
self.blocked.sigchld_ready.insert(dtid);
}
return ChildExitSigchldAnswer::Recorded;
}
let absorbed = match copy {
DequeuedCopy::Kernel { child } => Some(child),
_ => None,
};
if !self.sigchld_window_usable(parent) {
self.child_exit_sigchld.forget_window(parent);
}
if self.models_signal_targets
&& copy != DequeuedCopy::Thread
&& let Some(deliver) = self.child_exit_sigchld.take_window(parent, absorbed)
{
if admits {
self.blocked.sigchld_ready.insert(dtid);
self.child_exit_sigchld.attributed.insert(dtid);
}
return ChildExitSigchldAnswer::OwnCopy(match deliver {
Some(info) => OwnCopy::Deliver(info),
None => OwnCopy::Unowned,
});
}
let (answer, attributed) = match copy {
DequeuedCopy::Kernel { child } => {
let owned = self.child_exit_sigchld.owns(parent, child);
let answer = self.claim_kernel_copy(dtid, child);
let kept = !matches!(answer, ChildExitSigchldAnswer::Claimed(true));
(answer, owned && kept)
}
DequeuedCopy::Scheduler => {
let own = self.take_own_copy(dtid);
(
ChildExitSigchldAnswer::OwnCopy(own),
matches!(own, OwnCopy::Deliver(_)),
)
}
DequeuedCopy::Other | DequeuedCopy::Unknown | DequeuedCopy::Thread => {
(ChildExitSigchldAnswer::Recorded, false)
}
};
if admits && attributed {
self.child_exit_sigchld.attributed.insert(dtid);
}
answer
}
pub(crate) fn committed_sigchld_pending(&self, dtid: DetTid) -> bool {
if !self.models_signal_targets {
return true;
}
if self.child_exit_sigchld.private_sent.contains(&dtid)
&& !self.discarded_at_send.is_discarded(
super::discarded_at_send::QueueId::Thread(dtid),
libc::SIGCHLD,
)
{
return true;
}
let parent = self.sigchld_process(dtid);
self.child_exit_sigchld.window_open(parent) && self.sigchld_window_usable(parent)
}
pub(crate) fn sigchld_window_usable(&self, parent: DetPid) -> bool {
!self.child_exit_sigchld.outside_takers.contains(&parent)
}
pub(crate) fn note_outside_blocker(
&mut self,
thread: DetTid,
mask: Option<u64>,
descriptors: bool,
) {
let sigchld = super::kernel_signal_bit(libc::SIGCHLD);
let process = self.sigchld_process(thread);
let reads_signalfd = descriptors
&& self
.signalfd_masks
.get(&process)
.is_some_and(|mask| mask & sigchld != 0);
if self.models_signal_targets
&& (reads_signalfd || mask.is_none_or(|mask| mask & sigchld == 0))
&& self.child_exit_sigchld.outside_takers.insert(process)
{
debug!(
"[dtid {}] process {} no longer uses the SIGCHLD send window: a thread may take SIGCHLD outside the schedule",
thread, process
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const PARENT: DetPid = DetPid::from_raw(10);
const CHILD: DetPid = DetPid::from_raw(20);
fn exited(pid: i32, status: i32) -> ChildExitSiginfo {
ChildExitSiginfo {
code: libc::CLD_EXITED,
pid,
uid: 1000,
status,
}
}
fn owned_child() -> ChildExitSigchldLedger {
let mut ledger = ChildExitSigchldLedger::default();
ledger.exit_status.insert(CHILD, exited(CHILD.as_raw(), 3));
assert!(ledger.own(PARENT, CHILD));
ledger
}
#[test]
fn child_exit_siginfo_has_linuxs_layout() {
let bytes = exited(42, 7).to_bytes();
let info: libc::siginfo_t = unsafe { std::mem::transmute(bytes) };
assert_eq!(info.si_signo, libc::SIGCHLD);
assert_eq!(info.si_code, libc::CLD_EXITED);
unsafe {
assert_eq!(info.si_pid(), 42);
assert_eq!(info.si_uid(), 1000);
assert_eq!(info.si_status(), 7);
assert_eq!(info.si_utime(), 0);
assert_eq!(info.si_stime(), 0);
}
assert_eq!(siginfo_code_and_pid(&bytes), (libc::CLD_EXITED, 42));
}
#[test]
fn a_raw_exit_status_is_settled_at_its_grant() {
let leader = DetTid::from_raw(CHILD.as_raw());
let worker = DetTid::from_raw(21);
let raw = |ledger: &mut ChildExitSigchldLedger, thread: DetTid, status: i32| {
ledger
.raw_exit_status
.insert(thread, exited(CHILD.as_raw(), status));
};
let mut ledger = ChildExitSigchldLedger::default();
raw(&mut ledger, worker, 1);
ledger.exit_status.insert(CHILD, exited(CHILD.as_raw(), 2));
ledger.settle_exit_grant(worker, CHILD, false, false);
assert!(ledger.raw_exit_status.is_empty());
ledger.settle_exit_grant(leader, CHILD, true, true);
assert_eq!(
ledger.exit_status.get(&CHILD),
Some(&exited(CHILD.as_raw(), 2))
);
for last_by_group in [false, true] {
let mut ledger = ChildExitSigchldLedger::default();
raw(&mut ledger, leader, 4);
ledger.settle_exit_grant(leader, CHILD, false, false);
assert!(ledger.exit_status.is_empty());
assert!(ledger.raw_exit_status.is_empty());
if last_by_group {
ledger.exit_status.insert(CHILD, exited(CHILD.as_raw(), 5));
} else {
raw(&mut ledger, worker, 5);
}
ledger.settle_exit_grant(worker, CHILD, last_by_group, true);
assert_eq!(
ledger.exit_status.get(&CHILD),
Some(&exited(CHILD.as_raw(), 5)),
"exit_group: {last_by_group}"
);
}
let mut ledger = ChildExitSigchldLedger::default();
raw(&mut ledger, leader, 7);
ledger.settle_exit_grant(leader, CHILD, false, true);
assert_eq!(
ledger.exit_status.get(&CHILD),
Some(&exited(CHILD.as_raw(), 7))
);
assert!(ledger.own(PARENT, CHILD));
}
#[test]
fn a_child_is_owned_once_it_reported_its_status() {
let mut ledger = ChildExitSigchldLedger::default();
assert!(!ledger.own(PARENT, CHILD), "no status reported");
assert_eq!(ledger.timer(PARENT, CHILD), None);
let ledger = &mut owned_child();
assert!(
!ledger.claim(DetPid::from_raw(11), CHILD),
"another process"
);
assert!(!ledger.claim(PARENT, DetPid::from_raw(21)), "another child");
}
#[test]
fn a_cohorts_kernel_copy_stands_for_its_lowest_pid_whichever_it_names() {
let [first, second, alone] = [20, 21, 30].map(DetPid::from_raw);
let killed = |pid: DetPid| ChildExitSiginfo {
code: libc::CLD_KILLED,
pid: pid.as_raw(),
uid: 1000,
status: libc::SIGKILL,
};
let outcome = |named: DetPid| {
let mut ledger = ChildExitSigchldLedger::default();
for child in [first, second, alone] {
ledger.exit_status.insert(child, killed(child));
assert!(ledger.own(PARENT, child));
}
ledger.join_cohort(first, 7);
ledger.join_cohort(second, 7);
assert_eq!(ledger.claim_for_cohort(PARENT, alone), None);
let kernel = ledger.claim_for_cohort(PARENT, named);
let timers = [first, second].map(|child| ledger.timer(PARENT, child));
(kernel, timers, ledger.take_own(PARENT))
};
let expected = (
Some(killed(first)),
[Some(TimerSend::Nothing), Some(TimerSend::Send)],
OwnCopy::Deliver(killed(second)),
);
assert_eq!(outcome(first), expected);
assert_eq!(outcome(second), expected);
}
#[test]
fn the_schedulers_copy_first_drops_the_kernels() {
let ledger = &mut owned_child();
assert_eq!(ledger.timer(PARENT, CHILD), Some(TimerSend::Send));
assert_eq!(ledger.take_own(PARENT), OwnCopy::Deliver(exited(20, 3)));
assert!(ledger.claim(PARENT, CHILD), "the kernel's copy is dropped");
assert!(!ledger.claim(PARENT, CHILD), "dropped once");
assert_eq!(ledger.take_own(PARENT), OwnCopy::Unowned);
assert!(ledger.owned.is_empty() && ledger.sent.is_empty());
}
#[test]
fn the_kernels_copy_first_drops_the_schedulers() {
let ledger = &mut owned_child();
assert_eq!(ledger.timer(PARENT, CHILD), Some(TimerSend::Send));
assert!(
!ledger.claim(PARENT, CHILD),
"the kernel's copy is delivered"
);
assert_eq!(ledger.take_own(PARENT), OwnCopy::Duplicate);
assert!(ledger.owned.is_empty() && ledger.sent.is_empty());
}
#[test]
fn the_kernels_copy_before_the_timer_means_no_send() {
let ledger = &mut owned_child();
assert!(!ledger.claim(PARENT, CHILD));
assert_eq!(ledger.timer(PARENT, CHILD), Some(TimerSend::Nothing));
assert_eq!(ledger.timer(PARENT, CHILD), None);
assert!(ledger.owned.is_empty());
}
#[test]
fn a_committed_deferred_delivery_stands_for_the_exit() {
let ledger = &mut owned_child();
ledger.stand_in(PARENT, CHILD);
assert!(ledger.claim(PARENT, CHILD));
}
#[test]
fn a_schedulers_copy_stands_for_an_undelivered_exit_first() {
let first = DetPid::from_raw(20);
let second = DetPid::from_raw(21);
let mut ledger = ChildExitSigchldLedger::default();
for child in [first, second] {
ledger.exit_status.insert(child, exited(child.as_raw(), 1));
assert!(ledger.own(PARENT, child));
assert_eq!(ledger.timer(PARENT, child), Some(TimerSend::Send));
}
assert!(
!ledger.claim(PARENT, first),
"the first child's kernel copy"
);
assert_eq!(ledger.take_own(PARENT), OwnCopy::Deliver(exited(21, 1)));
assert_eq!(ledger.take_own(PARENT), OwnCopy::Duplicate);
assert_eq!(ledger.take_own(PARENT), OwnCopy::Unowned);
}
#[test]
fn a_sigchlds_kind_is_told_by_its_code_and_sender() {
let siginfo = |code: i32, pid: i32| {
let mut bytes = [0u8; 128];
bytes[0..4].copy_from_slice(&libc::SIGCHLD.to_ne_bytes());
bytes[8..12].copy_from_slice(&code.to_ne_bytes());
bytes[16..20].copy_from_slice(&pid.to_ne_bytes());
bytes
};
let tracer = 1;
let dequeue = |copy, admits| Some(ChildExitSigchldControl::Dequeue { copy, admits });
assert_eq!(
control_for(&siginfo(libc::CLD_KILLED, 20), tracer, true),
dequeue(DequeuedCopy::Kernel { child: CHILD }, true)
);
assert_eq!(
control_for(&siginfo(libc::SI_USER, 1), tracer, false),
dequeue(DequeuedCopy::Scheduler, false)
);
for code in [libc::SI_USER, libc::SI_QUEUE] {
assert_eq!(
control_for(&siginfo(code, 30), tracer, true),
dequeue(DequeuedCopy::Other, true)
);
}
assert_eq!(
control_for(&siginfo(libc::CLD_STOPPED, 20), tracer, true),
dequeue(DequeuedCopy::Other, true)
);
assert_eq!(
control_for(&siginfo(libc::SI_TKILL, 1), tracer, true),
dequeue(DequeuedCopy::Thread, true)
);
for (code, pid) in [
(libc::CLD_KILLED, 20),
(libc::SI_USER, 1),
(libc::SI_USER, 30),
(libc::SI_TKILL, 1),
] {
let info = siginfo(code, pid);
let ChildExitSigchldControl::Taken {
code: taken_code,
pid: taken_pid,
value,
admits,
} = taken_control(&info, true)
else {
panic!("not a taken copy");
};
assert_eq!((taken_code, taken_pid, value, admits), (code, pid, 0, true));
assert_eq!(
Some(copy_of(taken_code, taken_pid, value, tracer)),
dequeued_copy(&info, tracer)
);
}
}
#[test]
fn a_nested_receivers_own_copy_is_told_by_its_mark() {
let tracer = 1;
let mut marked = marked_own_copy(tracer, 0);
marked[16..20].copy_from_slice(&0i32.to_ne_bytes());
assert_eq!(
dequeued_copy(&marked, tracer),
Some(DequeuedCopy::Scheduler)
);
let mut unmarked = marked;
unmarked[24..28].copy_from_slice(&7i32.to_ne_bytes());
assert_eq!(dequeued_copy(&unmarked, tracer), Some(DequeuedCopy::Other));
let mut with_pid = marked;
with_pid[16..20].copy_from_slice(&30i32.to_ne_bytes());
assert_eq!(dequeued_copy(&with_pid, tracer), Some(DequeuedCopy::Other));
let mut ancestor = [0u8; 128];
ancestor[0..4].copy_from_slice(&libc::SIGCHLD.to_ne_bytes());
ancestor[8..12].copy_from_slice(&libc::SI_USER.to_ne_bytes());
assert_eq!(dequeued_copy(&ancestor, tracer), Some(DequeuedCopy::Other));
}
#[test]
fn only_exit_codes_are_child_exits() {
for code in [libc::CLD_EXITED, libc::CLD_KILLED, libc::CLD_DUMPED] {
assert!(is_child_exit_code(code));
}
for code in [
libc::CLD_TRAPPED,
libc::CLD_STOPPED,
libc::CLD_CONTINUED,
libc::SI_TKILL,
libc::SI_USER,
libc::SI_QUEUE,
] {
assert!(!is_child_exit_code(code));
}
}
}