Truly independent web browser
LibIPC: Port the shared Mach IO thread to the Rust transport
Aliaksandr Kalenik4a640cb311fe
diff --git a/Libraries/LibIPC/Rust/build.rs b/Libraries/LibIPC/Rust/build.rsnew file mode 100644index 00000000000..a19861a3d28--- /dev/null+++ b/Libraries/LibIPC/Rust/build.rs@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::env;++fn main() {+ println!("cargo:rerun-if-changed=build.rs");++ // NB: A CMake build of the shared target directory links what it builds into libraries that link AK. Unit tests+ // link without it.+ println!("cargo::rustc-check-cfg=cfg(ladybird_links_ak)");+ println!("cargo:rerun-if-env-changed=LADYBIRD_LINKS_AK");+ if env::var_os("LADYBIRD_LINKS_AK").is_some() {+ println!("cargo::rustc-cfg=ladybird_links_ak");+ }+}diff --git a/Libraries/LibIPC/Rust/src/mach.rs b/Libraries/LibIPC/Rust/src/mach.rsindex abd570b5175..6272d13a4c8 100644--- a/Libraries/LibIPC/Rust/src/mach.rs+++ b/Libraries/LibIPC/Rust/src/mach.rs@@ -38,11 +38,14 @@ pub const MACH_MSG_VIRTUAL_COPY: u8 = 1;pub const MACH_SEND_MSG: i32 = 0x1;pub const MACH_RCV_MSG: i32 = 0x2;pub const MACH_RCV_LARGE: i32 = 0x4;+// NB: With MACH_RCV_LARGE, a message too large for the buffer names the port it waits on, which a receive on a port set+// needs to take that message rather than another port's.+const MACH_RCV_LARGE_IDENTITY: i32 = 0x8;pub const MACH_SEND_TIMEOUT: i32 = 0x10;pub const MACH_RCV_TIMEOUT: i32 = 0x100;pub const MACH_MSG_SUCCESS: KernReturn = 0;-const MACH_MSG_MASK: KernReturn = 0x0000_3e00;+pub(crate) const MACH_MSG_MASK: KernReturn = 0x0000_3e00;const MACH_SEND_INVALID_DATA: KernReturn = 0x1000_0002;pub const MACH_SEND_INVALID_DEST: KernReturn = 0x1000_0003;pub const MACH_SEND_TIMED_OUT: KernReturn = 0x1000_0004;@@ -63,15 +66,22 @@ const MACH_SEND_NO_GRANT_DEST: KernReturn = 0x1000_0016;const MACH_SEND_MSG_FILTERED: KernReturn = 0x1000_0017;const MACH_RCV_TIMED_OUT: KernReturn = 0x1000_4003;pub const MACH_RCV_TOO_LARGE: KernReturn = 0x1000_4004;+pub const MACH_RCV_HEADER_ERROR: KernReturn = 0x1000_400b;+pub const MACH_RCV_BODY_ERROR: KernReturn = 0x1000_400c;pub const MACH_MSG_TIMEOUT_NONE: u32 = 0;+pub const MACH_NOTIFY_SEND_POSSIBLE: i32 = 0o102;pub const MACH_NOTIFY_NO_SENDERS: i32 = 0o106;pub const MACH_NOTIFY_SEND_ONCE: i32 = 0o107;+pub const MACH_NOTIFY_DEAD_NAME: i32 = 0o110;const MACH_PORT_RIGHT_RECEIVE: u32 = 1;const MACH_PORT_RIGHT_PORT_SET: u32 = 3;+pub const MACH_PORT_TYPE_DNREQUEST: u32 = 0x8000_0000;+pub const MACH_PORT_TYPE_SPREQUEST: u32 = 0x4000_0000;+const MACH_PORT_LIMITS_INFO: i32 = 1;const MACH_PORT_LIMITS_INFO_COUNT: u32 = 1;pub(crate) const MACH_PORT_QLIMIT_MAX: i32 = 1024;@@ -87,7 +97,6 @@ pub fn is_valid(name: PortName) -> bool {/// `mach_msg_trailer_t`, which the kernel appends to every received message.pub const TRAILER_SIZE: usize = 8;pub const DEFAULT_RECEIVE_BUFFER_SIZE: usize = 65536;-const MAX_RETAINED_RECEIVE_BUFFER_SIZE: usize = 1024 * 1024;unsafe extern "C" {static mach_task_self_: PortName;@@ -119,6 +128,14 @@ unsafe extern "C" {previous: *mut PortName,) -> KernReturn;fn mach_port_set_attributes(task: PortName, name: PortName, flavor: i32, info: *mut i32, count: u32) -> KernReturn;+ fn mach_port_extract_right(+ task: PortName,+ name: PortName,+ right_type: u32,+ right: *mut PortName,+ acquired_type: *mut u32,+ ) -> KernReturn;+ fn mach_port_type(task: PortName, name: PortName, port_type: *mut u32) -> KernReturn;fn vm_deallocate(task: PortName, address: usize, size: usize) -> KernReturn;fn mach_error_string(error: KernReturn) -> *const c_char;fn fileport_makeport(fd: c_int, port: *mut PortName) -> c_int;@@ -157,6 +174,14 @@ impl From<KernelError> for std::io::Error {}}+/// The time on `CLOCK_MONOTONIC`, which AK's `MonotonicTime` reads, and which keeps counting while the system sleeps.+pub fn clock_monotonic_nanoseconds() -> i64 {+ let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0 };+ // NB: now points to a local that the call writes to, and the clock always exists.+ unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut now) };+ now.tv_sec * 1_000_000_000 + now.tv_nsec+}+/// Runs the calling thread at the user-interactive quality of service, as `Threading::Thread::set_qos()` does.pub fn set_current_thread_qos_to_user_interactive() {// NB: The call only changes how the calling thread is scheduled. A thread that keeps its default quality of@@ -247,6 +272,17 @@ impl MachPort {Ok(())}+ /// Takes a member out of this port set by its name, for an owner that no longer holds the member's right here.+ pub fn extract_member_named(&self, member: PortName) -> Result<(), KernReturn> {+ assert_eq!(self.right, PortRight::PortSet);+ // NB: Both are names in this task; a name that is not a member fails without effect.+ let result = unsafe { mach_port_extract_member(task_self(), member, self.name) };+ if result != KERN_SUCCESS {+ return Err(result);+ }+ Ok(())+ }+/// Raises the number of messages the port queues, so that a peer can send a burst before this side reads it.pub fn raise_queue_limit(&self) {assert_eq!(self.right, PortRight::Receive);@@ -288,6 +324,125 @@ impl MachPort {}Ok(())}++ /// Takes back the request for `MACH_NOTIFY_NO_SENDERS`, before the receive right goes to another owner.+ pub fn cancel_no_senders_notification(&self) -> Result<(), KernReturn> {+ assert_eq!(self.right, PortRight::Receive);+ let previous =+ self.request_notification(MACH_NOTIFY_NO_SENDERS, 0, MACH_PORT_NULL, MACH_MSG_TYPE_MAKE_SEND_ONCE)?;+ drop(previous);+ Ok(())+ }++ /// Makes a send-once right to the port this receive right is for. A message sent through it bypasses the queue+ /// limit, and doesn't count as a sender for `MACH_NOTIFY_NO_SENDERS`.+ pub fn make_send_once_right(&self) -> Result<Self, KernReturn> {+ assert_eq!(self.right, PortRight::Receive);+ make_send_once_right_from_receive_right_named(self.name)+ }+}++/// As `MachPort::make_send_once_right()`, for a receive right that something else owns, and keeps while this runs.+pub fn make_send_once_right_from_receive_right_named(receive_right: PortName) -> Result<MachPort, KernReturn> {+ let mut name = MACH_PORT_NULL;+ let mut acquired_type = 0;+ // NB: name and acquired_type point to locals that the call writes to.+ let result = unsafe {+ mach_port_extract_right(+ task_self(),+ receive_right,+ MACH_MSG_TYPE_MAKE_SEND_ONCE,+ &raw mut name,+ &raw mut acquired_type,+ )+ };+ if result != KERN_SUCCESS {+ return Err(result);+ }+ Ok(MachPort::adopt(name, PortRight::SendOnce))+}++impl MachPort {+ /// The `MACH_PORT_TYPE_*` bits of this name in this task, which include the notification requests made on it.+ pub fn port_type(&self) -> Result<u32, KernReturn> {+ let mut port_type = 0;+ // NB: port_type points to a local that the call writes to.+ let result = unsafe { mach_port_type(task_self(), self.name, &raw mut port_type) };+ if result != KERN_SUCCESS {+ return Err(result);+ }+ Ok(port_type)+ }++ /// Asks for `MACH_NOTIFY_SEND_POSSIBLE` on `notify_port` once the queue of the port this send right is for has+ /// room, or at once if it has room already. A port that dies answers with `MACH_NOTIFY_DEAD_NAME` instead.+ ///+ /// Gives back the send-once right of a request on this name that this one replaced.+ pub fn request_send_possible_notification(&self, notify_port: &MachPort) -> Result<Option<Self>, KernReturn> {+ assert_eq!(notify_port.right, PortRight::Receive);+ self.request_notification(+ MACH_NOTIFY_SEND_POSSIBLE,+ 1,+ notify_port.name,+ MACH_MSG_TYPE_MAKE_SEND_ONCE,+ )+ }++ /// Takes back a request for `MACH_NOTIFY_SEND_POSSIBLE`, and answers whether it was still armed. One that was not+ /// has fired or is firing, so its notification is on its way.+ pub fn cancel_send_possible_notification(&self) -> bool {+ matches!(+ self.request_notification(+ MACH_NOTIFY_SEND_POSSIBLE,+ 0,+ MACH_PORT_NULL,+ MACH_MSG_TYPE_MAKE_SEND_ONCE+ ),+ Ok(Some(_))+ )+ }++ /// Puts back a dead-name request that a send-possible request replaced, with the send-once right it gave back.+ pub fn restore_dead_name_notification(&self, notify_right: Self) {+ assert_eq!(notify_right.right, PortRight::SendOnce);+ let notify_right = std::mem::ManuallyDrop::new(notify_right);+ match self.request_notification(+ MACH_NOTIFY_DEAD_NAME,+ 1,+ notify_right.name,+ MACH_MSG_TYPE_MOVE_SEND_ONCE,+ ) {+ // NB: The kernel took the send-once right, and gave back the one this request replaced, if any.+ Ok(replaced) => drop(replaced),+ Err(_) => drop(std::mem::ManuallyDrop::into_inner(notify_right)),+ }+ }++ fn request_notification(+ &self,+ message_id: i32,+ sync: u32,+ notify: PortName,+ notify_type: u32,+ ) -> Result<Option<Self>, KernReturn> {+ let mut previous = MACH_PORT_NULL;+ // NB: previous points to a local that the call writes to.+ let result = unsafe {+ mach_port_request_notification(+ task_self(),+ self.name,+ message_id,+ sync,+ notify,+ notify_type,+ &raw mut previous,+ )+ };+ if result != KERN_SUCCESS {+ return Err(result);+ }+ Ok(is_valid(previous).then(|| Self::adopt(previous, PortRight::SendOnce)))+ }}impl Drop for MachPort {@@ -339,10 +494,25 @@ pub fn fd_from_file_port(port: MachPort) -> Result<OwnedFd, std::io::Error> {Ok(descriptor)}+/// Has writes to a pipe or socket whose reader is gone fail with `EPIPE` instead of raising `SIGPIPE`, which the+/// process does not ignore.+pub fn disable_sigpipe_on_writes(fd: &OwnedFd) -> Result<(), std::io::Error> {+ // NB: As <sys/fcntl.h> numbers it.+ const F_SETNOSIGPIPE: c_int = 73;+ // NB: fd is open, and the call only sets a flag on it.+ if unsafe { libc::fcntl(fd.as_raw_fd(), F_SETNOSIGPIPE, 1) } < 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+}+pub const IPC_DATA_MESSAGE_ID: i32 = 0x4950_C001;pub const IPC_INLINE_DATA_MESSAGE_ID: i32 = 0x4950_C002;pub const IPC_WAKEUP_MESSAGE_ID: i32 = 0x4950_C003;pub const IPC_RECEIVE_BARRIER_MESSAGE_ID: i32 = 0x4950_C004;+/// What a transport sends to its own receive right once it finds the peer unreachable, so that the peer's departure+/// shows after every message that the peer sent before.+pub const IPC_PEER_UNREACHABLE_MESSAGE_ID: i32 = 0x4950_C005;// NB: The largest message that carries its payload inline; a larger payload goes out of line.const INLINE_MESSAGE_MAX_SIZE: usize = 4096;@@ -375,9 +545,15 @@ impl MessageBuffer {}}- fn release_excess_capacity(&mut self) {- if self.words.capacity() * 8 > MAX_RETAINED_RECEIVE_BUFFER_SIZE {- *self = Self::new(MAX_RETAINED_RECEIVE_BUFFER_SIZE);+ fn size(&self) -> usize {+ self.words.len() * 8+ }++ // NB: A receive buffer lives as long as its thread, so it does not keep the size of the largest message a peer+ // sent.+ fn shrink_after_large_message(&mut self) {+ if self.size() > DEFAULT_RECEIVE_BUFFER_SIZE {+ *self = Self::new(DEFAULT_RECEIVE_BUFFER_SIZE);}}@@ -449,30 +625,172 @@ pub fn send_header_only_message(destination: &MachPort, id: i32, timeout: Optionresult}-/// Sends LibIPC's data message through a send right this task keeps, moving the rights of the attachments with it.+/// Sends a header-only message through a send-once right, which the message uses up. It waits for nothing, as a+/// send-once right bypasses the queue limit.+pub fn send_header_only_message_through_send_once_right(destination: MachPort, id: i32) -> KernReturn {+ assert_eq!(destination.right(), PortRight::SendOnce);+ let mut buffer = [0u32; HEADER_SIZE / size_of::<u32>()];+ // NB: All words are initialized and u8 alignment covers the entire slice.+ let bytes = unsafe { buffer.align_to_mut::<u8>().1 };+ write_header(+ bytes,+ msgh_bits(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0),+ HEADER_SIZE,+ destination.name(),+ id,+ );+ // NB: The buffer holds a header-only message that moves the send-once right, and outlives the call.+ let result = unsafe {+ mach_msg(+ buffer.as_mut_ptr().cast(),+ MACH_SEND_MSG,+ HEADER_SIZE as u32,+ 0,+ MACH_PORT_NULL,+ MACH_MSG_TIMEOUT_NONE,+ MACH_PORT_NULL,+ )+ };+ if result == MACH_MSG_SUCCESS {+ // NB: The message took the right.+ std::mem::forget(destination);+ }+ result+}++/// What became of a data message that was given to the kernel without waiting for room in its destination's queue.+pub enum SendOutcome {+ Sent,+ /// The destination's queue is full. The message keeps what it carries, to be sent again.+ WouldBlock(PendingMessage),+ /// The message is gone with what it carried, for the reason the kernel gave.+ Failed(KernReturn),+}++/// The bytes of a message that waits to be sent, which it owns, wherever they are.+pub type OwnedPayload = Box<dyn AsRef<[u8]> + Send>;++/// A data message that waits for room in its destination's queue, to be sent in its turn.+pub struct PendingMessage(PendingMessageContents);++enum PendingMessageContents {+ /// Posted behind other messages that wait, and not given to the kernel yet.+ Unsent {+ payload: OwnedPayload,+ ports: Vec<(MachPort, u32)>,+ },+ /// Given to the kernel once already, and handed back.+ Returned(ReturnedMessage),+}++impl PendingMessage {+ pub fn unsent(payload: OwnedPayload, ports: Vec<(MachPort, u32)>) -> Self {+ Self(PendingMessageContents::Unsent { payload, ports })+ }++ /// Tries to send the message without waiting for room, with the buffer as scratch space as `send_data_message()`+ /// takes it.+ pub fn try_send(self, buffer: &mut MessageBuffer, destination: &MachPort) -> SendOutcome {+ match self.0 {+ PendingMessageContents::Unsent { payload, ports } => {+ send_data_message(buffer, destination, (*payload).as_ref(), ports)+ }+ PendingMessageContents::Returned(message) => message.try_send_with(send_without_waiting),+ }+ }+}++/// A data message whose destination's queue was full, as the kernel handed it back: pseudo-received, with the rights+/// it carries under the names they have now, a send right of its own on the destination, and a mapping of its own of+/// an out-of-line payload. It is sent again as it is, and dropping it gives all of that back.+struct ReturnedMessage {+ buffer: MessageBuffer,+ // NB: Zero once the kernel has taken the message, or taken it apart.+ size: usize,+}++impl ReturnedMessage {+ fn try_send_with(mut self, send: impl FnOnce(&mut MessageBuffer, usize) -> KernReturn) -> SendOutcome {+ let result = send(&mut self.buffer, self.size);+ match classify_send_attempt(result) {+ SendAttempt::Sent => {+ self.size = 0;+ SendOutcome::Sent+ }+ SendAttempt::QueueFull => SendOutcome::WouldBlock(PendingMessage(PendingMessageContents::Returned(self))),+ SendAttempt::FailedWithMessageBack => SendOutcome::Failed(result),+ SendAttempt::FailedWithMessageConsumed => {+ self.size = 0;+ SendOutcome::Failed(result)+ }+ }+ }+}++impl Drop for ReturnedMessage {+ fn drop(&mut self) {+ if self.size == 0 {+ return;+ }+ // NB: This message owns everything it carries, including the mapping of an out-of-line payload.+ unsafe { mach_msg_destroy(self.buffer.header_pointer()) };+ }+}++enum SendAttempt {+ Sent,+ QueueFull,+ /// The kernel handed the message back, maybe only in part, and whatever came back is ours to release.+ FailedWithMessageBack,+ /// The kernel took the message apart, and nothing in it is ours any more.+ FailedWithMessageConsumed,+}++fn classify_send_attempt(result: KernReturn) -> SendAttempt {+ if result == MACH_MSG_SUCCESS {+ return SendAttempt::Sent;+ }+ // NB: A send that times out comes back pseudo-received. When the kernel can't hand all of it back, that shows as+ // extra bits on the timeout, or as a body error, and the message can't go out whole any more.+ if result == MACH_SEND_TIMED_OUT {+ return SendAttempt::QueueFull;+ }+ let error = result & !MACH_MSG_MASK;+ if error == MACH_SEND_TIMED_OUT || error == MACH_RCV_BODY_ERROR || send_error_leaves_descriptors_untouched(result) {+ return SendAttempt::FailedWithMessageBack;+ }+ // NB: Body copyin errors can destroy a prefix of the descriptors without saying how long, so none of the names+ // in the message may be released here.+ SendAttempt::FailedWithMessageConsumed+}++fn send_without_waiting(buffer: &mut MessageBuffer, size: usize) -> KernReturn {+ // NB: The buffer holds a message of size bytes that owns what it moves, and outlives the call.+ unsafe {+ mach_msg(+ buffer.header_pointer(),+ MACH_SEND_MSG | MACH_SEND_TIMEOUT,+ size as u32,+ 0,+ MACH_PORT_NULL,+ 0,+ MACH_PORT_NULL,+ )+ }+}++/// Gives LibIPC's data message to the kernel through a send right this task keeps, moving the rights of the+/// attachments with it, without waiting for room in the destination's queue.///-/// A payload that fits goes inline after a 32-bit size; a larger one goes out of line, as `TransportMachPort` sends it.+/// A payload that fits goes inline after a 32-bit size; a larger one goes out of line, borrowed for the call, as+/// `TransportMachPort` sends it. The buffer is scratch space that a message which has to wait is copied out of.pub fn send_data_message(buffer: &mut MessageBuffer,destination: &MachPort,payload: &[u8],ports: Vec<(MachPort, u32)>,- should_retry: impl FnMut() -> bool,-) -> KernReturn {- send_data_message_with(buffer, destination, payload, ports, should_retry, |buffer, size| {- // NB: The buffer owns its moved rights and borrows the original payload until a timeout returns a mapping.- unsafe {- mach_msg(- buffer.header_pointer(),- MACH_SEND_MSG | MACH_SEND_TIMEOUT,- size as u32,- 0,- MACH_PORT_NULL,- 100,- MACH_PORT_NULL,- )- }- })+) -> SendOutcome {+ send_data_message_with(buffer, destination, payload, ports, send_without_waiting)}fn send_data_message_with(@@ -480,11 +798,10 @@ fn send_data_message_with(destination: &MachPort,payload: &[u8],mut ports: Vec<(MachPort, u32)>,- mut should_retry: impl FnMut() -> bool,- mut send: impl FnMut(&mut MessageBuffer, usize) -> KernReturn,-) -> KernReturn {- if payload.len() > crate::MAX_MESSAGE_PAYLOAD_SIZE || ports.len() > crate::MAX_MESSAGE_ATTACHMENT_COUNT {- return MACH_SEND_TOO_LARGE;+ send: impl FnOnce(&mut MessageBuffer, usize) -> KernReturn,+) -> SendOutcome {+ if payload.len() > crate::MAX_MESSAGE_PAYLOAD_SIZE {+ return SendOutcome::Failed(MACH_SEND_TOO_LARGE);}if ports.iter().any(|(port, disposition)| {!matches!(@@ -497,7 +814,7 @@ fn send_data_message_with(| (PortRight::SendOnce, MACH_MSG_TYPE_MOVE_SEND_ONCE))}) {- return MACH_SEND_INVALID_RIGHT;+ return SendOutcome::Failed(MACH_SEND_INVALID_RIGHT);}let port_count = ports.len();let mut inline_size = HEADER_SIZE + INLINE_PAYLOAD_HEADER_SIZE + payload.len();@@ -511,6 +828,7 @@ fn send_data_message_with(} else {round_message_size(HEADER_SIZE + BODY_SIZE + port_count * PORT_DESCRIPTOR_SIZE + OUT_OF_LINE_DESCRIPTOR_SIZE)};+ let out_of_line_descriptor_offset = HEADER_SIZE + BODY_SIZE + port_count * PORT_DESCRIPTOR_SIZE;buffer.ensure_size(message_size);{@@ -559,8 +877,7 @@ fn send_data_message_with(}}- // NB: The message now owns moved rights. Header errors leave them untouched; body-copyin errors can destroy- // a prefix without reporting its length, so those original names must never be deallocated here.+ // NB: The message now owns the rights it moves, so their owners here must not give them back.for (port, disposition) in &mut ports {if matches!(*disposition,@@ -569,21 +886,48 @@ fn send_data_message_with(port.name = MACH_PORT_NULL;}}- let resources = MessageResources(buffer);- loop {- let result = send(resources.0, message_size);- if result & !MACH_MSG_MASK == MACH_SEND_TIMED_OUT {- // NB: A timeout pseudo-receives the message, possibly with new names and mappings. Retry or destroy- // that returned message, rather than the original port owners or payload address.- if result == MACH_SEND_TIMED_OUT && should_retry() {- continue;++ // NB: Until the kernel maps a copy of its own, the message's out-of-line descriptor points at the borrowed payload,+ // which destroying the message must not deallocate.+ let forget_borrowed_payload = |buffer: &mut MessageBuffer| {+ if send_payload_inline {+ return false;+ }+ let bytes = buffer.bytes_mut();+ let descriptor =+ &mut bytes[out_of_line_descriptor_offset..out_of_line_descriptor_offset + OUT_OF_LINE_DESCRIPTOR_SIZE];+ if u64::from_ne_bytes(descriptor[..8].try_into().unwrap_or_default()) != payload.as_ptr() as u64 {+ return false;+ }+ descriptor[..8].fill(0);+ descriptor[12..16].fill(0);+ true+ };++ let result = send(buffer, message_size);+ match classify_send_attempt(result) {+ SendAttempt::Sent => SendOutcome::Sent,+ SendAttempt::QueueFull => {+ let mut returned = ReturnedMessage {+ buffer: MessageBuffer::new(message_size + TRAILER_SIZE),+ size: message_size,+ };+ returned.buffer.bytes_mut()[..message_size].copy_from_slice(&buffer.bytes()[..message_size]);+ // NB: The kernel hands back a mapping of its own of an out-of-line payload. One that still points at the+ // borrowed payload would outlive it, so the message can't wait.+ if forget_borrowed_payload(&mut returned.buffer) {+ drop(returned);+ return SendOutcome::Failed(result);}- return result;+ SendOutcome::WouldBlock(PendingMessage(PendingMessageContents::Returned(returned)))}- if !send_error_leaves_descriptors_untouched(result) {- std::mem::forget(resources);+ SendAttempt::FailedWithMessageBack => {+ forget_borrowed_payload(buffer);+ // NB: What came back of the message is ours, and the payload no longer in it.+ unsafe { mach_msg_destroy(buffer.header_pointer()) };+ SendOutcome::Failed(result)}- return result;+ SendAttempt::FailedWithMessageConsumed => SendOutcome::Failed(result),}}@@ -642,49 +986,87 @@ pub struct ReceivedMessage {pub local_port: PortName,/// For a LibIPC data message, its bytes and the rights it moved, with their dispositions.pub data: Option<(PayloadBytes, Vec<(MachPort, u32)>)>,+ /// For a message with the id of `MACH_NOTIFY_DEAD_NAME`, the name it says has died. Only the kernel's own+ /// notification holds a reference to that name, which its receiver releases; on a port that a peer can send to, the+ /// name is whatever the peer wrote, and refers to nothing of this task's.+ pub dead_name: Option<PortName>,}#[derive(Debug)]pub enum ReceiveError {- Kernel(KernReturn),- Malformed(&'static str),+ /// A message that could not be received whole is gone. The kernel names the port it came in on, if it got that far.+ Kernel { code: KernReturn, local_port: PortName },+ /// A message that isn't shaped as LibIPC sends one, on the port it came in on.+ Malformed { what: &'static str, local_port: PortName },}/// Receives the next message from a port or port set, growing the buffer for a large one.pub fn receive_message(buffer: &mut MessageBuffer, from: &MachPort) -> Result<ReceivedMessage, ReceiveError> {- receive(buffer, from, 0)+ receive(buffer, from, None).map(|message| message.expect("a receive without a timeout returns a message"))}-/// Receives the next message if one is already queued, without waiting for one.-pub fn try_receive_message(+/// Receives the next message from a port or port set if one comes within the timeout.+pub fn receive_message_within(buffer: &mut MessageBuffer,from: &MachPort,+ timeout_in_milliseconds: u32,) -> Result<Option<ReceivedMessage>, ReceiveError> {- match receive(buffer, from, MACH_RCV_TIMEOUT) {- Err(ReceiveError::Kernel(MACH_RCV_TIMED_OUT)) => Ok(None),- result => result.map(Some),- }+ receive(buffer, from, Some(timeout_in_milliseconds))}-fn receive(buffer: &mut MessageBuffer, from: &MachPort, options: i32) -> Result<ReceivedMessage, ReceiveError> {- let mut result = receive_into(buffer, from, MACH_RCV_LARGE | options);- if result == MACH_RCV_TOO_LARGE {- // NB: The message stays queued; its header says how large a buffer it needs.- let needed = read_u32(buffer.bytes(), 4).unwrap_or(0) as usize + TRAILER_SIZE;+fn receive(+ buffer: &mut MessageBuffer,+ from: &MachPort,+ timeout_in_milliseconds: Option<u32>,+) -> Result<Option<ReceivedMessage>, ReceiveError> {+ // NB: A failed receive names the port of its message here, if the kernel gets that far, so nothing is left over+ // from the last message.+ write_u32(buffer.bytes_mut(), 12, MACH_PORT_NULL);+ let mut options = MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY;+ if timeout_in_milliseconds.is_some() {+ options |= MACH_RCV_TIMEOUT;+ }+ // NB: A retry for a large message keeps to the caller's timeout: something else may take that message meanwhile.+ let deadline = timeout_in_milliseconds+ .map(|timeout| clock_monotonic_nanoseconds().saturating_add(i64::from(timeout) * 1_000_000));+ let remaining_timeout = || match deadline {+ Some(deadline) => {+ let remaining = deadline.saturating_sub(clock_monotonic_nanoseconds()).max(0) as u64;+ u32::try_from(remaining.div_ceil(1_000_000)).unwrap_or(u32::MAX)+ }+ None => MACH_MSG_TIMEOUT_NONE,+ };+ let mut result = receive_into(buffer, from.name(), options, remaining_timeout());+ // NB: The message stays queued, and its header says how large a buffer it needs and which port it waits on. The+ // retry receives from that port alone, as on a port set it could take another port's message, which need not+ // fit either.+ while result == MACH_RCV_TOO_LARGE {+ let port = read_u32(buffer.bytes(), 12).unwrap_or(MACH_PORT_NULL);+ let mut needed = read_u32(buffer.bytes(), 4).unwrap_or(0) as usize + TRAILER_SIZE;+ if needed <= buffer.size() {+ needed = buffer.size() * 2;+ }buffer.ensure_size(needed);- result = receive_into(buffer, from, options);+ result = receive_into(buffer, port, options, remaining_timeout());+ }+ if result == MACH_RCV_TIMED_OUT {+ buffer.shrink_after_large_message();+ return Ok(None);}let message = if result != MACH_MSG_SUCCESS {- Err(ReceiveError::Kernel(result))+ Err(ReceiveError::Kernel {+ code: result,+ local_port: read_u32(buffer.bytes(), 12).unwrap_or(MACH_PORT_NULL),+ })} else {- parse_received_message(buffer)+ parse_received_message(buffer).map(Some)};- buffer.release_excess_capacity();+ buffer.shrink_after_large_message();message}-fn receive_into(buffer: &mut MessageBuffer, from: &MachPort, options: i32) -> KernReturn {- let size = u32::try_from(buffer.words.len() * 8).unwrap_or(u32::MAX);+fn receive_into(buffer: &mut MessageBuffer, from: PortName, options: i32, timeout: u32) -> KernReturn {+ let size = u32::try_from(buffer.size()).unwrap_or(u32::MAX);// NB: The buffer is aligned for a header, and the call writes at most size bytes into it.unsafe {mach_msg(@@ -692,8 +1074,8 @@ fn receive_into(buffer: &mut MessageBuffer, from: &MachPort, options: i32) -> KeMACH_RCV_MSG | options,0,size,- from.name(),- MACH_MSG_TIMEOUT_NONE,+ from,+ timeout,MACH_PORT_NULL,)}@@ -714,20 +1096,31 @@ fn parse_received_message(buffer: &mut MessageBuffer) -> Result<ReceivedMessage,// resources, including header rights, until individual descriptors transfer into Rust owners.let resources = MessageResources(buffer);let bytes = resources.0.bytes_mut();- let malformed = ReceiveError::Malformed;+ let local_port = read_u32(bytes, 12).unwrap_or(MACH_PORT_NULL);+ let malformed = |what| ReceiveError::Malformed { what, local_port };let bits = read_u32(bytes, 0).ok_or(malformed("header"))?;let size = read_u32(bytes, 4).ok_or(malformed("header"))? as usize;- let local_port = read_u32(bytes, 12).ok_or(malformed("header"))?;let id = read_u32(bytes, 20).ok_or(malformed("header"))? as i32;if size > bytes.len() || size < HEADER_SIZE {return Err(malformed("size"));}let bytes = &mut bytes[..size];+ if id == MACH_NOTIFY_DEAD_NAME {+ // NB: After the header comes an NDR record, then the name.+ let name = read_u32(bytes, HEADER_SIZE + 8).ok_or(malformed("dead-name notification"))?;+ return Ok(ReceivedMessage {+ id,+ local_port,+ data: None,+ dead_name: is_valid(name).then_some(name),+ });+ }if id != IPC_DATA_MESSAGE_ID && id != IPC_INLINE_DATA_MESSAGE_ID {return Ok(ReceivedMessage {id,local_port,data: None,+ dead_name: None,});}@@ -801,6 +1194,7 @@ fn parse_received_message(buffer: &mut MessageBuffer) -> Result<ReceivedMessage,id,local_port,data: Some((payload, ports)),+ dead_name: None,})}@@ -992,38 +1386,22 @@ mod tests {use super::*;#[test]- fn large_receives_reuse_the_grown_buffer() {+ fn a_buffer_grown_for_a_large_message_shrinks_back() {let receive = MachPort::allocate_receive_right().unwrap();let destination = receive.make_send_right().unwrap();let attachment = MachPort::allocate_receive_right().unwrap();let ports = (0..6000).map(|_| (attachment.make_send_right().unwrap(), MACH_MSG_TYPE_MOVE_SEND)).collect();- assert_eq!(- send_data_message(&mut MessageBuffer::new(4096), &destination, &[7], ports, || true),- MACH_MSG_SUCCESS- );+ assert!(matches!(+ send_data_message(&mut MessageBuffer::new(4096), &destination, &[7], ports),+ SendOutcome::Sent+ ));let mut buffer = MessageBuffer::new(DEFAULT_RECEIVE_BUFFER_SIZE);let (payload, ports) = receive_message(&mut buffer, &receive).unwrap().data.unwrap();assert_eq!(payload.bytes(), [7]);assert_eq!(ports.len(), 6000);- let buffer_address = buffer.words.as_ptr();- let buffer_size = buffer.words.len() * 8;- assert!(buffer_size > DEFAULT_RECEIVE_BUFFER_SIZE);- assert!(buffer.words.capacity() * 8 <= MAX_RETAINED_RECEIVE_BUFFER_SIZE);- drop(ports);- let ports = (0..6000)- .map(|_| (attachment.make_send_right().unwrap(), MACH_MSG_TYPE_MOVE_SEND))- .collect();- assert_eq!(- send_data_message(&mut MessageBuffer::new(4096), &destination, &[8], ports, || true),- MACH_MSG_SUCCESS- );- let (payload, ports) = receive_message(&mut buffer, &receive).unwrap().data.unwrap();- assert_eq!(payload.bytes(), [8]);- assert_eq!(ports.len(), 6000);- assert_eq!(buffer.words.len() * 8, buffer_size);- assert_eq!(buffer.words.as_ptr(), buffer_address);+ assert_eq!(buffer.size(), DEFAULT_RECEIVE_BUFFER_SIZE);}#[test]@@ -1059,74 +1437,48 @@ mod tests {}#[test]- fn receive_buffer_retention_is_capped() {- let mut buffer = MessageBuffer::new(DEFAULT_RECEIVE_BUFFER_SIZE);- buffer.ensure_size(2 * DEFAULT_RECEIVE_BUFFER_SIZE);- let address = buffer.words.as_ptr();- buffer.release_excess_capacity();- assert_eq!(buffer.words.as_ptr(), address);- buffer.ensure_size(MAX_RETAINED_RECEIVE_BUFFER_SIZE + 8);- buffer.release_excess_capacity();- assert_eq!(buffer.words.len() * 8, MAX_RETAINED_RECEIVE_BUFFER_SIZE);- assert_eq!(buffer.words.capacity() * 8, MAX_RETAINED_RECEIVE_BUFFER_SIZE);- }-- #[test]- fn timed_out_sends_preserve_returned_memory_ownership() {+ fn timed_out_sends_keep_the_mapping_the_kernel_returned() {let mut buffer = MessageBuffer::new(4096);let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);let payload = vec![7; 8192];let descriptor = HEADER_SIZE + BODY_SIZE;- let mut attempt = 0;- assert_eq!(- send_data_message_with(- &mut buffer,- &destination,- &payload,- vec![],- || true,- |buffer, _| {- let bytes = buffer.bytes_mut();- let address = u64::from_ne_bytes(bytes[descriptor..descriptor + 8].try_into().unwrap());- if attempt == 0 {- assert_eq!(address, payload.as_ptr() as u64);- assert_eq!(bytes[descriptor + 8], 0);- } else {- assert_eq!(address, attempt);- assert_eq!(bytes[descriptor + 8], 1);- }- assert_eq!(bytes[descriptor + 9], MACH_MSG_VIRTUAL_COPY);- attempt += 1;- if attempt == 3 {- return MACH_MSG_SUCCESS;- }- // NB: XNU returns a new mapping with deallocate set for a virtual-copy descriptor.- bytes[descriptor..descriptor + 8].copy_from_slice(&attempt.to_ne_bytes());- bytes[descriptor + 8] = 1;- MACH_SEND_TIMED_OUT- }- ),+ let outcome = send_data_message_with(&mut buffer, &destination, &payload, vec![], |buffer, _| {+ let bytes = buffer.bytes_mut();+ let address = u64::from_ne_bytes(bytes[descriptor..descriptor + 8].try_into().unwrap());+ assert_eq!(address, payload.as_ptr() as u64);+ assert_eq!(bytes[descriptor + 8], 0);+ assert_eq!(bytes[descriptor + 9], MACH_MSG_VIRTUAL_COPY);+ // NB: XNU returns a new mapping with deallocate set for a virtual-copy descriptor.+ bytes[descriptor..descriptor + 8].copy_from_slice(&1u64.to_ne_bytes());+ bytes[descriptor + 8] = 1;+ MACH_SEND_TIMED_OUT+ });+ let SendOutcome::WouldBlock(pending) = outcome else {+ panic!("a full queue keeps the message");+ };+ let PendingMessage(PendingMessageContents::Returned(returned)) = pending else {+ panic!("the kernel handed the message back");+ };+ let outcome = returned.try_send_with(|buffer, _| {+ let bytes = buffer.bytes_mut();+ assert_eq!(+ u64::from_ne_bytes(bytes[descriptor..descriptor + 8].try_into().unwrap()),+ 1+ );+ assert_eq!(bytes[descriptor + 8], 1);MACH_MSG_SUCCESS- );- assert_eq!(attempt, 3);+ });+ assert!(matches!(outcome, SendOutcome::Sent));}#[test]- fn too_many_attachments_are_refused_before_sending() {+ fn a_returned_message_that_still_borrows_the_payload_does_not_wait() {let mut buffer = MessageBuffer::new(4096);- let destination = MachPort::allocate_receive_right().unwrap();- let ports = (0..crate::MAX_MESSAGE_ATTACHMENT_COUNT + 1)- .map(|_| {- (- MachPort::adopt(MACH_PORT_NULL, PortRight::Send),- MACH_MSG_TYPE_COPY_SEND,- )- })- .collect();- assert_eq!(- send_data_message(&mut buffer, &destination, &[1], ports, || false),- MACH_SEND_TOO_LARGE- );+ let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);+ let payload = vec![7; 8192];+ let outcome = send_data_message_with(&mut buffer, &destination, &payload, vec![], |_, _| MACH_SEND_TIMED_OUT);+ assert!(matches!(outcome, SendOutcome::Failed(MACH_SEND_TIMED_OUT)));+ assert_eq!(payload, vec![7; 8192]);}#[test]@@ -1136,17 +1488,14 @@ mod tests {let port = file_port_from_fd(OwnedFd::from(writer)).unwrap();let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);let mut buffer = MessageBuffer::new(4096);- assert_eq!(- send_data_message_with(- &mut buffer,- &destination,- &[1],- vec![(port, MACH_MSG_TYPE_MOVE_RECEIVE)],- || false,- |_, _| panic!("invalid dispositions must not be sent")- ),- MACH_SEND_INVALID_RIGHT+ let outcome = send_data_message_with(+ &mut buffer,+ &destination,+ &[1],+ vec![(port, MACH_MSG_TYPE_MOVE_RECEIVE)],+ |_, _| panic!("invalid dispositions must not be sent"),);+ assert!(matches!(outcome, SendOutcome::Failed(MACH_SEND_INVALID_RIGHT)));assert_eq!(reader.read(&mut [0]).unwrap(), 0);}@@ -1167,22 +1516,23 @@ mod tests {MACH_SEND_NO_GRANT_DEST,MACH_SEND_MSG_FILTERED,] {- let (mut reader, writer) = std::io::pipe().unwrap();- let port = file_port_from_fd(OwnedFd::from(writer)).unwrap();- let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);- let mut buffer = MessageBuffer::new(4096);- assert_eq!(- send_data_message_with(+ for payload in [vec![1], vec![1; 8192]] {+ let (mut reader, writer) = std::io::pipe().unwrap();+ let port = file_port_from_fd(OwnedFd::from(writer)).unwrap();+ let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);+ let mut buffer = MessageBuffer::new(4096);+ let outcome = send_data_message_with(&mut buffer,&destination,- &[1],+ &payload,vec![(port, MACH_MSG_TYPE_MOVE_SEND)],- || false,- |_, _| error- ),- error- );- assert_eq!(reader.read(&mut [0]).unwrap(), 0);+ |_, _| error,+ );+ assert!(matches!(outcome, SendOutcome::Failed(failure) if failure == error));+ assert_eq!(reader.read(&mut [0]).unwrap(), 0);+ // NB: Destroying the message must leave the borrowed payload alone.+ assert!(payload.iter().all(|&byte| byte == 1));+ }}}@@ -1202,21 +1552,18 @@ mod tests {);let retained = MachPort::adopt(port.name(), PortRight::Send);let destination = MachPort::adopt(MACH_PORT_NULL, PortRight::Send);- assert_eq!(- send_data_message_with(- &mut MessageBuffer::new(4096),- &destination,- &[1],- vec![(port, MACH_MSG_TYPE_MOVE_SEND)],- || false,- |buffer, _| {- // NB: Simulate the kernel consuming the preceding descriptor before a body-copyin error.- unsafe { mach_msg_destroy(buffer.header_pointer()) };- error- }- ),- error+ let outcome = send_data_message_with(+ &mut MessageBuffer::new(4096),+ &destination,+ &[1],+ vec![(port, MACH_MSG_TYPE_MOVE_SEND)],+ |buffer, _| {+ // NB: Simulate the kernel consuming the preceding descriptor before a body-copyin error.+ unsafe { mach_msg_destroy(buffer.header_pointer()) };+ error+ },);+ assert!(matches!(outcome, SendOutcome::Failed(failure) if failure == error));drop(fd_from_file_port(retained).unwrap());drop(reader);}@@ -1234,7 +1581,7 @@ mod tests {}#[test]- fn timed_out_sends_destroy_the_returned_message() {+ fn a_message_left_waiting_gives_back_what_it_carries() {use std::io::Read;for payload in [vec![1], vec![1; 8192]] {let receive = MachPort::allocate_receive_right().unwrap();@@ -1244,19 +1591,19 @@ mod tests {let port = file_port_from_fd(OwnedFd::from(writer)).unwrap();let attachment_receive = MachPort::allocate_receive_right().unwrap();let attachment_send = attachment_receive.make_send_right().unwrap();- assert_eq!(- send_data_message(- &mut MessageBuffer::new(4096),- &destination,- &payload,- vec![- (port, MACH_MSG_TYPE_MOVE_SEND),- (attachment_receive, MACH_MSG_TYPE_MOVE_RECEIVE)- ],- || false- ),- MACH_SEND_TIMED_OUT+ let outcome = send_data_message(+ &mut MessageBuffer::new(4096),+ &destination,+ &payload,+ vec![+ (port, MACH_MSG_TYPE_MOVE_SEND),+ (attachment_receive, MACH_MSG_TYPE_MOVE_RECEIVE),+ ],);+ let SendOutcome::WouldBlock(pending) = outcome else {+ panic!("a full queue keeps the message");+ };+ drop(pending);assert_eq!(reader.read(&mut [0]).unwrap(), 0);assert_eq!(send_header_only_message(&attachment_send, IPC_WAKEUP_MESSAGE_ID, Some(0)),@@ -1266,30 +1613,31 @@ mod tests {}#[test]- fn timed_out_sends_retry_the_returned_rights_and_memory() {+ fn a_message_left_waiting_goes_out_whole_once_there_is_room() {let receive = MachPort::allocate_receive_right().unwrap();let destination = receive.make_send_right().unwrap();fill_queue(&receive, &destination);let attachment = MachPort::allocate_receive_right().unwrap();let payload = vec![7; 8192];- let mut retries = 0;- assert_eq!(- send_data_message(- &mut MessageBuffer::new(4096),- &destination,- &payload,- vec![(attachment, MACH_MSG_TYPE_MOVE_RECEIVE)],- || {- retries += 1;- assert_eq!(retries, 1);- let message = receive_message(&mut MessageBuffer::new(4096), &receive).unwrap();- assert_eq!(message.id, IPC_WAKEUP_MESSAGE_ID);- true- }- ),- MACH_MSG_SUCCESS+ let outcome = send_data_message(+ &mut MessageBuffer::new(4096),+ &destination,+ &payload,+ vec![(attachment, MACH_MSG_TYPE_MOVE_RECEIVE)],);- assert_eq!(retries, 1);+ let SendOutcome::WouldBlock(pending) = outcome else {+ panic!("a full queue keeps the message");+ };+ let mut scratch = MessageBuffer::new(4096);+ let SendOutcome::WouldBlock(pending) = pending.try_send(&mut scratch, &destination) else {+ panic!("the queue is still full");+ };+ let message = receive_message(&mut MessageBuffer::new(4096), &receive).unwrap();+ assert_eq!(message.id, IPC_WAKEUP_MESSAGE_ID);+ assert!(matches!(+ pending.try_send(&mut scratch, &destination),+ SendOutcome::Sent+ ));loop {let message = receive_message(&mut MessageBuffer::new(4096), &receive).unwrap();if let Some((bytes, ports)) = message.data {diff --git a/Libraries/LibIPC/Rust/src/receive_queue.rs b/Libraries/LibIPC/Rust/src/receive_queue.rsindex 67d876d2dff..d94a1ee75ba 100644--- a/Libraries/LibIPC/Rust/src/receive_queue.rs+++ b/Libraries/LibIPC/Rust/src/receive_queue.rs@@ -4,9 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-#[cfg(unix)]+#[cfg(all(unix, not(target_vendor = "apple")))]use std::collections::VecDeque;-#[cfg(unix)]+#[cfg(all(unix, not(target_vendor = "apple")))]use std::sync::{Condvar, Mutex, MutexGuard};use crate::attachment::Attachment;@@ -31,21 +31,21 @@ impl ReceivedMessage {}}-#[cfg(unix)]+#[cfg(all(unix, not(target_vendor = "apple")))]#[derive(Default)]pub(crate) struct Incoming {pub messages: VecDeque<ReceivedMessage>,pub peer_eof: bool,}-#[cfg(unix)]+#[cfg(all(unix, not(target_vendor = "apple")))]#[derive(Default)]pub(crate) struct IncomingQueue {incoming: Mutex<Incoming>,changed: Condvar,}-#[cfg(unix)]+#[cfg(all(unix, not(target_vendor = "apple")))]impl IncomingQueue {pub fn lock(&self) -> MutexGuard<'_, Incoming> {self.incoming.lock().unwrap_or_else(|error| error.into_inner())diff --git a/Libraries/LibIPC/Rust/src/transport.rs b/Libraries/LibIPC/Rust/src/transport.rsindex b36b3481658..04d39cae3e1 100644--- a/Libraries/LibIPC/Rust/src/transport.rs+++ b/Libraries/LibIPC/Rust/src/transport.rs@@ -6,18 +6,27 @@//! The Mach port transport, which speaks with `IPC::TransportMachPort` on the other end.//!-//! An IO thread waits on a port set holding the transport's receive right and a private wakeup port. It sends what the-//! owner posts, and queues what arrives for the owner to take. The peer going away shows as `MACH_NOTIFY_NO_SENDERS` on-//! the receive right, once the peer's last send right to it is gone.+//! All transports of a process share one IO thread. It waits on one port set, which holds the receive right of each+//! transport and the port on which a transport hears that its peer's full queue has room. The thread that posts a+//! message hands it to the kernel itself, unless earlier messages still wait for room in the peer's queue; then it+//! waits behind them, and the IO thread sends them as the peer makes room. The peer going away shows as+//! `MACH_NOTIFY_NO_SENDERS` on the receive right, once the peer's last send right to it is gone.-use std::sync::atomic::{AtomicU8, Ordering};-use std::sync::{Arc, Condvar, Mutex, MutexGuard};-use std::thread::JoinHandle;+use std::cell::Cell;+use std::collections::{HashMap, VecDeque};+use std::fs::File;+use std::io::Write;+use std::os::fd::OwnedFd;+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};+use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};+use std::time::{Duration, Instant};use crate::MAX_MESSAGE_ATTACHMENT_COUNT;use crate::attachment::Attachment;-use crate::mach::{self, KernelError, MachPort, MessageBuffer, ReceiveError};-use crate::receive_queue::IncomingQueue;+use crate::mach::{+ self, KernReturn, KernelError, MachPort, MessageBuffer, OwnedPayload, PendingMessage, PortName, ReceiveError,+ SendOutcome,+};pub use crate::receive_queue::ReceivedMessage;/// The receive right and send right that make up one end of a connection, as `IPC::TransportHandle` holds them.@@ -26,6 +35,60 @@ pub struct MachPortPair {pub send_right: MachPort,}+/// What the IO thread shows every message that arrives, before the transport's owner gets to see it, and empty bytes+/// once the peer is gone.+pub type IncomingMessageObserver = Box<dyn Fn(&[u8]) + Send>;++/// A point in time on `CLOCK_MONOTONIC`, the clock of AK's `MonotonicTime`, which keeps counting while the system+/// sleeps. A wait checks it again after every wakeup, so that it ends when its caller's deadline passes.+#[derive(Clone, Copy)]+pub struct MonotonicDeadline {+ nanoseconds: i64,+}++impl MonotonicDeadline {+ pub fn from_nanoseconds(nanoseconds: i64) -> Self {+ Self { nanoseconds }+ }++ fn remaining(self) -> Option<Duration> {+ let now = mach::clock_monotonic_nanoseconds();+ (now < self.nanoseconds).then(|| Duration::from_nanos(self.nanoseconds.abs_diff(now)))+ }+}++/// The bytes of a message to post: owned already, or lent by a caller that hands them over only if the message has to+/// wait, as C++ does with the buffer it encoded the message into.+pub enum OutgoingPayload<'a> {+ Owned(Vec<u8>),+ Lent {+ bytes: &'a [u8],+ hand_over: &'a mut dyn FnMut() -> OwnedPayload,+ },+}++impl OutgoingPayload<'_> {+ fn bytes(&self) -> &[u8] {+ match self {+ Self::Owned(bytes) => bytes,+ Self::Lent { bytes, .. } => bytes,+ }+ }++ fn into_owned(self) -> OwnedPayload {+ match self {+ Self::Owned(bytes) => Box::new(bytes),+ Self::Lent { hand_over, .. } => hand_over(),+ }+ }+}++const MAX_BACKLOG_MESSAGES_SENT_PER_TURN: usize = 64;+const MAX_MESSAGES_RECEIVED_BETWEEN_TURNS_OF_SENDING: usize = 64;+const IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS: u32 = 1000;+const RETRY_DELAY: Duration = Duration::from_millis(1);+const FLUSH_WAKEUP_REARM_INTERVAL: Duration = Duration::from_millis(50);+#[derive(Clone, Copy, PartialEq, Eq)]#[repr(u8)]enum IoThreadState {@@ -34,56 +97,889 @@ enum IoThreadState {Stopped = 2,}-struct PendingMessage {- bytes: Vec<u8>,- attachments: Vec<Attachment>,+// One turn of sending on the IO thread, as far as the peer has room, and the stop asked for.+enum PendingIo {+ None,+ MoreToSendNextTurn,+ // The peer's queue is full, and the kernel could not be asked to say when it has room.+ RetryAfterDelay,+ IoIsOver,+}++struct SendState {+ send_right: Option<MachPort>,+ // NB: Messages the peer's queue had no room for, in order. While there are any, a newly posted message waits+ // behind them, and the IO thread sends them as the peer makes room.+ backlog: VecDeque<PendingMessage>,+ sending_is_over: bool,+ // NB: Set once a send fails, which the kernel only does for a message that can't reach the peer, and after which+ // nothing more is taken to send. What the peer sent before keeps arriving.+ peer_is_unreachable: bool,+ // NB: Grows on the first send, so that a transport which only receives keeps no send storage.+ buffer: MessageBuffer,+ // NB: Where the kernel says that the peer's full queue has room, from the first time it was full.+ send_possible_notification_port: Option<MachPort>,+ send_possible_notification_is_requested: bool,}#[derive(Default)]-struct SendQueue {- pending: Vec<PendingMessage>,- in_progress: bool,- waiters_released: bool,+struct Incoming {+ messages: VecDeque<ReceivedMessage>,+ // NB: Set once this end's IO is over, which ends a wait for messages that can no longer come, even when the rights+ // went to a new owner and the peer is not gone.+ local_io_is_over: bool,+ wait_until_readable_interrupted: bool,+ receive_barriers_sent: u64,+ receive_barriers_received: u64,+ read_notification_pending: bool,+ read_notification_pipe: Option<File>,}struct Shared {- state: AtomicU8,- send_queue: Mutex<SendQueue>,+ receive_port_name: PortName,+ io_thread_state: AtomicU8,+ is_open: AtomicBool,+ // NB: Written under the incoming lock, so that a reader under it sees it with the messages that came before.+ peer_eof: AtomicBool,+ // NB: True while release_for_transfer() moves the rights to a new owner. Shutdown of this end is then part of the+ // handoff, not the peer going away.+ is_being_transferred: AtomicBool,+ // NB: Set by a thread that found the peer gone as it posted, for the IO thread to tell the owner, as it does when+ // it finds that itself, so that the incoming message observer only runs there.+ posting_thread_found_peer_gone: AtomicBool,+ peer_unreachable_marker_was_sent: AtomicBool,+ // NB: As SendState::peer_is_unreachable, for is_open() to read without the send lock.+ peer_is_unreachable: AtomicBool,+ // NB: Set before the owner asks IO to stop. IO that stops on its own, as for a peer that misbehaves, hands what is+ // left unsent to the IO thread to release, as nothing else would until the owner lets go of the transport.+ stop_was_requested_by_owner: AtomicBool,+ // NB: These two change only under the lock of the shared IO thread's attention list.+ needs_attention: AtomicBool,+ io_is_finished: AtomicBool,++ // NB: Held by whichever thread sends, which is the thread that posts a message unless the message has to wait.+ send: Mutex<SendState>,sent: Condvar,- incoming: IncomingQueue,- wakeup_send_right: MachPort,++ incoming: Mutex<Incoming>,+ incoming_changed: Condvar,++ // NB: This has a lock of its own, which is taken before the incoming lock: the observer may interrupt a wait.+ incoming_message_observer: Mutex<Option<IncomingMessageObserver>>,+}++fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {+ mutex.lock().unwrap_or_else(|error| error.into_inner())+}++fn wait<'a, T>(condition: &Condvar, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {+ condition.wait(guard).unwrap_or_else(|error| error.into_inner())+}++fn wait_for<'a, T>(condition: &Condvar, guard: MutexGuard<'a, T>, timeout: Duration) -> (MutexGuard<'a, T>, bool) {+ let (guard, result) = condition+ .wait_timeout(guard, timeout)+ .unwrap_or_else(|error| error.into_inner());+ (guard, result.timed_out())}impl Shared {- fn state(&self) -> IoThreadState {- match self.state.load(Ordering::Acquire) {+ fn io_thread_state(&self) -> IoThreadState {+ match self.io_thread_state.load(Ordering::Acquire) {0 => IoThreadState::Running,1 => IoThreadState::SendPendingMessagesAndStop,_ => IoThreadState::Stopped,}}- fn set_state(&self, state: IoThreadState) {- self.state.store(state as u8, Ordering::Release);+ fn set_io_thread_state(&self, state: IoThreadState) {+ self.io_thread_state.store(state as u8, Ordering::Release);+ }++ fn identity(self: &Arc<Self>) -> usize {+ Arc::as_ptr(self) as usize+ }++ fn notify_incoming_message_observer(&self, bytes: &[u8]) {+ // NB: The observer runs under its lock, so once a new one is set, the old one is no longer running.+ if let Some(observer) = &*lock(&self.incoming_message_observer) {+ observer(bytes);+ }+ }++ fn schedule_read_notification(incoming: &mut Incoming) {+ if incoming.read_notification_pending {+ return;+ }+ incoming.read_notification_pending = true;+ if let Some(pipe) = &incoming.read_notification_pipe {+ // NB: An interrupted write wrote nothing, so it is retried. The pipe does not block, and a full one already+ // wakes the owner.+ let _ = (&*pipe).write_all(&[0]);+ }+ }++ fn mark_peer_eof(&self) {+ self.notify_incoming_message_observer(&[]);+ {+ let mut incoming = lock(&self.incoming);+ self.peer_eof.store(true, Ordering::Release);+ Self::schedule_read_notification(&mut incoming);+ }+ self.incoming_changed.notify_all();+ }++ // NB: The peer may have sent messages that are still on the receive right, which the IO thread has yet to take in,+ // and which the owner gets to read before it hears that the peer is gone. A marker sent to the receive right+ // follows them, and the peer's departure shows once the marker arrives. A send-once right bypasses the queue+ // limit, so sending it doesn't wait.+ fn mark_peer_eof_behind_messages_already_sent(&self) {+ if self.peer_unreachable_marker_was_sent.swap(true, Ordering::AcqRel) {+ return;+ }+ // NB: The owner keeps the receive right until IO is over, and this runs on the IO thread before that.+ let marker_was_sent =+ mach::make_send_once_right_from_receive_right_named(self.receive_port_name).is_ok_and(|marker_right| {+ mach::send_header_only_message_through_send_once_right(+ marker_right,+ mach::IPC_PEER_UNREACHABLE_MESSAGE_ID,+ ) == mach::MACH_MSG_SUCCESS+ });+ if !marker_was_sent {+ self.mark_peer_eof();+ }+ }++ // NB: Answers whether to go on taking messages from the peer.+ fn handle_message_on_io_thread(&self, message: mach::ReceivedMessage) -> bool {+ match message.id {+ mach::IPC_RECEIVE_BARRIER_MESSAGE_ID => {+ lock(&self.incoming).receive_barriers_received += 1;+ self.incoming_changed.notify_all();+ true+ }+ mach::MACH_NOTIFY_NO_SENDERS => {+ self.mark_peer_eof();+ true+ }+ // NB: The peer may still hold a send right to this end after it let go of its receive right. What it sends+ // after the marker would come after the owner heard that it is gone, so nothing more is taken from it.+ mach::IPC_PEER_UNREACHABLE_MESSAGE_ID => {+ self.mark_peer_eof();+ self.set_io_thread_state(IoThreadState::Stopped);+ false+ }+ mach::MACH_NOTIFY_SEND_ONCE => true,+ mach::IPC_DATA_MESSAGE_ID | mach::IPC_INLINE_DATA_MESSAGE_ID => {+ if self.process_received_message(message) {+ return true;+ }+ self.set_io_thread_state(IoThreadState::Stopped);+ false+ }+ id => {+ eprintln!("TransportMachPort: Rejecting message with unknown id {id:#x}");+ self.mark_peer_eof();+ self.set_io_thread_state(IoThreadState::Stopped);+ false+ }+ }+ }++ // NB: Answers false for a message the peer had no business sending, after which the transport takes nothing more+ // from it.+ fn process_received_message(&self, message: mach::ReceivedMessage) -> bool {+ let Some((bytes, ports)) = message.data else {+ self.mark_peer_eof();+ return false;+ };+ // NB: The rights and the payload region are ours once received, so dropping them releases them.+ if ports.len() > MAX_MESSAGE_ATTACHMENT_COUNT {+ eprintln!(+ "TransportMachPort: Rejecting message with {} attachments exceeding limit {MAX_MESSAGE_ATTACHMENT_COUNT}",+ ports.len()+ );+ self.mark_peer_eof();+ return false;+ }+ if bytes.bytes().is_empty() && ports.is_empty() {+ return true;+ }++ self.notify_incoming_message_observer(bytes.bytes());++ let attachments = ports+ .into_iter()+ .map(|(port, disposition)| Attachment::from_mach_port(port, disposition))+ .collect();+ {+ let mut incoming = lock(&self.incoming);+ let was_empty = incoming.messages.is_empty();+ incoming.messages.push_back(ReceivedMessage { bytes, attachments });+ if was_empty {+ Self::schedule_read_notification(&mut incoming);+ }+ }+ self.incoming_changed.notify_all();+ true+ }++ // NB: The request is armed as it is made, and answered right away if the peer's queue has room by then. Answers+ // whether it was made. A transport that can't make one retries after a delay instead.+ fn request_send_possible_notification(self: &Arc<Self>, send: &mut SendState) -> bool {+ assert!(!send.send_possible_notification_is_requested);+ let io_thread = shared_io_thread();+ if send.send_possible_notification_port.is_none() {+ let Ok(port) = MachPort::allocate_receive_right() else {+ return false;+ };+ if io_thread+ .add(Registration::SendPossibleNotification(Arc::clone(self)), &port)+ .is_err()+ {+ return false;+ }+ send.send_possible_notification_port = Some(port);+ }+ let (Some(destination), Some(notification_port)) = (&send.send_right, &send.send_possible_notification_port)+ else {+ return false;+ };+ if !io_thread.claim_send_possible_request(self.identity(), destination) {+ return false;+ }+ match destination.request_send_possible_notification(notification_port) {+ Ok(None) => {+ send.send_possible_notification_is_requested = true;+ true+ }+ Ok(Some(replaced)) => {+ // NB: Something besides the transports made a request on the name after the claim checked it, and+ // this one took its place. It goes back, as the dead-name request that anything but a transport+ // makes.+ destination.restore_dead_name_notification(replaced);+ io_thread.release_send_possible_request(self.identity(), destination.name());+ false+ }+ Err(_) => {+ io_thread.release_send_possible_request(self.identity(), destination.name());+ false+ }+ }+ }++ fn handle_send_possible_notification(self: &Arc<Self>, message: &mach::ReceivedMessage) {+ if !consumes_send_possible_request(message) {+ return;+ }+ let mut send = lock(&self.send);+ send.send_possible_notification_is_requested = false;+ if let Some(destination) = &send.send_right {+ shared_io_thread().release_send_possible_request(self.identity(), destination.name());+ }+ }++ fn send(self: &Arc<Self>, send: &mut SendState, message: Outgoing<'_>) -> SendResult {+ let SendState { send_right, buffer, .. } = &mut *send;+ let Some(destination) = send_right.as_ref() else {+ return SendResult::PeerGone;+ };+ let outcome = match message {+ Outgoing::Waiting(pending) => pending.try_send(buffer, destination),+ Outgoing::New { payload, ports } => mach::send_data_message(buffer, destination, payload.bytes(), ports),+ };+ match outcome {+ SendOutcome::Sent => SendResult::Sent,+ SendOutcome::WouldBlock(pending) => {+ if !send.send_possible_notification_is_requested {+ let _ = self.request_send_possible_notification(send);+ }+ SendResult::WouldBlock(pending)+ }+ SendOutcome::Failed(error) => {+ eprintln!("TransportMachPort: send failed: {}", mach::error_string(error));+ send.peer_is_unreachable = true;+ self.peer_is_unreachable.store(true, Ordering::Release);+ SendResult::PeerGone+ }+ }+ }++ // NB: The backlog is retried while the IO thread keeps receiving: a thread that blocked in a send would stop+ // draining its own queue, and two such threads facing each other would wait on each other for good.+ fn do_pending_io(self: &Arc<Self>) -> PendingIo {+ if self.io_thread_state() == IoThreadState::Stopped {+ return PendingIo::IoIsOver;+ }++ let mut peer_is_gone = self.posting_thread_found_peer_gone.swap(false, Ordering::AcqRel);+ let mut pending_io = PendingIo::None;+ let mut unsendable = Vec::new();+ {+ let mut send = lock(&self.send);+ let had_backlog = !send.backlog.is_empty();+ // NB: A turn sends a bounded part of a long backlog, as of one that a peer takes again after a while, so+ // that the IO thread gets back to receiving, and to the other transports, in between.+ let mut peer_queue_is_full = false;+ // NB: After a failed send, nothing more goes out: a message that came after one the peer never got would+ // arrive out of turn.+ for _ in 0..MAX_BACKLOG_MESSAGES_SENT_PER_TURN {+ if send.peer_is_unreachable {+ break;+ }+ let Some(message) = send.backlog.pop_front() else {+ break;+ };+ match self.send(&mut send, Outgoing::Waiting(message)) {+ SendResult::Sent => {}+ SendResult::WouldBlock(message) => {+ send.backlog.push_front(message);+ peer_queue_is_full = true;+ break;+ }+ SendResult::PeerGone => peer_is_gone = true,+ }+ }+ // NB: What can no longer be sent may carry rights that keep other connections open, so it goes without+ // waiting for the owner, a bounded part per turn as releasing rights takes a while.+ if send.peer_is_unreachable {+ let count = send.backlog.len().min(MAX_BACKLOG_MESSAGES_SENT_PER_TURN);+ unsendable.extend(send.backlog.drain(..count));+ self.sent.notify_all();+ }+ if send.backlog.is_empty() {+ if had_backlog {+ // NB: A queue that has drained keeps its capacity, which this lets go of.+ send.backlog = VecDeque::new();+ self.sent.notify_all();+ }+ // NB: Posting threads check the state under this lock, so nothing is left behind in the backlog.+ if self.io_thread_state() == IoThreadState::SendPendingMessagesAndStop {+ self.set_io_thread_state(IoThreadState::Stopped);+ pending_io = PendingIo::IoIsOver;+ }+ } else if send.peer_is_unreachable || !peer_queue_is_full {+ pending_io = PendingIo::MoreToSendNextTurn;+ } else if !send.send_possible_notification_is_requested {+ pending_io = PendingIo::RetryAfterDelay;+ }+ }+ drop(unsendable);+ if peer_is_gone {+ self.mark_peer_eof_behind_messages_already_sent();+ }+ pending_io+ }++ // NB: Runs on the IO thread as IO is over, after the receive right has left the port set. Gives back what is left+ // unsent for the IO thread to release, unless the owner asked IO to stop, and releases it itself.+ fn stop_sending(self: &Arc<Self>) -> VecDeque<PendingMessage> {+ let io_thread = shared_io_thread();+ let mut send = lock(&self.send);+ send.sending_is_over = true;+ let unsendable = if self.stop_was_requested_by_owner.load(Ordering::Acquire) {+ VecDeque::new()+ } else {+ std::mem::take(&mut send.backlog)+ };+ // NB: A request that cancelling does not take back has been used up, and the kernel owes a notification for+ // it, which need not be queued yet. One about a dead port holds a reference to the dead name, to release.+ let mut notification_is_owed = false;+ if send.send_possible_notification_is_requested {+ send.send_possible_notification_is_requested = false;+ match &send.send_right {+ Some(destination) => {+ notification_is_owed = !destination.cancel_send_possible_notification();+ io_thread.release_send_possible_request(self.identity(), destination.name());+ }+ None => notification_is_owed = true,+ }+ }+ if let Some(port) = send.send_possible_notification_port.take() {+ let mut buffer = MessageBuffer::new(256);+ while let Ok(Some(message)) = mach::receive_message_within(&mut buffer, &port, 0) {+ if consumes_send_possible_request(&message) {+ notification_is_owed = false;+ }+ }+ if notification_is_owed {+ io_thread.keep_until_its_last_notification(port);+ } else {+ // NB: Destroying the receive right takes it out of the port set, and frees its name for reuse.+ io_thread.remove(port.name(), self);+ drop(port);+ }+ }+ drop(send);+ self.sent.notify_all();+ unsendable}- fn should_retry_send(&self) -> bool {- self.state() != IoThreadState::Stopped+ // NB: Runs on the IO thread as IO is over, after the receive right has left the port set.+ fn finish_io(self: &Arc<Self>) -> VecDeque<PendingMessage> {+ assert!(self.io_thread_state() == IoThreadState::Stopped);+ let unsendable = self.stop_sending();+ lock(&self.incoming).local_io_is_over = true;+ self.incoming_changed.notify_all();+ // NB: Stopping for transfer tears down this end on purpose, and the rights are about to be adopted by the+ // new owner, so that is not the peer going away.+ if !self.is_being_transferred.load(Ordering::Acquire) {+ self.mark_peer_eof();+ }+ unsendable}+}++enum Outgoing<'a> {+ New {+ payload: OutgoingPayload<'a>,+ ports: Vec<(MachPort, u32)>,+ },+ Waiting(PendingMessage),+}++enum SendResult {+ Sent,+ WouldBlock(PendingMessage),+ PeerGone,+}++// NB: Answers whether the notification used up the send-possible request, which it does once the peer's queue has+// room, or as a dead-name notification once the peer's port has died. It is only for a message that came in on a+// notification port, which only the kernel can send to, as the dead-name notification then holds a reference to+// the dead name, to release.+fn consumes_send_possible_request(message: &mach::ReceivedMessage) -> bool {+ match message.id {+ mach::MACH_NOTIFY_SEND_POSSIBLE => true,+ mach::MACH_NOTIFY_DEAD_NAME => {+ if let Some(dead_name) = message.dead_name {+ drop(MachPort::adopt(dead_name, mach::PortRight::Send));+ }+ true+ }+ _ => false,+ }+}++fn release_unused_allocator_memory() {+ // NB: The messages the IO thread receives are freed by the threads that handle them, and the allocator keeps that+ // memory until this thread allocates again or collects, which an idle process may never do. Unit tests+ // don't link AK, and use the system allocator.+ #[cfg(ladybird_links_ak)]+ ak::release_unused_allocator_memory();+}- fn wake_io_thread(&self) {- // NB: The wakeup is best-effort; a full wakeup queue already wakes the thread.+enum Registration {+ Receive(Arc<Shared>),+ SendPossibleNotification(Arc<Shared>),+ // NB: The notification port of a transport whose IO is over, while the kernel still owes it a notification for a+ // request that it has used up. It goes once that has arrived.+ OrphanedNotification(+ #[expect(dead_code, reason = "Only held for the right, which dropping it gives back")] MachPort,+ ),+}++enum Route {+ Receive(Arc<Shared>),+ SendPossibleNotification(Arc<Shared>),+ OrphanedNotification,+ Unknown,+}++#[derive(Default)]+struct Attention {+ transports: Vec<Arc<Shared>>,+}++thread_local! {+ static IS_SHARED_IO_THREAD: Cell<bool> = const { Cell::new(false) };+}++/// The IO thread of every transport in the process. It waits on one port set, which holds the receive right of each+/// transport, and finds the transport a message is for by the port it came in on. Each message costs this thread a+/// copy and a wakeup of its owner, so the messages of other transports hold one up only briefly.+struct SharedIoThread {+ port_set: MachPort,+ wakeup_receive_right: MachPort,+ wakeup_send_right: MachPort,++ attention: Mutex<Attention>,+ io_finished: Condvar,++ // NB: Entries go in before their port joins the set, and out before their port is destroyed, as a name can be+ // reused at once.+ registrations: Mutex<HashMap<PortName, Registration>>,++ // NB: The task holds one notification request per name, and transports that send to the same port share the+ // name of their send right, so only one of them at a time may have a send-possible request on it.+ send_possible_request_owners: Mutex<HashMap<PortName, usize>>,+}++static IO_THREAD: OnceLock<Arc<SharedIoThread>> = OnceLock::new();++// NB: Every transport starts the thread as it is made, before anything reaches it through here.+fn shared_io_thread() -> &'static SharedIoThread {+ IO_THREAD+ .get()+ .expect("a transport starts the shared Mach IO thread before it uses it")+}++fn start_shared_io_thread() -> std::io::Result<&'static SharedIoThread> {+ static STARTING: Mutex<()> = Mutex::new(());+ if let Some(io_thread) = IO_THREAD.get() {+ return Ok(io_thread);+ }+ let _starting = lock(&STARTING);+ if let Some(io_thread) = IO_THREAD.get() {+ return Ok(io_thread);+ }+ let io_thread = Arc::new(SharedIoThread::new().map_err(KernelError)?);+ // NB: Nothing waits for this thread, which goes with the process. If it can't start, its ports go with the last+ // reference, and the next transport tries again.+ std::thread::Builder::new().name("IPC IO (Mach)".to_string()).spawn({+ let io_thread = Arc::clone(&io_thread);+ move || {+ // NB: This thread only relays messages between the kernel and the threads that own the transports. If+ // it ran below them, every message would wait on a lower-priority wakeup.+ mach::set_current_thread_qos_to_user_interactive();+ io_thread.run();+ }+ })?;+ Ok(IO_THREAD.get_or_init(|| io_thread))+}++// NB: Only the IO thread uses these.+struct IoThreadLocals {+ receive_buffer: MessageBuffer,+ transports_to_serve: Vec<Arc<Shared>>,+ // NB: Transports whose peer's queue is full, which the kernel could not be asked to say when it has room.+ transports_retrying_after_delay: Vec<Arc<Shared>>,+ // NB: What transports whose IO stopped on its own left unsent, released a bounded part per turn.+ unsendable: VecDeque<PendingMessage>,+ retry_deadline: Instant,+}++impl SharedIoThread {+ fn new() -> Result<Self, KernReturn> {+ let port_set = MachPort::allocate_port_set()?;+ let wakeup_receive_right = MachPort::allocate_receive_right()?;+ let wakeup_send_right = wakeup_receive_right.make_send_right()?;+ port_set.insert_member(&wakeup_receive_right)?;+ Ok(Self {+ port_set,+ wakeup_receive_right,+ wakeup_send_right,+ attention: Mutex::default(),+ io_finished: Condvar::new(),+ registrations: Mutex::default(),+ send_possible_request_owners: Mutex::default(),+ })+ }++ // NB: Messages that arrive on the port, one of the transport's own, are the transport's from here on.+ fn add(&self, registration: Registration, port: &MachPort) -> Result<(), KernReturn> {+ lock(&self.registrations).insert(port.name(), registration);+ if let Err(error) = self.port_set.insert_member(port) {+ lock(&self.registrations).remove(&port.name());+ return Err(error);+ }+ Ok(())+ }++ fn remove(&self, port: PortName, transport: &Arc<Shared>) {+ let mut registrations = lock(&self.registrations);+ let belongs_to_transport = match registrations.get(&port) {+ Some(Registration::Receive(owner) | Registration::SendPossibleNotification(owner)) => {+ Arc::ptr_eq(owner, transport)+ }+ _ => false,+ };+ if belongs_to_transport {+ registrations.remove(&port);+ }+ }++ fn route(&self, port: PortName) -> Route {+ match lock(&self.registrations).get(&port) {+ Some(Registration::Receive(transport)) => Route::Receive(Arc::clone(transport)),+ Some(Registration::SendPossibleNotification(transport)) => {+ Route::SendPossibleNotification(Arc::clone(transport))+ }+ Some(Registration::OrphanedNotification(_)) => Route::OrphanedNotification,+ None => Route::Unknown,+ }+ }++ // NB: Nor may one take the place of a request that something else has made there. Answers whether the transport+ // may make its request.+ fn claim_send_possible_request(&self, transport: usize, destination: &MachPort) -> bool {+ let mut owners = lock(&self.send_possible_request_owners);+ if owners.contains_key(&destination.name()) {+ return false;+ }+ match destination.port_type() {+ Ok(port_type) if port_type & (mach::MACH_PORT_TYPE_DNREQUEST | mach::MACH_PORT_TYPE_SPREQUEST) == 0 => {}+ _ => return false,+ }+ owners.insert(destination.name(), transport);+ true+ }++ fn release_send_possible_request(&self, transport: usize, destination: PortName) {+ let mut owners = lock(&self.send_possible_request_owners);+ if owners.get(&destination) == Some(&transport) {+ owners.remove(&destination);+ }+ }++ // NB: Has this thread send the transport's backlog, take note of a peer it found gone, and stop its IO if asked+ // to. A backlog is otherwise sent when the kernel says the peer's queue has room.+ fn request_attention(&self, transport: &Arc<Shared>) {+ {+ let mut attention = lock(&self.attention);+ if transport.io_is_finished.load(Ordering::Relaxed) {+ return;+ }+ if !transport.needs_attention.load(Ordering::Relaxed) {+ transport.needs_attention.store(true, Ordering::Relaxed);+ attention.transports.push(Arc::clone(transport));+ }+ }+ self.wake();+ }++ fn wait_until_io_is_finished(&self, transport: &Shared) {+ assert!(+ !IS_SHARED_IO_THREAD.get(),+ "the shared Mach IO thread must not wait for itself"+ );+ let mut attention = lock(&self.attention);+ while !transport.io_is_finished.load(Ordering::Relaxed) {+ attention = wait(&self.io_finished, attention);+ }+ }++ fn keep_until_its_last_notification(&self, notification_port: MachPort) {+ assert!(IS_SHARED_IO_THREAD.get());+ let name = notification_port.name();+ lock(&self.registrations).insert(name, Registration::OrphanedNotification(notification_port));+ }++ fn wake(&self) {+ // NB: A full wakeup queue already has this thread on its way.let _ = mach::send_header_only_message(&self.wakeup_send_right, mach::IPC_WAKEUP_MESSAGE_ID, Some(0));}- fn lock_send_queue(&self) -> MutexGuard<'_, SendQueue> {- self.send_queue.lock().unwrap_or_else(|error| error.into_inner())+ fn run(&self) {+ IS_SHARED_IO_THREAD.set(true);+ let mut locals = IoThreadLocals {+ receive_buffer: MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE),+ transports_to_serve: Vec::new(),+ transports_retrying_after_delay: Vec::new(),+ unsendable: VecDeque::new(),+ retry_deadline: Instant::now(),+ };+ let mut released_memory_since_last_message = true;+ loop {+ self.serve_transports_needing_attention(&mut locals);+ let count = locals.unsendable.len().min(MAX_BACKLOG_MESSAGES_SENT_PER_TURN);+ locals.unsendable.drain(..count);++ // NB: A backlog that one turn did not get through goes on in the next, once this thread has taken in what+ // came meanwhile.+ if self.has_transports_needing_attention() || !locals.unsendable.is_empty() {+ for _ in 0..MAX_MESSAGES_RECEIVED_BETWEEN_TURNS_OF_SENDING {+ if !self.receive_and_handle_message(&mut locals, Some(0)) {+ break;+ }+ released_memory_since_last_message = false;+ }+ continue;+ }++ // NB: Wait on the whole port set, for messages from every peer, wakeups, and kernel notifications like+ // MACH_NOTIFY_NO_SENDERS, or MACH_NOTIFY_SEND_POSSIBLE once a peer's full queue has room.+ let retries_after_delay = !locals.transports_retrying_after_delay.is_empty();+ let timeout = if retries_after_delay {+ let remaining = locals.retry_deadline.saturating_duration_since(Instant::now());+ Some(u32::try_from(remaining.as_micros().div_ceil(1000)).unwrap_or(u32::MAX))+ } else if !released_memory_since_last_message {+ Some(IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS)+ } else {+ None+ };+ if self.receive_and_handle_message(&mut locals, timeout) {+ released_memory_since_last_message = false;+ continue;+ }+ if !retries_after_delay {+ release_unused_allocator_memory();+ released_memory_since_last_message = true;+ }+ }+ }++ fn has_transports_needing_attention(&self) -> bool {+ !lock(&self.attention).transports.is_empty()+ }++ fn serve_transports_needing_attention(&self, locals: &mut IoThreadLocals) {+ let mut transports_to_serve = std::mem::take(&mut locals.transports_to_serve);+ {+ let mut attention = lock(&self.attention);+ std::mem::swap(&mut transports_to_serve, &mut attention.transports);+ for transport in &transports_to_serve {+ transport.needs_attention.store(false, Ordering::Relaxed);+ }+ }+ if !locals.transports_retrying_after_delay.is_empty() && Instant::now() >= locals.retry_deadline {+ for transport in std::mem::take(&mut locals.transports_retrying_after_delay) {+ if !transports_to_serve.iter().any(|other| Arc::ptr_eq(other, &transport)) {+ transports_to_serve.push(transport);+ }+ }+ }+ for transport in transports_to_serve.drain(..) {+ self.serve(&transport, locals);+ }+ locals.transports_to_serve = transports_to_serve;+ }++ fn serve(&self, transport: &Arc<Shared>, locals: &mut IoThreadLocals) {+ match transport.do_pending_io() {+ PendingIo::None => {}+ PendingIo::MoreToSendNextTurn => {+ let mut attention = lock(&self.attention);+ if !transport.needs_attention.load(Ordering::Relaxed) {+ transport.needs_attention.store(true, Ordering::Relaxed);+ attention.transports.push(Arc::clone(transport));+ }+ }+ PendingIo::RetryAfterDelay => {+ if locals.transports_retrying_after_delay.is_empty() {+ locals.retry_deadline = Instant::now() + RETRY_DELAY;+ }+ if !locals+ .transports_retrying_after_delay+ .iter()+ .any(|other| Arc::ptr_eq(other, transport))+ {+ locals.transports_retrying_after_delay.push(Arc::clone(transport));+ }+ }+ PendingIo::IoIsOver => self.finish(transport, locals),+ }+ }++ // NB: Waits for one message no longer than the timeout, if there is one, and answers whether one came.+ fn receive_and_handle_message(&self, locals: &mut IoThreadLocals, timeout: Option<u32>) -> bool {+ let received = match timeout {+ Some(timeout) => mach::receive_message_within(&mut locals.receive_buffer, &self.port_set, timeout),+ None => mach::receive_message(&mut locals.receive_buffer, &self.port_set).map(Some),+ };+ let message = match received {+ Ok(Some(message)) => message,+ Ok(None) => return false,+ Err(ReceiveError::Kernel { code, local_port }) => {+ self.handle_failed_receive(code, local_port, locals);+ return true;+ }+ Err(ReceiveError::Malformed { what, local_port }) => {+ eprintln!("TransportMachPort: Rejecting malformed message ({what})");+ if let Some(transport) = self.transport_receiving_on(local_port) {+ transport.mark_peer_eof();+ transport.set_io_thread_state(IoThreadState::Stopped);+ self.finish(&transport, locals);+ }+ return true;+ }+ };++ if message.local_port == self.wakeup_receive_right.name() {+ assert_eq!(message.id, mach::IPC_WAKEUP_MESSAGE_ID);+ return true;+ }+ match self.route(message.local_port) {+ Route::Receive(transport) => {+ if !transport.handle_message_on_io_thread(message) {+ self.finish(&transport, locals);+ }+ }+ Route::SendPossibleNotification(transport) => {+ // NB: Only the kernel can send to the port on which the transport hears that its peer's queue has+ // room.+ transport.handle_send_possible_notification(&message);+ self.serve(&transport, locals);+ }+ Route::OrphanedNotification => {+ if consumes_send_possible_request(&message) {+ let port = lock(&self.registrations).remove(&message.local_port);+ drop(port);+ }+ }+ Route::Unknown => {}+ }+ true+ }++ fn handle_failed_receive(&self, error: KernReturn, port: PortName, locals: &mut IoThreadLocals) {+ eprintln!(+ "TransportMachPort: mach_msg receive failed: {}",+ mach::error_string(error)+ );+ // NB: A message that could not be received whole is gone, and the transport it was for can no longer deliver+ // in order what its peer sends, so its IO is over. That is if the kernel got as far as naming the port it+ // came in on. Any other failure would be one of the port set itself.+ let error = error & !mach::MACH_MSG_MASK;+ assert!(+ error == mach::MACH_RCV_HEADER_ERROR || error == mach::MACH_RCV_BODY_ERROR,+ "the shared Mach IO thread's port set failed"+ );+ let Some(transport) = self.transport_receiving_on(port) else {+ return;+ };+ transport.set_io_thread_state(IoThreadState::Stopped);+ self.finish(&transport, locals);+ }++ fn transport_receiving_on(&self, port: PortName) -> Option<Arc<Shared>> {+ if !mach::is_valid(port) || port == self.wakeup_receive_right.name() {+ return None;+ }+ match self.route(port) {+ Route::Receive(transport) | Route::SendPossibleNotification(transport) => Some(transport),+ Route::OrphanedNotification | Route::Unknown => None,+ }+ }++ // NB: The owner may destroy the transport as soon as this returns.+ fn finish(&self, transport: &Arc<Shared>, locals: &mut IoThreadLocals) {+ // NB: Once the receive right has left the set, nothing more comes in for the transport.+ self.port_set+ .extract_member_named(transport.receive_port_name)+ .expect("a transport's receive right is in the port set until its IO is over");+ self.remove(transport.receive_port_name, transport);+ locals+ .transports_retrying_after_delay+ .retain(|other| !Arc::ptr_eq(other, transport));++ let unsendable = transport.finish_io();+ locals.unsendable.extend(unsendable);++ let mut attention = lock(&self.attention);+ if transport.needs_attention.load(Ordering::Relaxed) {+ attention.transports.retain(|other| !Arc::ptr_eq(other, transport));+ transport.needs_attention.store(false, Ordering::Relaxed);+ }+ transport.io_is_finished.store(true, Ordering::Relaxed);+ self.io_finished.notify_all();}}pub struct TransportMachPort {shared: Arc<Shared>,- io_thread: Option<JoinHandle<()>>,+ // NB: Owned here rather than by the IO thread, which only needs the name, so that it can go to a new owner.+ receive_right: Mutex<Option<MachPort>>,}impl TransportMachPort {@@ -109,275 +1005,338 @@ impl TransportMachPort {}pub fn new(receive_right: MachPort, send_right: MachPort) -> std::io::Result<Self> {- let io = IoThread::new(receive_right, send_right).map_err(KernelError)?;- let shared = Arc::clone(&io.shared);- let io_thread = std::thread::Builder::new()- .name("IPC IO (Mach)".to_string())- .spawn(move || {- // NB: The IO thread only relays messages between the kernel and the owning thread. If it ran below- // that thread, every message would wait on a lower-priority wakeup.- mach::set_current_thread_qos_to_user_interactive();- io.run();- })?;+ Self::with_read_notification_pipe(receive_right, send_right, None)+ }++ /// A transport that writes a byte to the pipe when messages are there to read, or the peer is gone, and nothing+ /// more until `acknowledge_read_notification()`. It has the pipe from the start, so that what arrives before+ /// anything watches the pipe still leaves a byte in it.+ pub fn with_read_notification_pipe(+ receive_right: MachPort,+ send_right: MachPort,+ read_notification_pipe: Option<OwnedFd>,+ ) -> std::io::Result<Self> {+ if let Some(pipe) = &read_notification_pipe {+ mach::disable_sigpipe_on_writes(pipe)?;+ }+ receive_right.raise_queue_limit();+ // NB: The kernel sends MACH_NOTIFY_NO_SENDERS to the receive right once the peer loses its last send right+ // to it. This is how the transport notices that the peer went away.+ receive_right.request_no_senders_notification().map_err(KernelError)?;+ let shared = Arc::new(Shared {+ receive_port_name: receive_right.name(),+ io_thread_state: AtomicU8::new(IoThreadState::Running as u8),+ is_open: AtomicBool::new(true),+ peer_eof: AtomicBool::new(false),+ is_being_transferred: AtomicBool::new(false),+ posting_thread_found_peer_gone: AtomicBool::new(false),+ peer_unreachable_marker_was_sent: AtomicBool::new(false),+ peer_is_unreachable: AtomicBool::new(false),+ stop_was_requested_by_owner: AtomicBool::new(false),+ needs_attention: AtomicBool::new(false),+ io_is_finished: AtomicBool::new(false),+ send: Mutex::new(SendState {+ send_right: Some(send_right),+ backlog: VecDeque::new(),+ sending_is_over: false,+ peer_is_unreachable: false,+ buffer: MessageBuffer::new(0),+ send_possible_notification_port: None,+ send_possible_notification_is_requested: false,+ }),+ sent: Condvar::new(),+ incoming: Mutex::new(Incoming {+ read_notification_pipe: read_notification_pipe.map(File::from),+ ..Incoming::default()+ }),+ incoming_changed: Condvar::new(),+ incoming_message_observer: Mutex::new(None),+ });+ start_shared_io_thread()?+ .add(Registration::Receive(Arc::clone(&shared)), &receive_right)+ .map_err(KernelError)?;Ok(Self {shared,- io_thread: Some(io_thread),+ receive_right: Mutex::new(Some(receive_right)),})}- /// Queues a message for the IO thread to send, or refuses it once the transport has stopped sending.+ /// Sends a message, or queues it behind earlier ones that wait for room in the peer's queue. Refuses it once a stop+ /// is asked for or a send has failed, and refuses one with more attachments than a peer takes.pub fn post_message(&self, bytes: Vec<u8>, attachments: Vec<Attachment>) -> std::io::Result<()> {crate::validate_message_size(bytes.len(), attachments.len())?;- let mut queue = self.shared.lock_send_queue();- if self.shared.state() != IoThreadState::Running {- return Err(std::io::ErrorKind::NotConnected.into());+ self.post_message_with_any_number_of_attachments(OutgoingPayload::Owned(bytes), attachments)+ }++ /// As `post_message()`, but leaves it to the peer to refuse a message with too many attachments, as+ /// `IPC::TransportMachPort` does. Lent bytes are only handed over if the message has to wait behind others.+ pub fn post_message_with_any_number_of_attachments(+ &self,+ payload: OutgoingPayload<'_>,+ attachments: Vec<Attachment>,+ ) -> std::io::Result<()> {+ let ports: Vec<_> = attachments.into_iter().map(Attachment::into_mach_port).collect();+ let mut should_wake_io_thread = false;+ {+ let mut send = lock(&self.shared.send);+ // NB: Once a stop is asked for, nothing new comes in, so that a producer can't keep a graceful close or a+ // transfer from finishing.+ if send.sending_is_over+ || send.peer_is_unreachable+ || self.shared.io_thread_state() != IoThreadState::Running+ {+ return Err(std::io::ErrorKind::NotConnected.into());+ }+ if send.backlog.is_empty() {+ match self.shared.send(&mut send, Outgoing::New { payload, ports }) {+ SendResult::Sent => {}+ SendResult::WouldBlock(message) => {+ send.backlog.push_back(message);+ should_wake_io_thread = true;+ }+ SendResult::PeerGone => {+ self.shared+ .posting_thread_found_peer_gone+ .store(true, Ordering::Release);+ should_wake_io_thread = true;+ }+ }+ } else {+ send.backlog+ .push_back(PendingMessage::unsent(payload.into_owned(), ports));+ }}- let was_empty = queue.pending.is_empty();- queue.pending.push(PendingMessage { bytes, attachments });- drop(queue);- if was_empty {- self.shared.wake_io_thread();+ if should_wake_io_thread {+ shared_io_thread().request_attention(&self.shared);}Ok(())}- /// How many posted messages are still waiting to be sent, so a producer can tell when its peer falls behind.+ /// How many posted messages wait for room in the peer's queue, so a producer can tell when its peer falls behind.pub fn pending_message_count(&self) -> usize {- let queue = self.shared.lock_send_queue();- queue.pending.len() + usize::from(queue.in_progress)+ lock(&self.shared.send).backlog.len()}- /// Waits until every message posted so far is sent, or the transport stops.+ /// Waits until everything posted so far has been handed to the kernel.pub fn flush(&self) {- self.shared.wake_io_thread();- let mut queue = self.shared.lock_send_queue();- while !queue.waiters_released && (!queue.pending.is_empty() || queue.in_progress) {- queue = self.shared.sent.wait(queue).unwrap_or_else(|error| error.into_inner());+ if !self.shared.is_open.load(Ordering::Relaxed) {+ return;+ }+ let mut send = lock(&self.shared.send);+ while !send.sending_is_over && !send.peer_is_unreachable && !send.backlog.is_empty() {+ let (guard, timed_out) = wait_for(&self.shared.sent, send, FLUSH_WAKEUP_REARM_INTERVAL);+ send = guard;+ // NB: The wakeup is best-effort, so re-arm it rather than wait forever if one is ever dropped.+ if timed_out {+ shared_io_thread().request_attention(&self.shared);+ }}}+ /// False once this end is closed or asked to stop, a send has failed, or the peer is gone: whenever a post would+ /// be refused, so that an owner which checks first doesn't post into a refusal.pub fn is_open(&self) -> bool {- self.shared.state() == IoThreadState::Running && !self.shared.incoming.lock().peer_eof+ self.shared.is_open.load(Ordering::Acquire)+ && self.shared.io_thread_state() == IoThreadState::Running+ && !self.shared.peer_is_unreachable.load(Ordering::Acquire)+ && !self.shared.peer_eof.load(Ordering::Acquire)}/// Waits for the next message, or returns `None` once the peer is gone and every message it sent was taken.pub fn receive(&self) -> Option<ReceivedMessage> {- self.shared.incoming.receive()+ let mut incoming = lock(&self.shared.incoming);+ loop {+ if let Some(message) = incoming.messages.pop_front() {+ return Some(message);+ }+ if self.shared.peer_eof.load(Ordering::Acquire) || incoming.local_io_is_over {+ return None;+ }+ incoming = wait(&self.shared.incoming_changed, incoming);+ }}- /// Sends what is queued, then stops, which tells the peer that this end is gone.- pub fn close_after_sending_all_pending_messages(&mut self) {- self.stop(IoThreadState::SendPendingMessagesAndStop);+ /// Takes every message that has arrived, and whether the peer was gone as they were taken. Later arrivals can't+ /// be skipped by reporting the peer gone.+ pub fn take_incoming(&self) -> (Vec<ReceivedMessage>, bool) {+ let mut incoming = lock(&self.shared.incoming);+ let messages = std::mem::take(&mut incoming.messages).into();+ (messages, self.shared.peer_eof.load(Ordering::Acquire))}- pub fn close(&mut self) {- self.stop(IoThreadState::Stopped);+ /// Waits until there is a message to take, the peer is gone, the wait is interrupted, or the deadline passes.+ pub fn wait_until_readable(&self, deadline: Option<MonotonicDeadline>) {+ let mut incoming = lock(&self.shared.incoming);+ while incoming.messages.is_empty()+ && !self.shared.peer_eof.load(Ordering::Acquire)+ && !incoming.local_io_is_over+ && !incoming.wait_until_readable_interrupted+ {+ match deadline {+ None => incoming = wait(&self.shared.incoming_changed, incoming),+ Some(deadline) => {+ let Some(remaining) = deadline.remaining() else {+ break;+ };+ incoming = wait_for(&self.shared.incoming_changed, incoming, remaining).0;+ }+ }+ }+ incoming.wait_until_readable_interrupted = false;}- fn stop(&mut self, state: IoThreadState) {- let Some(io_thread) = self.io_thread.take() else {+ /// Makes `wait_until_readable()` return, even with nothing to read, now or if none is under way, the next time.+ /// Any thread may call this.+ pub fn interrupt_wait_until_readable(&self) {+ lock(&self.shared.incoming).wait_until_readable_interrupted = true;+ self.shared.incoming_changed.notify_all();+ }++ /// Waits until everything the peer has already sent has been taken into the incoming queue.+ pub fn wait_until_incoming_is_current(&self) {+ let receive_right = lock(&self.receive_right);+ let Some(receive_right) = receive_right.as_ref() else {return;};- self.shared.set_state(state);- self.shared.wake_io_thread();- let _ = io_thread.join();+ let mut incoming = lock(&self.shared.incoming);+ if self.shared.peer_eof.load(Ordering::Acquire) || self.shared.io_thread_state() != IoThreadState::Running {+ return;+ }+ // NB: A marker on the receive right follows every message sent to it before, including one the IO thread+ // has taken off the port but not queued yet. A send-once right keeps the peer's departure visible, and+ // bypasses the queue limit, so sending under the incoming lock can't wait on a full queue.+ let barrier_right = receive_right+ .make_send_once_right()+ .expect("a send-once right for the receive barrier");+ let result =+ mach::send_header_only_message_through_send_once_right(barrier_right, mach::IPC_RECEIVE_BARRIER_MESSAGE_ID);+ assert_eq!(result, mach::MACH_MSG_SUCCESS, "the receive barrier is sent");+ incoming.receive_barriers_sent += 1;+ let barrier = incoming.receive_barriers_sent;+ while !self.shared.peer_eof.load(Ordering::Acquire)+ && self.shared.io_thread_state() == IoThreadState::Running+ && incoming.receive_barriers_received < barrier+ {+ incoming = wait(&self.shared.incoming_changed, incoming);+ }}-}-impl Drop for TransportMachPort {- fn drop(&mut self) {- self.close();+ /// Sets what the IO thread shows every message that arrives, before the owner gets to see it, and empty bytes once+ /// the peer is gone. It runs while the IO thread holds a lock, so it should only have a look. Once this returns,+ /// the observer it gives back is no longer running.+ pub fn set_incoming_message_observer(+ &self,+ observer: Option<IncomingMessageObserver>,+ ) -> Option<IncomingMessageObserver> {+ std::mem::replace(&mut *lock(&self.shared.incoming_message_observer), observer)}-}--struct IoThread {- shared: Arc<Shared>,- receive_right: MachPort,- send_right: Option<MachPort>,- port_set: MachPort,- wakeup_receive_right: MachPort,-}--impl IoThread {- fn new(receive_right: MachPort, send_right: MachPort) -> Result<Self, mach::KernReturn> {- let port_set = MachPort::allocate_port_set()?;- port_set.insert_member(&receive_right)?;- let wakeup_receive_right = MachPort::allocate_receive_right()?;- let wakeup_send_right = wakeup_receive_right.make_send_right()?;- port_set.insert_member(&wakeup_receive_right)?;- receive_right.raise_queue_limit();- receive_right.request_no_senders_notification()?;-- let shared = Arc::new(Shared {- state: AtomicU8::new(IoThreadState::Running as u8),- send_queue: Mutex::default(),- sent: Condvar::new(),- incoming: IncomingQueue::default(),- wakeup_send_right,- });- Ok(Self {- shared,- receive_right,- send_right: Some(send_right),- port_set,- wakeup_receive_right,- })+ /// Lets the transport write to its read-notification pipe again, once the owner has drained it.+ pub fn acknowledge_read_notification(&self) {+ lock(&self.shared.incoming).read_notification_pending = false;}- fn run(mut self) {- let mut receive_buffer = MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE);- let mut send_buffer = MessageBuffer::new(4096);- loop {- if self.shared.state() == IoThreadState::Stopped {- break;- }+ /// Writes to the read-notification pipe if there is something to read, or the peer is gone, and no byte is+ /// already pending.+ pub fn schedule_read_notification_if_readable(&self) {+ let mut incoming = lock(&self.shared.incoming);+ if !incoming.messages.is_empty() || self.shared.peer_eof.load(Ordering::Acquire) {+ Shared::schedule_read_notification(&mut incoming);+ }+ }- let messages_to_send = {- let mut queue = self.shared.lock_send_queue();- let messages = std::mem::take(&mut queue.pending);- if !messages.is_empty() {- queue.in_progress = true;- }- messages- };- let sent_any = !messages_to_send.is_empty();- for message in messages_to_send {- if self.shared.state() == IoThreadState::Stopped {- break;- }- self.send(&mut send_buffer, &mut receive_buffer, message);- }- if sent_any {- self.shared.lock_send_queue().in_progress = false;- self.shared.sent.notify_all();- }+ /// Sends what is queued, then stops, which tells the peer that this end is gone.+ pub fn close_after_sending_all_pending_messages(&self) {+ self.stop(IoThreadState::SendPendingMessagesAndStop);+ self.shared.is_open.store(false, Ordering::Release);+ self.release_send_right_to_peer();+ self.release_receive_right();+ }- if self.shared.state() == IoThreadState::Stopped {- break;- }- // NB: Waiting for a send to go through takes in what arrived meanwhile, which may include the wakeups for- // messages posted since this thread took the queue.- if !self.shared.lock_send_queue().pending.is_empty() {- continue;- }- if self.shared.state() == IoThreadState::SendPendingMessagesAndStop {- self.shared.set_state(IoThreadState::Stopped);- break;- }+ pub fn close(&self) {+ self.shared.is_open.store(false, Ordering::Release);+ self.stop(IoThreadState::Stopped);+ self.release_send_right_to_peer();+ self.release_receive_right();+ }- let received = mach::receive_message(&mut receive_buffer, &self.port_set);- if !self.handle_receive_result(received) {- break;- }- }+ /// Sends what is queued, stops, and hands both rights over for another transport to take this end's place.+ pub fn release_for_transfer(&self) -> std::io::Result<MachPortPair> {+ self.shared.is_being_transferred.store(true, Ordering::Release);+ self.stop(IoThreadState::SendPendingMessagesAndStop);+ self.shared.is_open.store(false, Ordering::Release);- self.shared.set_state(IoThreadState::Stopped);- {- let mut queue = self.shared.lock_send_queue();- queue.waiters_released = true;- queue.pending.clear();- }- self.shared.sent.notify_all();- // NB: As closing a socket does, dropping the send right tells the peer that this end is gone.- self.send_right = None;- self.shared.incoming.mark_peer_eof();- let _ = self.port_set.extract_member(&self.receive_right);+ let receive_right = lock(&self.receive_right)+ .take()+ .ok_or(std::io::ErrorKind::NotConnected)?;+ // NB: Otherwise this end would still hear of the peer going away, on a port it no longer owns.+ receive_right.cancel_no_senders_notification().map_err(KernelError)?;+ let send_right = lock(&self.shared.send)+ .send_right+ .take()+ .ok_or(std::io::ErrorKind::NotConnected)?;+ Ok(MachPortPair {+ receive_right,+ send_right,+ })}- fn send(&mut self, send_buffer: &mut MessageBuffer, receive_buffer: &mut MessageBuffer, message: PendingMessage) {- let Some(send_right) = &self.send_right else {- return;- };- let ports = message- .attachments- .into_iter()- .map(Attachment::into_mach_port)- .collect();- let result = mach::send_data_message(send_buffer, send_right, &message.bytes, ports, || {- // NB: The peer may be waiting to send to this side while this side waits for room in its queue, so take- // in what it sent before retrying.- if !self.receive_queued_messages(receive_buffer) {- self.shared.set_state(IoThreadState::Stopped);- }- self.shared.should_retry_send()- });- if result != mach::MACH_MSG_SUCCESS {- eprintln!("TransportMachPort: send failed: {}", mach::error_string(result));- self.send_right = None;- self.shared.set_state(IoThreadState::Stopped);- }+ // NB: As closing a socket does, closing the transport tells the peer: its receive right gets MACH_NOTIFY_NO_SENDERS+ // once this send right is gone. Sending is over by now, as IO has stopped.+ fn release_send_right_to_peer(&self) {+ let send_right = lock(&self.shared.send).send_right.take();+ drop(send_right);}- // NB: Takes in every message that is already queued, and returns whether to go on.- fn receive_queued_messages(&self, buffer: &mut MessageBuffer) -> bool {- while let Some(received) = mach::try_receive_message(buffer, &self.port_set).transpose() {- if !self.handle_receive_result(received) {- return false;- }- }- true+ // NB: Nothing takes messages off the port once IO has stopped. Destroying it makes the peer's sends fail, rather+ // than leave the peer waiting for room in a full queue that nobody drains. What was already taken off the+ // port can still be read.+ fn release_receive_right(&self) {+ let receive_right = lock(&self.receive_right).take();+ drop(receive_right);}- // NB: Handles the outcome of receiving from the port set, and returns whether to go on.- fn handle_receive_result(&self, received: Result<mach::ReceivedMessage, ReceiveError>) -> bool {- match received {- Ok(message) if message.local_port == self.wakeup_receive_right.name() => true,- Ok(message) => self.handle_received(message),- Err(ReceiveError::Kernel(error)) => {- eprintln!(- "TransportMachPort: mach_msg receive failed: {}",- mach::error_string(error)- );- false- }- Err(ReceiveError::Malformed(what)) => {- eprintln!("TransportMachPort: Refusing a message with a malformed {what}");- false+ fn stop(&self, desired_state: IoThreadState) {+ self.shared.stop_was_requested_by_owner.store(true, Ordering::Release);+ // NB: The IO thread may already have stopped on its own, as when the peer hung up. Stopped is final, so it is+ // never replaced by a new stop request.+ let mut state = self.shared.io_thread_state.load(Ordering::Acquire);+ while state != IoThreadState::Stopped as u8 {+ match self.shared.io_thread_state.compare_exchange(+ state,+ desired_state as u8,+ Ordering::AcqRel,+ Ordering::Acquire,+ ) {+ Ok(_) => break,+ Err(current) => state = current,}}+ let io_thread = shared_io_thread();+ io_thread.request_attention(&self.shared);+ io_thread.wait_until_io_is_finished(&self.shared);++ // NB: What was left unsent goes here rather than on the IO thread, which all transports share, as releasing+ // the rights of a long backlog takes a while.+ let backlog = std::mem::take(&mut lock(&self.shared.send).backlog);+ drop(backlog);}+}- // NB: Handles a message that arrived on the receive right, and returns whether to go on.- fn handle_received(&self, message: mach::ReceivedMessage) -> bool {- match message.id {- mach::MACH_NOTIFY_NO_SENDERS => {- self.shared.incoming.mark_peer_eof();- true- }- mach::MACH_NOTIFY_SEND_ONCE | mach::IPC_RECEIVE_BARRIER_MESSAGE_ID => true,- mach::IPC_DATA_MESSAGE_ID | mach::IPC_INLINE_DATA_MESSAGE_ID => {- let Some((bytes, ports)) = message.data else {- return false;- };- if ports.len() > MAX_MESSAGE_ATTACHMENT_COUNT {- eprintln!("TransportMachPort: Refusing a message with {} attachments", ports.len());- return false;- }- if bytes.bytes().is_empty() && ports.is_empty() {- return true;- }- let attachments = ports- .into_iter()- .map(|(port, disposition)| Attachment::from_mach_port(port, disposition))- .collect();- let message = ReceivedMessage { bytes, attachments };- self.shared.incoming.push([message]);- true- }- id => {- eprintln!("TransportMachPort: Refusing a message with ID {id:#x}");- false- }- }+impl Drop for TransportMachPort {+ fn drop(&mut self) {+ self.stop(IoThreadState::Stopped);+ self.release_send_right_to_peer();+ // NB: The observer goes here, on the owner's thread, rather than wherever the last reference to the shared state+ // happens to be dropped.+ drop(self.set_incoming_message_observer(None));}}#[cfg(test)]mod tests {use super::*;- use crate::mach::{PayloadBytes, PortRight};use std::os::fd::OwnedFd;fn paired() -> (TransportMachPort, TransportMachPort) {@@ -385,103 +1344,6 @@ mod tests {(a, TransportMachPort::from_handle(handle).unwrap())}- #[test]- fn graceful_close_retries_a_full_queue() {- let receive = MachPort::allocate_receive_right().unwrap();- let send = receive.make_send_right().unwrap();- let ours = MachPort::allocate_receive_right().unwrap();- let io = IoThread::new(ours, send).unwrap();- let destination = io.send_right.as_ref().unwrap();- loop {- match mach::send_header_only_message(destination, mach::IPC_WAKEUP_MESSAGE_ID, Some(0)) {- mach::MACH_MSG_SUCCESS => (),- mach::MACH_SEND_TIMED_OUT => break,- error => panic!("queue fill failed: {}", mach::error_string(error)),- }- }- io.shared.set_state(IoThreadState::SendPendingMessagesAndStop);- let mut receive_buffer = MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE);- let mut retried = false;- assert_eq!(- mach::send_data_message(&mut MessageBuffer::new(4096), destination, &[7], vec![], || {- retried = true;- let keep_sending = io.shared.should_retry_send();- mach::receive_message(&mut receive_buffer, &receive).unwrap();- keep_sending- }),- mach::MACH_MSG_SUCCESS- );- assert!(retried);- loop {- let message = mach::receive_message(&mut receive_buffer, &receive).unwrap();- if let Some((payload, _)) = message.data {- assert_eq!(payload.bytes(), [7]);- break;- }- }- io.shared.set_state(IoThreadState::Stopped);- assert!(!io.shared.should_retry_send());- }-- #[test]- fn no_senders_keeps_pending_replies() {- let (io, peer) = {- let ours = MachPort::allocate_receive_right().unwrap();- let peer = MachPort::allocate_receive_right().unwrap();- (IoThread::new(ours, peer.make_send_right().unwrap()).unwrap(), peer)- };- io.shared.lock_send_queue().pending.push(PendingMessage {- bytes: vec![7],- attachments: vec![],- });- assert!(io.handle_received(mach::ReceivedMessage {- id: mach::MACH_NOTIFY_NO_SENDERS,- local_port: io.receive_right.name(),- data: None,- }));- assert!(io.shared.incoming.lock().peer_eof);- assert!(io.shared.state() == IoThreadState::Running);- io.shared.set_state(IoThreadState::SendPendingMessagesAndStop);- io.run();- let message = mach::receive_message(&mut MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE), &peer).unwrap();- assert_eq!(message.data.unwrap().0.bytes(), [7]);- }-- #[test]- fn send_failure_leaves_eof_to_the_io_thread() {- let receive = MachPort::allocate_receive_right().unwrap();- let invalid_send = MachPort::adopt(mach::MACH_PORT_NULL, PortRight::Send);- let mut io = IoThread::new(receive, invalid_send).unwrap();- let transport = TransportMachPort {- shared: Arc::clone(&io.shared),- io_thread: None,- };- io.send(- &mut MessageBuffer::new(4096),- &mut MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE),- PendingMessage {- bytes: vec![1],- attachments: Vec::new(),- },- );- assert!(io.shared.state() == IoThreadState::Stopped);- assert!(!io.shared.incoming.lock().peer_eof);- assert!(io.handle_received(mach::ReceivedMessage {- id: mach::IPC_INLINE_DATA_MESSAGE_ID,- local_port: io.receive_right.name(),- data: Some((PayloadBytes::Inline(vec![7]), Vec::new())),- }));- io.run();- assert_eq!(transport.receive().unwrap().bytes(), [7]);- assert!(transport.receive().is_none());- assert_eq!(- transport.post_message(vec![2], Vec::new()).unwrap_err().kind(),- std::io::ErrorKind::NotConnected- );- assert!(transport.shared.lock_send_queue().pending.is_empty());- assert!(transport.receive().is_none());- }-#[test]fn messages_arrive_in_order() {let (a, b) = paired();@@ -507,47 +1369,6 @@ mod tests {}}- #[test]- fn a_burst_of_posts_sends_one_wakeup() {- let receive = MachPort::allocate_receive_right().unwrap();- let peer = MachPort::allocate_receive_right().unwrap();- let io = IoThread::new(receive, peer.make_send_right().unwrap()).unwrap();- io.wakeup_receive_right.raise_queue_limit();- let transport = TransportMachPort {- shared: Arc::clone(&io.shared),- io_thread: None,- };- let mut buffer = MessageBuffer::new(mach::DEFAULT_RECEIVE_BUFFER_SIZE);- for _ in 0..2 {- for number in 0..100u32 {- transport- .post_message(number.to_ne_bytes().to_vec(), Vec::new())- .unwrap();- }- assert_eq!(- mach::send_header_only_message(- &io.shared.wakeup_send_right,- mach::IPC_RECEIVE_BARRIER_MESSAGE_ID,- Some(0),- ),- mach::MACH_MSG_SUCCESS- );- assert_eq!(- mach::receive_message(&mut buffer, &io.wakeup_receive_right).unwrap().id,- mach::IPC_WAKEUP_MESSAGE_ID- );- assert_eq!(- mach::receive_message(&mut buffer, &io.wakeup_receive_right).unwrap().id,- mach::IPC_RECEIVE_BARRIER_MESSAGE_ID- );- let messages = std::mem::take(&mut transport.shared.lock_send_queue().pending);- assert_eq!(messages.len(), 100);- for (number, message) in messages.into_iter().enumerate() {- assert_eq!(message.bytes, (number as u32).to_ne_bytes());- }- }- }-#[test]fn large_messages_go_out_of_line() {let (a, b) = paired();@@ -573,9 +1394,118 @@ mod tests {assert_eq!(buffer, "ok");}+ #[test]+ fn a_failed_send_refuses_later_posts_and_keeps_what_arrived() {+ let receive_right = MachPort::allocate_receive_right().unwrap();+ let to_this_end = receive_right.make_send_right().unwrap();+ let peer_receive_right = MachPort::allocate_receive_right().unwrap();+ let transport = TransportMachPort::new(receive_right, peer_receive_right.make_send_right().unwrap()).unwrap();+ assert!(matches!(+ mach::send_data_message(&mut MessageBuffer::new(0), &to_this_end, &[7], Vec::new()),+ SendOutcome::Sent+ ));+ drop(peer_receive_right);++ transport.post_message(vec![1], Vec::new()).unwrap();+ assert_eq!(+ transport.post_message(vec![2], Vec::new()).unwrap_err().kind(),+ std::io::ErrorKind::NotConnected+ );+ assert_eq!(transport.receive().unwrap().bytes(), [7]);+ assert!(transport.receive().is_none());+ assert!(!transport.is_open());+ }++ #[test]+ fn a_backlog_that_can_no_longer_be_sent_lets_go_of_its_attachments() {+ let peer_receive_right = MachPort::allocate_receive_right().unwrap();+ let transport = TransportMachPort::new(+ MachPort::allocate_receive_right().unwrap(),+ peer_receive_right.make_send_right().unwrap(),+ )+ .unwrap();+ let (mut reader, writer) = std::io::pipe().unwrap();+ // NB: The peer never reads, so its queue fills, and later messages wait in the backlog with their files.+ while transport.pending_message_count() < 3 {+ let attachment = Attachment::from_fd(OwnedFd::from(writer.try_clone().unwrap())).unwrap();+ transport.post_message(vec![1], vec![attachment]).unwrap();+ }+ drop(writer);+ drop(peer_receive_right);++ // NB: Every copy of the writer is gone once the backlog lets go of its files, without the owner doing anything.+ let (done, finished) = std::sync::mpsc::channel();+ std::thread::spawn(move || done.send(std::io::Read::read(&mut reader, &mut [0]).unwrap()));+ assert_eq!(finished.recv_timeout(Duration::from_secs(10)), Ok(0));+ assert_eq!(transport.pending_message_count(), 0);+ }++ #[test]+ fn nothing_is_taken_from_a_peer_after_it_is_found_unreachable() {+ let receive_right = MachPort::allocate_receive_right().unwrap();+ let to_this_end = receive_right.make_send_right().unwrap();+ let peer_receive_right = MachPort::allocate_receive_right().unwrap();+ let transport = TransportMachPort::new(receive_right, peer_receive_right.make_send_right().unwrap()).unwrap();+ // NB: The peer lets go of its receive right, but keeps sending to this end.+ assert!(matches!(+ mach::send_data_message(&mut MessageBuffer::new(0), &to_this_end, &[7], Vec::new()),+ SendOutcome::Sent+ ));+ drop(peer_receive_right);+ transport.post_message(vec![1], Vec::new()).unwrap();+ assert_eq!(transport.receive().unwrap().bytes(), [7]);+ assert!(transport.receive().is_none());++ assert!(matches!(+ mach::send_data_message(&mut MessageBuffer::new(0), &to_this_end, &[8], Vec::new()),+ SendOutcome::Sent+ ));+ std::thread::sleep(Duration::from_millis(50));+ assert!(transport.receive().is_none());+ }++ #[test]+ fn a_backlog_left_by_io_that_stopped_on_its_own_lets_go_of_its_attachments() {+ let receive_right = MachPort::allocate_receive_right().unwrap();+ let to_this_end = receive_right.make_send_right().unwrap();+ let peer_receive_right = MachPort::allocate_receive_right().unwrap();+ let transport = TransportMachPort::new(receive_right, peer_receive_right.make_send_right().unwrap()).unwrap();+ let (mut reader, writer) = std::io::pipe().unwrap();+ // NB: The peer never reads, so its queue fills, and later messages wait in the backlog with their files.+ while transport.pending_message_count() < 3 {+ let attachment = Attachment::from_fd(OwnedFd::from(writer.try_clone().unwrap())).unwrap();+ transport.post_message(vec![1], vec![attachment]).unwrap();+ }+ drop(writer);+ // NB: A message the transport refuses stops its IO, and the peer's queue keeps the messages that reached it.+ assert_eq!(+ mach::send_header_only_message(&to_this_end, 0x1234, Some(0)),+ mach::MACH_MSG_SUCCESS+ );+ let (done, finished) = std::sync::mpsc::channel();+ let reader_thread = std::thread::spawn(move || done.send(std::io::Read::read(&mut reader, &mut [0]).unwrap()));+ drop(peer_receive_right);+ assert_eq!(finished.recv_timeout(Duration::from_secs(10)), Ok(0));+ reader_thread.join().unwrap().unwrap();+ assert!(!transport.is_open());+ }++ #[test]+ fn a_reader_of_an_endpoint_that_is_handed_over_stops_waiting() {+ let (_a, b) = paired();+ std::thread::scope(|scope| {+ let reader = scope.spawn(|| b.receive());+ // NB: The reader may or may not be waiting yet; either way it must not wait for good.+ std::thread::sleep(Duration::from_millis(10));+ let handle = b.release_for_transfer().unwrap();+ assert!(reader.join().unwrap().is_none());+ drop(handle);+ });+ }+#[test]fn the_peer_closing_ends_the_messages() {- let (mut a, b) = paired();+ let (a, b) = paired();a.post_message(vec![7], Vec::new()).unwrap();a.close_after_sending_all_pending_messages();assert_eq!(b.receive().unwrap().bytes(), [7]);diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex 43c9a66ae73..abf62729040 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -34,6 +34,9 @@ ALLOWED = {"AK/Rust/src/waiter_list.rs:LISTS": "only libjs_rust and libwasm_engine use it, which are in one library of a process, so they share a copy; a caller in another library needs the state moved to C++","Libraries/LibCompositing/Rust/src/test_stubs.rs:NEXT": "test stub for LibGfx's C++ counters, in the cargo test binary that has no C++ side","Libraries/LibCompositing/Rust/src/display_list/replay.rs:WARM_REPLAY_SCRATCH_STORAGE": "per-thread replay scratch; a second copy costs memory, never an answer",+ "Libraries/LibIPC/Rust/src/transport.rs:IO_THREAD": "the IO thread of the Mach transports that one copy of the crate makes; a transport stays with the thread of its copy, so a second copy that makes transports, as a test binary that also links LibIPC does, only costs a second thread. Its claims on send-possible requests are per copy too, which holds while no two copies send to the same port: a shipped process makes transports through one copy, and the test binary's two copies send to each other",+ "Libraries/LibIPC/Rust/src/transport.rs:STARTING": "serializes the start of IO_THREAD's thread, and is per copy with it",+ "Libraries/LibIPC/Rust/src/transport.rs:IS_SHARED_IO_THREAD": "per-thread marker of the IO thread of IO_THREAD's copy, which only that copy's code reads","Libraries/LibJS/Flap/src/low_ir/lowering.rs:LABELS": "per-thread scratch buffer; a second copy costs memory, never an answer","Libraries/LibJS/JIT/Rust/src/asm/x86_64/sse.rs:FEATURES": "immutable CPU/OS feature cache; each copy computes the same supported instructions","Libraries/LibJS/JIT/Rust/src/codegen/tests.rs:REGION": "the fake heap region of JIT unit tests, in the cargo test binary that has no runtime",