use std::io;
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use super::*;
#[cfg(target_os = "linux")]
pub(super) const REPORT_PLACED: i32 = -1;
#[cfg(target_os = "linux")]
const MESSAGE_LEN: usize = 8;
#[cfg(target_os = "linux")]
pub(super) const TAG_INTENT: i32 = 1;
#[cfg(target_os = "linux")]
const TAG_REPORT: i32 = 2;
#[cfg(target_os = "linux")]
const PROCEED: u8 = b'P';
#[cfg(target_os = "linux")]
pub(crate) struct ReportChannel {
pub(super) read: OwnedFd,
pub(super) write: Option<OwnedFd>,
received: Received,
}
#[cfg(target_os = "linux")]
#[derive(Debug, Default)]
pub(crate) struct Received {
pub(crate) report: Option<PlacementReport>,
pub(crate) pid: Option<u32>,
}
#[cfg(target_os = "linux")]
impl Received {
pub(crate) fn placement(&self) -> PlacementReport {
self.report.unwrap_or(PlacementReport::NotReported)
}
}
#[cfg(target_os = "linux")]
impl ReportChannel {
pub(crate) fn new() -> io::Result<ReportChannel> {
use rustix::net::{socketpair, AddressFamily, SocketFlags, SocketType};
#[cfg(test)]
if fault::take_force_report_channel_failure() {
return Err(io::Error::from_raw_os_error(libc::EMFILE));
}
let (read, write) = socketpair(AddressFamily::UNIX, SocketType::SEQPACKET, SocketFlags::CLOEXEC, None)?;
Ok(ReportChannel {
read: crate::above_stdio::above_stdio(read)?,
write: Some(crate::above_stdio::above_stdio(write)?),
received: Received::default(),
})
}
#[cfg(test)]
pub(crate) fn dup_child_end_for_test(&self) -> std::os::fd::OwnedFd {
self.write
.as_ref()
.expect("the child's end is open until the wait")
.try_clone()
.expect("dup the child's end")
}
pub(crate) fn slot(&self) -> ReportSlot {
ReportSlot {
fd: self
.write
.as_ref()
.expect("the child's end is open until the wait")
.as_raw_fd(),
parent_fd: self.read.as_raw_fd(),
}
}
pub(crate) fn wait(&mut self, pidfd: std::os::fd::BorrowedFd<'_>) -> PlacementReport {
use rustix::event::{PollFd, PollFlags};
self.write = None;
#[cfg(test)]
fault::notify_wait_entry(std::os::fd::AsRawFd::as_raw_fd(&pidfd));
loop {
let closed = self.drain();
if let Some(report) = self.received.report {
return report;
}
if closed {
return PlacementReport::NotReported;
}
let mut fds = [
PollFd::new(&self.read, PollFlags::IN),
PollFd::new(&pidfd, PollFlags::IN),
];
#[cfg(test)]
fault::notify_wait_polling();
if let Err(e) = crate::wait::poll_ready(&mut fds) {
panic!("poll on the placement report channel failed: {e}");
}
if !fds[1].revents().is_empty() {
self.drain();
return self.received.placement();
}
}
}
fn drain(&mut self) -> bool {
use rustix::net::{recv, RecvFlags};
loop {
let mut message = [0u8; MESSAGE_LEN];
let bytes = match recv(&self.read, &mut message, RecvFlags::DONTWAIT) {
Ok((bytes, _)) => bytes,
Err(rustix::io::Errno::INTR | rustix::io::Errno::NOMEM) => continue,
Err(rustix::io::Errno::AGAIN) => return false,
Err(e) => panic!("recvmsg on the placement report channel failed: {e}"),
};
if bytes == 0 {
return true;
}
debug_assert_eq!(bytes, message.len(), "a message is two i32s");
let tag = i32::from_ne_bytes(message[..4].try_into().expect("four bytes"));
let value = i32::from_ne_bytes(message[4..].try_into().expect("four bytes"));
match tag {
TAG_INTENT => self.received.pid = u32::try_from(value).ok(),
TAG_REPORT => {
self.received.report.get_or_insert(match value {
REPORT_PLACED => PlacementReport::Placed,
errno => {
debug_assert!(errno > 0, "a failed write reports its positive errno, got {errno}");
PlacementReport::WriteFailed(errno)
}
});
}
tag => debug_assert!(false, "unknown placement message tag {tag}"),
}
}
}
pub(super) fn proceed(mut self) {
self.drain();
_ = rustix::net::send(
&self.read,
&[PROCEED],
rustix::net::SendFlags::NOSIGNAL | rustix::net::SendFlags::DONTWAIT,
);
}
pub(super) fn shut(mut self) -> Received {
self.write = None;
rustix::net::shutdown(&self.read, rustix::net::Shutdown::Read)
.expect("shut the placement report channel for reading");
self.drain();
#[cfg(test)]
fault::run_after_shut_read();
self.received
}
}
#[cfg(all(target_os = "linux", test))]
impl ReportChannel {
pub(crate) fn report_for_test(mut self) -> PlacementReport {
self.write = None;
self.drain();
self.received.placement()
}
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Delivery {
Queued,
Decided,
Abandoned,
}
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
pub(crate) struct ReportSlot {
pub(super) fd: RawFd,
pub(super) parent_fd: RawFd,
}
#[cfg(target_os = "linux")]
impl ReportSlot {
pub(super) unsafe fn send_intent(self) -> io::Result<Delivery> {
let pid = rustix::process::getpid();
unsafe { self.send(TAG_INTENT, pid.as_raw_nonzero().get()) }
}
pub(crate) unsafe fn close_parents_end(self) {
unsafe { libc::close(self.parent_fd) };
}
pub(super) unsafe fn send_report(self, value: i32) -> io::Result<Delivery> {
unsafe { self.send(TAG_REPORT, value) }
}
pub(super) unsafe fn send(self, tag: i32, value: i32) -> io::Result<Delivery> {
let mut message = [0u8; MESSAGE_LEN];
message[..4].copy_from_slice(&tag.to_ne_bytes());
message[4..].copy_from_slice(&value.to_ne_bytes());
loop {
let sent = unsafe { libc::send(self.fd, message.as_ptr().cast(), message.len(), libc::MSG_NOSIGNAL) };
if sent == message.len() as isize {
return Ok(Delivery::Queued);
}
let errno = unsafe { *libc::__errno_location() };
return match (sent, errno) {
(-1, libc::EINTR) => continue,
(-1, libc::EPIPE | libc::ECONNRESET) => Ok(if unsafe { self.proceed_queued() } {
Delivery::Decided
} else {
Delivery::Abandoned
}),
(-1, errno) => Err(io::Error::from_raw_os_error(errno)),
_ => Err(io::Error::from_raw_os_error(libc::EMSGSIZE)),
};
}
}
unsafe fn proceed_queued(self) -> bool {
let mut byte = 0u8;
loop {
let got = unsafe { libc::recv(self.fd, (&raw mut byte).cast(), 1, libc::MSG_DONTWAIT) };
if got == -1 && unsafe { *libc::__errno_location() } == libc::EINTR {
continue;
}
return got == 1 && byte == PROCEED;
}
}
}
#[cfg(all(target_os = "linux", test))]
impl ReportSlot {
pub(crate) unsafe fn report_placed_for_test(self) {
let sent = unsafe { self.send_report(REPORT_PLACED) }.expect("send the report");
assert_eq!(sent, Delivery::Queued, "the parent must still be listening");
}
}
#[cfg(test)]
#[path = "channel_tests.rs"]
mod channel_tests;