Skip to content

Truly independent web browser

LibIPC: Add Rust codecs for the IPC wire format

Andreas Kling3c3cc093677f
diff --git a/Cargo.lock b/Cargo.lock
index f220ed74a89..04ff171aafe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -887,6 +887,13 @@ dependencies = [
"rustc-demangle",
]
+[[package]]
+name = "libipc_rust"
+version = "0.1.0"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "libjs_abi"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index e48cbdf0f59..3560d94edfc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,7 @@ members = [
"Libraries/LibCompositing/Rust",
"Libraries/LibGfx/Rust",
"Libraries/LibImageDecoders/Rust",
+ "Libraries/LibIPC/Rust",
"Libraries/LibJS/ABI",
"Libraries/LibJS/JIT/Rust",
"Libraries/LibJS/Rust",
diff --git a/Libraries/LibIPC/Rust/Cargo.toml b/Libraries/LibIPC/Rust/Cargo.toml
new file mode 100644
index 00000000000..9c484fc39f8
--- /dev/null
+++ b/Libraries/LibIPC/Rust/Cargo.toml
@@ -0,0 +1,14 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+[package]
+name = "libipc_rust"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+libc = "0.2"
+
+[lints]
+workspace = true
diff --git a/Libraries/LibIPC/Rust/src/attachment.rs b/Libraries/LibIPC/Rust/src/attachment.rs
new file mode 100644
index 00000000000..bbd1a5ae1e3
--- /dev/null
+++ b/Libraries/LibIPC/Rust/src/attachment.rs
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What a message carries besides its bytes: a Mach port right on Apple platforms, and a file descriptor elsewhere.
+
+use std::os::fd::OwnedFd;
+
+#[cfg(target_vendor = "apple")]
+use crate::mach::{self, MachPort};
+
+#[cfg(target_vendor = "apple")]
+#[derive(Debug)]
+pub struct Attachment {
+ port: MachPort,
+ disposition: u32,
+}
+
+#[cfg(target_vendor = "apple")]
+impl Attachment {
+ /// An attachment moving a right in a message, with the disposition the right is moved with.
+ pub fn from_mach_port(port: MachPort, disposition: u32) -> Self {
+ Self { port, disposition }
+ }
+
+ pub fn from_fd(fd: OwnedFd) -> std::io::Result<Self> {
+ Ok(Self::from_mach_port(
+ mach::file_port_from_fd(fd)?,
+ mach::MACH_MSG_TYPE_MOVE_SEND,
+ ))
+ }
+
+ pub fn into_fd(self) -> std::io::Result<OwnedFd> {
+ mach::fd_from_file_port(self.port)
+ }
+
+ pub fn into_mach_port(self) -> (MachPort, u32) {
+ (self.port, self.disposition)
+ }
+}
+
+#[cfg(not(target_vendor = "apple"))]
+#[derive(Debug)]
+pub struct Attachment {
+ fd: OwnedFd,
+}
+
+#[cfg(not(target_vendor = "apple"))]
+impl Attachment {
+ pub fn from_fd(fd: OwnedFd) -> std::io::Result<Self> {
+ Ok(Self { fd })
+ }
+
+ pub fn into_fd(self) -> std::io::Result<OwnedFd> {
+ Ok(self.fd)
+ }
+
+ pub fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
+ std::os::fd::AsFd::as_fd(&self.fd)
+ }
+}
+
+#[cfg(not(target_vendor = "apple"))]
+impl From<OwnedFd> for Attachment {
+ fn from(fd: OwnedFd) -> Self {
+ Self { fd }
+ }
+}
diff --git a/Libraries/LibIPC/Rust/src/lib.rs b/Libraries/LibIPC/Rust/src/lib.rs
new file mode 100644
index 00000000000..8fbac8ce3de
--- /dev/null
+++ b/Libraries/LibIPC/Rust/src/lib.rs
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! LibIPC's wire format, transports and message endpoints, for Rust processes and services that speak with C++ ones.
+//!
+//! Everything but the operating system interface of the transports is safe Rust.
+
+#![deny(unsafe_code)]
+
+pub mod attachment;
+pub mod wire;
+
+/// The most attachments a message may carry, as `IPC::MAX_MESSAGE_FD_COUNT`.
+pub const MAX_MESSAGE_ATTACHMENT_COUNT: usize = 16000;
+
+/// The largest payload a socket frame or Mach descriptor can represent.
+pub const MAX_MESSAGE_PAYLOAD_SIZE: usize = u32::MAX as usize;
+
+#[cfg(target_vendor = "apple")]
+pub mod mach;
+
+pub use attachment::Attachment;
+pub use wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, EndpointMessage};
diff --git a/Libraries/LibIPC/Rust/src/mach.rs b/Libraries/LibIPC/Rust/src/mach.rs
new file mode 100644
index 00000000000..e61da5d91e6
--- /dev/null
+++ b/Libraries/LibIPC/Rust/src/mach.rs
@@ -0,0 +1,1119 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The Mach interface that the transport uses: port rights, messages and file ports.
+//!
+//! This is one of the crate's two islands of unsafe code. Everything outside it handles ports through `MachPort`,
+//! which owns one right and gives it back to the kernel when dropped.
+
+#![allow(unsafe_code)]
+
+use std::ffi::{CStr, c_char, c_int, c_void};
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+
+pub type PortName = u32;
+pub type KernReturn = i32;
+
+pub const MACH_PORT_NULL: PortName = 0;
+pub const MACH_PORT_DEAD: PortName = !0;
+
+pub const KERN_SUCCESS: KernReturn = 0;
+
+pub const MACH_MSG_TYPE_MOVE_RECEIVE: u32 = 16;
+pub const MACH_MSG_TYPE_MOVE_SEND: u32 = 17;
+pub const MACH_MSG_TYPE_MOVE_SEND_ONCE: u32 = 18;
+pub const MACH_MSG_TYPE_COPY_SEND: u32 = 19;
+pub const MACH_MSG_TYPE_MAKE_SEND: u32 = 20;
+pub const MACH_MSG_TYPE_MAKE_SEND_ONCE: u32 = 21;
+
+pub const MACH_MSGH_BITS_COMPLEX: u32 = 0x8000_0000;
+
+pub const MACH_MSG_PORT_DESCRIPTOR: u8 = 0;
+pub const MACH_MSG_OOL_DESCRIPTOR: u8 = 1;
+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;
+pub const MACH_SEND_TIMEOUT: i32 = 0x10;
+
+pub const MACH_MSG_SUCCESS: KernReturn = 0;
+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;
+const MACH_SEND_INVALID_VOUCHER: KernReturn = 0x1000_0005;
+const MACH_SEND_MSG_TOO_SMALL: KernReturn = 0x1000_0008;
+const MACH_SEND_INVALID_REPLY: KernReturn = 0x1000_0009;
+pub const MACH_SEND_INVALID_RIGHT: KernReturn = 0x1000_000a;
+const MACH_SEND_INVALID_NOTIFY: KernReturn = 0x1000_000b;
+pub const MACH_SEND_INVALID_MEMORY: KernReturn = 0x1000_000c;
+pub const MACH_SEND_NO_BUFFER: KernReturn = 0x1000_000d;
+pub const MACH_SEND_TOO_LARGE: KernReturn = 0x1000_000e;
+pub const MACH_SEND_INVALID_TYPE: KernReturn = 0x1000_000f;
+const MACH_SEND_INVALID_HEADER: KernReturn = 0x1000_0010;
+const MACH_SEND_INVALID_TRAILER: KernReturn = 0x1000_0011;
+const MACH_SEND_INVALID_CONTEXT: KernReturn = 0x1000_0012;
+const MACH_SEND_INVALID_OPTIONS: KernReturn = 0x1000_0013;
+const MACH_SEND_NO_GRANT_DEST: KernReturn = 0x1000_0016;
+const MACH_SEND_MSG_FILTERED: KernReturn = 0x1000_0017;
+pub const MACH_RCV_TOO_LARGE: KernReturn = 0x1000_4004;
+
+pub const MACH_MSG_TIMEOUT_NONE: u32 = 0;
+
+pub const MACH_NOTIFY_NO_SENDERS: i32 = 0o106;
+pub const MACH_NOTIFY_SEND_ONCE: i32 = 0o107;
+
+const MACH_PORT_RIGHT_RECEIVE: u32 = 1;
+const MACH_PORT_RIGHT_PORT_SET: u32 = 3;
+
+const MACH_PORT_LIMITS_INFO: i32 = 1;
+const MACH_PORT_LIMITS_INFO_COUNT: u32 = 1;
+const MACH_PORT_QLIMIT_MAX: i32 = 1024;
+
+pub fn msgh_bits(remote: u32, local: u32) -> u32 {
+ remote | (local << 8)
+}
+
+pub fn is_valid(name: PortName) -> bool {
+ name != MACH_PORT_NULL && name != MACH_PORT_DEAD
+}
+
+/// `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;
+
+ fn mach_msg(
+ message: *mut c_void,
+ option: i32,
+ send_size: u32,
+ receive_size: u32,
+ receive_name: PortName,
+ timeout: u32,
+ notify: PortName,
+ ) -> KernReturn;
+ fn mach_msg_destroy(message: *mut c_void);
+ fn mach_port_allocate(task: PortName, right: u32, name: *mut PortName) -> KernReturn;
+ fn mach_port_insert_right(task: PortName, name: PortName, right: PortName, right_type: u32) -> KernReturn;
+ fn mach_port_deallocate(task: PortName, name: PortName) -> KernReturn;
+ fn mach_port_mod_refs(task: PortName, name: PortName, right: u32, delta: i32) -> KernReturn;
+ fn mach_port_insert_member(task: PortName, member: PortName, set: PortName) -> KernReturn;
+ fn mach_port_extract_member(task: PortName, member: PortName, set: PortName) -> KernReturn;
+ fn mach_port_request_notification(
+ task: PortName,
+ name: PortName,
+ message_id: i32,
+ sync: u32,
+ notify: PortName,
+ notify_type: u32,
+ previous: *mut PortName,
+ ) -> KernReturn;
+ fn mach_port_set_attributes(task: PortName, name: PortName, flavor: i32, info: *mut i32, count: 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;
+ fn fileport_makefd(port: PortName) -> c_int;
+}
+
+fn task_self() -> PortName {
+ // NB: The kernel sets up mach_task_self_ before any code runs, and it does not change afterwards.
+ unsafe { mach_task_self_ }
+}
+
+pub fn error_string(error: KernReturn) -> String {
+ // NB: mach_error_string() returns a pointer to a static, NUL-terminated string for any value.
+ unsafe { CStr::from_ptr(mach_error_string(error)) }
+ .to_string_lossy()
+ .into_owned()
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PortRight {
+ Send,
+ Receive,
+ SendOnce,
+ PortSet,
+}
+
+/// One right to a Mach port, given back to the kernel when dropped.
+#[derive(Debug)]
+pub struct MachPort {
+ name: PortName,
+ right: PortRight,
+}
+
+impl MachPort {
+ pub fn allocate_receive_right() -> Result<Self, KernReturn> {
+ Self::allocate(MACH_PORT_RIGHT_RECEIVE, PortRight::Receive)
+ }
+
+ pub fn allocate_port_set() -> Result<Self, KernReturn> {
+ Self::allocate(MACH_PORT_RIGHT_PORT_SET, PortRight::PortSet)
+ }
+
+ fn allocate(kernel_right: u32, right: PortRight) -> Result<Self, KernReturn> {
+ let mut name = MACH_PORT_NULL;
+ // NB: name points to a local the call writes the new port's name to.
+ let result = unsafe { mach_port_allocate(task_self(), kernel_right, &raw mut name) };
+ if result != KERN_SUCCESS {
+ return Err(result);
+ }
+ Ok(Self { name, right })
+ }
+
+ /// Takes over a right that this task holds under a name, such as one received in a message.
+ pub fn adopt(name: PortName, right: PortRight) -> Self {
+ Self { name, right }
+ }
+
+ pub fn name(&self) -> PortName {
+ self.name
+ }
+
+ pub fn right(&self) -> PortRight {
+ self.right
+ }
+
+ /// Makes a send right to the port this receive right is for.
+ pub fn make_send_right(&self) -> Result<Self, KernReturn> {
+ assert_eq!(self.right, PortRight::Receive);
+ // NB: The call only adds a send right under the receive right's name.
+ let result = unsafe { mach_port_insert_right(task_self(), self.name, self.name, MACH_MSG_TYPE_MAKE_SEND) };
+ if result != KERN_SUCCESS {
+ return Err(result);
+ }
+ Ok(Self {
+ name: self.name,
+ right: PortRight::Send,
+ })
+ }
+
+ pub fn insert_member(&self, member: &MachPort) -> Result<(), KernReturn> {
+ assert_eq!(self.right, PortRight::PortSet);
+ // NB: Both names are rights this task holds.
+ let result = unsafe { mach_port_insert_member(task_self(), member.name, self.name) };
+ if result != KERN_SUCCESS {
+ return Err(result);
+ }
+ Ok(())
+ }
+
+ pub fn extract_member(&self, member: &MachPort) -> Result<(), KernReturn> {
+ assert_eq!(self.right, PortRight::PortSet);
+ // NB: Both names are rights this task holds.
+ let result = unsafe { mach_port_extract_member(task_self(), member.name, 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);
+ let mut limit = MACH_PORT_QLIMIT_MAX;
+ // NB: limit is the one integer of mach_port_limits_t that MACH_PORT_LIMITS_INFO reads.
+ unsafe {
+ mach_port_set_attributes(
+ task_self(),
+ self.name,
+ MACH_PORT_LIMITS_INFO,
+ &raw mut limit,
+ MACH_PORT_LIMITS_INFO_COUNT,
+ );
+ }
+ }
+
+ /// Has the kernel send `MACH_NOTIFY_NO_SENDERS` to this receive right once no send right to it is left.
+ pub fn request_no_senders_notification(&self) -> Result<(), KernReturn> {
+ assert_eq!(self.right, PortRight::Receive);
+ 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,
+ MACH_NOTIFY_NO_SENDERS,
+ 0,
+ self.name,
+ MACH_MSG_TYPE_MAKE_SEND_ONCE,
+ &raw mut previous,
+ )
+ };
+ if result != KERN_SUCCESS {
+ return Err(result);
+ }
+ // NB: A registration this replaced gives back its send-once right.
+ if is_valid(previous) {
+ drop(Self::adopt(previous, PortRight::SendOnce));
+ }
+ Ok(())
+ }
+}
+
+impl Drop for MachPort {
+ fn drop(&mut self) {
+ if !is_valid(self.name) {
+ return;
+ }
+ // NB: This MachPort owns one right of its kind under its name.
+ unsafe {
+ match self.right {
+ PortRight::Send | PortRight::SendOnce => {
+ mach_port_deallocate(task_self(), self.name);
+ }
+ PortRight::Receive => {
+ mach_port_mod_refs(task_self(), self.name, MACH_PORT_RIGHT_RECEIVE, -1);
+ }
+ PortRight::PortSet => {
+ mach_port_mod_refs(task_self(), self.name, MACH_PORT_RIGHT_PORT_SET, -1);
+ }
+ }
+ }
+ }
+}
+
+/// Wraps a file descriptor in a send right to a file port, closing the descriptor.
+pub fn file_port_from_fd(fd: OwnedFd) -> Result<MachPort, std::io::Error> {
+ let mut name = MACH_PORT_NULL;
+ // NB: fd is open and name points to a local the call writes to.
+ let result = unsafe { fileport_makeport(fd.as_raw_fd(), &raw mut name) };
+ if result != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(MachPort::adopt(name, PortRight::Send))
+}
+
+/// Opens a file descriptor for the file a file port refers to, giving the send right back.
+pub fn fd_from_file_port(port: MachPort) -> Result<OwnedFd, std::io::Error> {
+ // NB: The port is a send right this function owns.
+ let fd = unsafe { fileport_makefd(port.name()) };
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ // NB: fileport_makefd() returned a new descriptor that nothing else owns.
+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
+}
+
+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;
+
+// NB: The largest message that carries its payload inline; a larger payload goes out of line.
+const INLINE_MESSAGE_MAX_SIZE: usize = 4096;
+
+const HEADER_SIZE: usize = 24;
+const BODY_SIZE: usize = 4;
+const PORT_DESCRIPTOR_SIZE: usize = 12;
+const OUT_OF_LINE_DESCRIPTOR_SIZE: usize = 16;
+const INLINE_PAYLOAD_HEADER_SIZE: usize = size_of::<u32>();
+
+fn round_message_size(size: usize) -> usize {
+ size.next_multiple_of(size_of::<u32>())
+}
+
+/// A buffer for a Mach message, aligned for its header.
+pub struct MessageBuffer {
+ words: Vec<u64>,
+}
+
+impl MessageBuffer {
+ pub fn new(size: usize) -> Self {
+ Self {
+ words: vec![0; size.div_ceil(8)],
+ }
+ }
+
+ fn ensure_size(&mut self, size: usize) {
+ if self.words.len() * 8 < size {
+ self.words.resize(size.div_ceil(8), 0);
+ }
+ }
+
+ 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 bytes(&self) -> &[u8] {
+ // NB: Every initialized word can be read as bytes, and u8 alignment covers the entire slice.
+ unsafe { self.words.align_to::<u8>().1 }
+ }
+
+ fn bytes_mut(&mut self) -> &mut [u8] {
+ // NB: Every byte pattern is a valid u64, and u8 alignment covers the entire slice.
+ unsafe { self.words.align_to_mut::<u8>().1 }
+ }
+
+ fn header_pointer(&mut self) -> *mut c_void {
+ self.words.as_mut_ptr().cast::<c_void>()
+ }
+}
+
+fn write_u32(bytes: &mut [u8], offset: usize, value: u32) {
+ bytes[offset..offset + 4].copy_from_slice(&value.to_ne_bytes());
+}
+
+fn read_u32(bytes: &[u8], offset: usize) -> Option<u32> {
+ Some(u32::from_ne_bytes(bytes.get(offset..offset + 4)?.try_into().ok()?))
+}
+
+fn write_header(bytes: &mut [u8], bits: u32, size: usize, remote_port: PortName, id: i32) {
+ write_u32(bytes, 0, bits);
+ write_u32(bytes, 4, size as u32);
+ write_u32(bytes, 8, remote_port);
+ write_u32(bytes, 12, MACH_PORT_NULL);
+ write_u32(bytes, 16, MACH_PORT_NULL);
+ write_u32(bytes, 20, id as u32);
+}
+
+/// Sends a header-only message through a send right this task keeps, as to wake a thread waiting on its port.
+pub fn send_header_only_message(destination: &MachPort, id: i32, timeout: Option<u32>) -> KernReturn {
+ 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_COPY_SEND, 0),
+ HEADER_SIZE,
+ destination.name(),
+ id,
+ );
+ let options = if timeout.is_some() {
+ MACH_SEND_MSG | MACH_SEND_TIMEOUT
+ } else {
+ MACH_SEND_MSG
+ };
+ // NB: The buffer holds a header-only message to a send right this task keeps, and outlives the call.
+ let result = unsafe {
+ mach_msg(
+ buffer.as_mut_ptr().cast(),
+ options,
+ HEADER_SIZE as u32,
+ 0,
+ MACH_PORT_NULL,
+ timeout.unwrap_or(MACH_MSG_TIMEOUT_NONE),
+ MACH_PORT_NULL,
+ )
+ };
+ if result & !MACH_MSG_MASK == MACH_SEND_TIMED_OUT {
+ // NB: A timeout returns the copied destination right in this header.
+ unsafe { mach_msg_destroy(buffer.as_mut_ptr().cast()) };
+ }
+ result
+}
+
+/// Sends LibIPC's data message through a send right this task keeps, moving the rights of the attachments with it.
+///
+/// A payload that fits goes inline after a 32-bit size; a larger one goes out of line, as `TransportMachPort` sends it.
+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,
+ )
+ }
+ })
+}
+
+fn send_data_message_with(
+ buffer: &mut MessageBuffer,
+ 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;
+ }
+ if ports.iter().any(|(port, disposition)| {
+ !matches!(
+ (port.right(), *disposition),
+ (PortRight::Send, MACH_MSG_TYPE_MOVE_SEND | MACH_MSG_TYPE_COPY_SEND)
+ | (
+ PortRight::Receive,
+ MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MAKE_SEND | MACH_MSG_TYPE_MAKE_SEND_ONCE
+ )
+ | (PortRight::SendOnce, MACH_MSG_TYPE_MOVE_SEND_ONCE)
+ )
+ }) {
+ return MACH_SEND_INVALID_RIGHT;
+ }
+ let port_count = ports.len();
+ let mut inline_size = HEADER_SIZE + INLINE_PAYLOAD_HEADER_SIZE + payload.len();
+ if port_count > 0 {
+ inline_size += BODY_SIZE + port_count * PORT_DESCRIPTOR_SIZE;
+ }
+ let inline_size = round_message_size(inline_size);
+ let send_payload_inline = inline_size <= INLINE_MESSAGE_MAX_SIZE;
+ let message_size = if send_payload_inline {
+ inline_size
+ } else {
+ round_message_size(HEADER_SIZE + BODY_SIZE + port_count * PORT_DESCRIPTOR_SIZE + OUT_OF_LINE_DESCRIPTOR_SIZE)
+ };
+
+ buffer.ensure_size(message_size);
+ {
+ let bytes = buffer.bytes_mut();
+ bytes[..message_size].fill(0);
+ let id = if send_payload_inline {
+ IPC_INLINE_DATA_MESSAGE_ID
+ } else {
+ IPC_DATA_MESSAGE_ID
+ };
+ let mut bits = msgh_bits(MACH_MSG_TYPE_COPY_SEND, 0);
+ let complex = port_count > 0 || !send_payload_inline;
+ if complex {
+ bits |= MACH_MSGH_BITS_COMPLEX;
+ }
+ write_header(bytes, bits, message_size, destination.name(), id);
+
+ let mut offset = HEADER_SIZE;
+ if complex {
+ let descriptor_count = port_count + usize::from(!send_payload_inline);
+ write_u32(bytes, offset, descriptor_count as u32);
+ offset += BODY_SIZE;
+ for (port, disposition) in &ports {
+ write_u32(bytes, offset, port.name());
+ write_u32(
+ bytes,
+ offset + 8,
+ (*disposition << 16) | (u32::from(MACH_MSG_PORT_DESCRIPTOR) << 24),
+ );
+ offset += PORT_DESCRIPTOR_SIZE;
+ }
+ }
+
+ if send_payload_inline {
+ write_u32(bytes, offset, payload.len() as u32);
+ offset += INLINE_PAYLOAD_HEADER_SIZE;
+ bytes[offset..offset + payload.len()].copy_from_slice(payload);
+ } else {
+ bytes[offset..offset + 8].copy_from_slice(&(payload.as_ptr() as u64).to_ne_bytes());
+ write_u32(
+ bytes,
+ offset + 8,
+ (u32::from(MACH_MSG_VIRTUAL_COPY) << 8) | (u32::from(MACH_MSG_OOL_DESCRIPTOR) << 24),
+ );
+ write_u32(bytes, offset + 12, payload.len() as u32);
+ }
+ }
+
+ // 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.
+ for (port, disposition) in &mut ports {
+ if matches!(
+ *disposition,
+ MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MOVE_SEND | MACH_MSG_TYPE_MOVE_SEND_ONCE
+ ) {
+ 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;
+ }
+ return result;
+ }
+ if !send_error_leaves_descriptors_untouched(result) {
+ std::mem::forget(resources);
+ }
+ return result;
+ }
+}
+
+fn send_error_leaves_descriptors_untouched(result: KernReturn) -> bool {
+ // NB: With inline port descriptors and one virtual-copy region, these errors precede descriptor copyin.
+ matches!(
+ result,
+ MACH_SEND_INVALID_DATA
+ | MACH_SEND_INVALID_DEST
+ | MACH_SEND_INVALID_VOUCHER
+ | MACH_SEND_MSG_TOO_SMALL
+ | MACH_SEND_INVALID_REPLY
+ | MACH_SEND_INVALID_NOTIFY
+ | MACH_SEND_NO_BUFFER
+ | MACH_SEND_TOO_LARGE
+ | MACH_SEND_INVALID_HEADER
+ | MACH_SEND_INVALID_TRAILER
+ | MACH_SEND_INVALID_CONTEXT
+ | MACH_SEND_INVALID_OPTIONS
+ | MACH_SEND_NO_GRANT_DEST
+ | MACH_SEND_MSG_FILTERED
+ )
+}
+
+fn right_for_disposition(disposition: u32) -> PortRight {
+ match disposition {
+ MACH_MSG_TYPE_MOVE_RECEIVE => PortRight::Receive,
+ MACH_MSG_TYPE_MOVE_SEND_ONCE => PortRight::SendOnce,
+ _ => PortRight::Send,
+ }
+}
+
+/// The bytes of a received LibIPC message, copied from the message or mapped out of line.
+pub enum PayloadBytes {
+ Inline(Vec<u8>),
+ OutOfLine(VmRegion),
+}
+
+impl AsRef<[u8]> for PayloadBytes {
+ fn as_ref(&self) -> &[u8] {
+ self.bytes()
+ }
+}
+
+impl PayloadBytes {
+ pub fn bytes(&self) -> &[u8] {
+ match self {
+ Self::Inline(bytes) => bytes,
+ Self::OutOfLine(region) => region.bytes(),
+ }
+ }
+}
+
+pub struct ReceivedMessage {
+ pub id: i32,
+ 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)>)>,
+}
+
+#[derive(Debug)]
+pub enum ReceiveError {
+ Kernel(KernReturn),
+ Malformed(&'static str),
+}
+
+/// 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> {
+ let mut result = receive_into(buffer, from, MACH_RCV_LARGE);
+ 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;
+ buffer.ensure_size(needed);
+ result = receive_into(buffer, from, 0);
+ }
+ let message = if result != MACH_MSG_SUCCESS {
+ Err(ReceiveError::Kernel(result))
+ } else {
+ parse_received_message(buffer)
+ };
+ buffer.release_excess_capacity();
+ 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);
+ // NB: The buffer is aligned for a header, and the call writes at most size bytes into it.
+ unsafe {
+ mach_msg(
+ buffer.header_pointer(),
+ MACH_RCV_MSG | options,
+ 0,
+ size,
+ from.name(),
+ MACH_MSG_TIMEOUT_NONE,
+ MACH_PORT_NULL,
+ )
+ }
+}
+
+struct MessageResources<'a>(&'a mut MessageBuffer);
+
+impl Drop for MessageResources<'_> {
+ fn drop(&mut self) {
+ // NB: This message owns its moved rights and deallocating memory regions. Descriptors adopted by Rust
+ // owners have been cleared; mach_msg_destroy() releases the remaining resources.
+ unsafe { mach_msg_destroy(self.0.header_pointer()) };
+ }
+}
+
+fn parse_received_message(buffer: &mut MessageBuffer) -> Result<ReceivedMessage, ReceiveError> {
+ // NB: The kernel validates the Mach descriptor layout, but not the LibIPC layout. Keep ownership of all received
+ // 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 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 != IPC_DATA_MESSAGE_ID && id != IPC_INLINE_DATA_MESSAGE_ID {
+ return Ok(ReceivedMessage {
+ id,
+ local_port,
+ data: None,
+ });
+ }
+
+ let mut ports = Vec::new();
+ let mut offset = HEADER_SIZE;
+ let mut out_of_line = None;
+ if bits & MACH_MSGH_BITS_COMPLEX != 0 {
+ let descriptor_count = read_u32(bytes, offset).ok_or(malformed("body"))? as usize;
+ offset += BODY_SIZE;
+ let port_count = if id == IPC_DATA_MESSAGE_ID {
+ descriptor_count.checked_sub(1).ok_or(malformed("descriptors"))?
+ } else {
+ descriptor_count
+ };
+ for _ in 0..port_count {
+ let name = read_u32(bytes, offset).ok_or(malformed("port descriptor"))?;
+ let descriptor_bits = read_u32(bytes, offset + 8).ok_or(malformed("port descriptor"))?;
+ let disposition = (descriptor_bits >> 16) & 0xff;
+ // NB: A right whose port died before this message was received arrives as MACH_PORT_DEAD, which is the
+ // kernel reporting a fact about the peer rather than a malformed message. Adopt it like any other, as
+ // TransportMachPort does, and leave it to whoever takes the attachment. The name holds no right in
+ // this task, so dropping it gives nothing back.
+ if (descriptor_bits >> 24) as u8 != MACH_MSG_PORT_DESCRIPTOR
+ || name == MACH_PORT_NULL
+ || !matches!(
+ disposition,
+ MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MOVE_SEND | MACH_MSG_TYPE_MOVE_SEND_ONCE
+ )
+ {
+ return Err(malformed("port descriptor"));
+ }
+ let port = MachPort::adopt(name, right_for_disposition(disposition));
+ write_u32(bytes, offset, MACH_PORT_NULL);
+ ports.push((port, disposition));
+ offset += PORT_DESCRIPTOR_SIZE;
+ }
+ if id == IPC_DATA_MESSAGE_ID {
+ let address = u64::from_ne_bytes(
+ bytes
+ .get(offset..offset + 8)
+ .ok_or(malformed("out-of-line descriptor"))?
+ .try_into()
+ .unwrap_or_default(),
+ );
+ let descriptor_bits = read_u32(bytes, offset + 8).ok_or(malformed("out-of-line descriptor"))?;
+ let payload_size = read_u32(bytes, offset + 12).ok_or(malformed("out-of-line descriptor"))? as usize;
+ if (descriptor_bits >> 24) as u8 != MACH_MSG_OOL_DESCRIPTOR {
+ return Err(malformed("out-of-line descriptor"));
+ }
+ // NB: The kernel mapped this region into this task for the message, and nothing else owns it.
+ out_of_line = Some(unsafe { VmRegion::adopt(address as *const c_void, payload_size) });
+ bytes[offset..offset + 8].fill(0);
+ write_u32(bytes, offset + 12, 0);
+ }
+ } else if id == IPC_DATA_MESSAGE_ID {
+ return Err(malformed("out-of-line message without descriptors"));
+ }
+
+ let payload = match out_of_line {
+ Some(region) => PayloadBytes::OutOfLine(region),
+ None => {
+ let payload_size = read_u32(bytes, offset).ok_or(malformed("inline payload"))? as usize;
+ offset += INLINE_PAYLOAD_HEADER_SIZE;
+ if payload_size > size.saturating_sub(offset) {
+ return Err(malformed("inline payload size"));
+ }
+ PayloadBytes::Inline(bytes[offset..offset + payload_size].to_vec())
+ }
+ };
+ Ok(ReceivedMessage {
+ id,
+ local_port,
+ data: Some((payload, ports)),
+ })
+}
+
+/// Memory the kernel mapped into this task for an out-of-line message payload, which this owns.
+pub struct VmRegion {
+ address: usize,
+ size: usize,
+}
+
+impl VmRegion {
+ /// # Safety
+ ///
+ /// The region must be one the kernel mapped into this task for a received message, and nothing else may own it.
+ pub unsafe fn adopt(address: *const c_void, size: usize) -> Self {
+ Self {
+ address: address as usize,
+ size,
+ }
+ }
+
+ #[expect(clippy::disallowed_methods, reason = "The nonempty slice borrows an owned mapping.")]
+ pub fn bytes(&self) -> &[u8] {
+ if self.size == 0 {
+ return &[];
+ }
+ // NB: The kernel mapped size readable bytes at address, which this region owns until it is dropped.
+ unsafe { std::slice::from_raw_parts(self.address as *const u8, self.size) }
+ }
+}
+
+impl Drop for VmRegion {
+ fn drop(&mut self) {
+ if self.size == 0 {
+ return;
+ }
+ // NB: This region owns the mapping.
+ unsafe {
+ vm_deallocate(task_self(), self.address, self.size);
+ }
+ }
+}
+
+// NB: A VmRegion is plain memory that this task owns; nothing ties it to the thread that received it.
+unsafe impl Send for VmRegion {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn large_receives_reuse_the_grown_buffer() {
+ 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
+ );
+ 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);
+ }
+
+ #[test]
+ fn rights_to_dead_ports_are_accepted() {
+ let message_size =
+ round_message_size(HEADER_SIZE + BODY_SIZE + PORT_DESCRIPTOR_SIZE + INLINE_PAYLOAD_HEADER_SIZE + 1);
+ let mut buffer = MessageBuffer::new(message_size + TRAILER_SIZE);
+ let bytes = buffer.bytes_mut();
+ write_header(
+ bytes,
+ MACH_MSGH_BITS_COMPLEX,
+ message_size,
+ MACH_PORT_NULL,
+ IPC_INLINE_DATA_MESSAGE_ID,
+ );
+ let mut offset = HEADER_SIZE;
+ write_u32(bytes, offset, 1);
+ offset += BODY_SIZE;
+ write_u32(bytes, offset, MACH_PORT_DEAD);
+ write_u32(
+ bytes,
+ offset + 8,
+ (MACH_MSG_TYPE_MOVE_SEND << 16) | (u32::from(MACH_MSG_PORT_DESCRIPTOR) << 24),
+ );
+ offset += PORT_DESCRIPTOR_SIZE;
+ write_u32(bytes, offset, 1);
+ bytes[offset + INLINE_PAYLOAD_HEADER_SIZE] = 7;
+ let (payload, ports) = parse_received_message(&mut buffer).unwrap().data.unwrap();
+ assert_eq!(payload.bytes(), [7]);
+ assert_eq!(ports.len(), 1);
+ assert_eq!(ports[0].0.name(), MACH_PORT_DEAD);
+ assert_eq!(ports[0].1, MACH_MSG_TYPE_MOVE_SEND);
+ }
+
+ #[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() {
+ 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
+ }
+ ),
+ MACH_MSG_SUCCESS
+ );
+ assert_eq!(attempt, 3);
+ }
+
+ #[test]
+ fn too_many_attachments_are_refused_before_sending() {
+ 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
+ );
+ }
+
+ #[test]
+ fn invalid_dispositions_are_refused_before_sending() {
+ use std::io::Read;
+ 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(
+ &mut buffer,
+ &destination,
+ &[1],
+ vec![(port, MACH_MSG_TYPE_MOVE_RECEIVE)],
+ || false,
+ |_, _| panic!("invalid dispositions must not be sent")
+ ),
+ MACH_SEND_INVALID_RIGHT
+ );
+ assert_eq!(reader.read(&mut [0]).unwrap(), 0);
+ }
+
+ #[test]
+ fn failed_sends_release_unconsumed_attachments() {
+ use std::io::Read;
+ for error in [
+ MACH_SEND_INVALID_DEST,
+ MACH_SEND_NO_BUFFER,
+ MACH_SEND_TOO_LARGE,
+ MACH_SEND_INVALID_HEADER,
+ MACH_SEND_INVALID_REPLY,
+ MACH_SEND_INVALID_VOUCHER,
+ MACH_SEND_MSG_TOO_SMALL,
+ MACH_SEND_INVALID_DATA,
+ MACH_SEND_INVALID_OPTIONS,
+ MACH_SEND_INVALID_CONTEXT,
+ 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(
+ &mut buffer,
+ &destination,
+ &[1],
+ vec![(port, MACH_MSG_TYPE_MOVE_SEND)],
+ || false,
+ |_, _| error
+ ),
+ error
+ );
+ assert_eq!(reader.read(&mut [0]).unwrap(), 0);
+ }
+ }
+
+ #[test]
+ fn body_copyin_errors_do_not_deallocate_consumed_names() {
+ for error in [
+ MACH_SEND_INVALID_MEMORY,
+ MACH_SEND_INVALID_RIGHT,
+ MACH_SEND_INVALID_TYPE,
+ ] {
+ let (reader, writer) = std::io::pipe().unwrap();
+ let port = file_port_from_fd(OwnedFd::from(writer)).unwrap();
+ // NB: This adds an independently owned reference to the send right.
+ assert_eq!(
+ unsafe { mach_port_mod_refs(task_self(), port.name(), 0, 1) },
+ KERN_SUCCESS
+ );
+ 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
+ );
+ drop(fd_from_file_port(retained).unwrap());
+ drop(reader);
+ }
+ }
+
+ fn fill_queue(receive: &MachPort, send: &MachPort) {
+ loop {
+ match send_header_only_message(send, IPC_WAKEUP_MESSAGE_ID, Some(0)) {
+ MACH_MSG_SUCCESS => (),
+ MACH_SEND_TIMED_OUT => break,
+ error => panic!("queue fill failed: {}", error_string(error)),
+ }
+ }
+ assert_eq!(receive.right(), PortRight::Receive);
+ }
+
+ #[test]
+ fn timed_out_sends_destroy_the_returned_message() {
+ use std::io::Read;
+ for payload in [vec![1], vec![1; 8192]] {
+ let receive = MachPort::allocate_receive_right().unwrap();
+ let destination = receive.make_send_right().unwrap();
+ fill_queue(&receive, &destination);
+ let (mut reader, writer) = std::io::pipe().unwrap();
+ 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
+ );
+ assert_eq!(reader.read(&mut [0]).unwrap(), 0);
+ assert_eq!(
+ send_header_only_message(&attachment_send, IPC_WAKEUP_MESSAGE_ID, Some(0)),
+ MACH_SEND_INVALID_DEST
+ );
+ }
+ }
+
+ #[test]
+ fn timed_out_sends_retry_the_returned_rights_and_memory() {
+ 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
+ );
+ assert_eq!(retries, 1);
+ loop {
+ let message = receive_message(&mut MessageBuffer::new(4096), &receive).unwrap();
+ if let Some((bytes, ports)) = message.data {
+ assert_eq!(bytes.bytes(), payload);
+ assert_eq!(ports.len(), 1);
+ assert_eq!(ports[0].0.right(), PortRight::Receive);
+ break;
+ }
+ }
+ }
+
+ #[test]
+ fn rights_are_given_back_when_dropped() {
+ let receive = MachPort::allocate_receive_right().unwrap();
+ let send = receive.make_send_right().unwrap();
+ assert_eq!(send.name(), receive.name());
+ drop(send);
+ drop(receive);
+ }
+}
diff --git a/Libraries/LibIPC/Rust/src/wire.rs b/Libraries/LibIPC/Rust/src/wire.rs
new file mode 100644
index 00000000000..ad9e8d5d8db
--- /dev/null
+++ b/Libraries/LibIPC/Rust/src/wire.rs
@@ -0,0 +1,906 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! LibIPC's wire format, as `IPC::Encoder` and `IPC::Decoder` write and read it.
+//!
+//! Numbers go as their bytes in the host's order, sizes as 32-bit numbers, booleans as one byte, an optional value as a
+//! boolean followed by the value, and a sequence as its size followed by its elements. File descriptors and port rights
+//! go beside the bytes, as attachments, in the order they are encoded.
+
+use std::collections::VecDeque;
+use std::os::fd::OwnedFd;
+
+use crate::attachment::Attachment;
+
+#[derive(Debug)]
+pub enum EncodeError {
+ SizeTooLarge(usize),
+ InvalidValue(&'static str),
+ Attachment(std::io::Error),
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum DecodeError {
+ UnexpectedEnd,
+ SizeTooLarge(usize),
+ InvalidBoolean(u8),
+ InvalidUtf8,
+ InvalidValue(&'static str),
+ MissingAttachment,
+ Attachment(String),
+ AllocationFailed,
+}
+
+pub trait Encode {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError>;
+
+ /// Encodes an owned value, moving its attachments into the encoder.
+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError>
+ where
+ Self: Sized,
+ {
+ self.encode(encoder)
+ }
+
+ fn encode_slice(elements: &[Self], encoder: &mut Encoder) -> Result<(), EncodeError>
+ where
+ Self: Sized,
+ {
+ for element in elements {
+ element.encode(encoder)?;
+ }
+ Ok(())
+ }
+
+ fn encode_vec(elements: Vec<Self>, encoder: &mut Encoder) -> Result<(), EncodeError>
+ where
+ Self: Sized,
+ {
+ encoder.encode_size(elements.len())?;
+ for element in elements {
+ element.encode_owned(encoder)?;
+ }
+ Ok(())
+ }
+}
+
+pub trait Decode: Sized {
+ /// A lower bound on the bytes an encoded value occupies, excluding attachments.
+ const MIN_ENCODED_SIZE: usize = 0;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError>;
+
+ fn decode_vec(decoder: &mut Decoder<'_>, size: usize) -> Result<Vec<Self>, DecodeError> {
+ decode_elements(decoder, size)
+ }
+}
+
+#[derive(Default)]
+pub struct Encoder {
+ bytes: Vec<u8>,
+ attachments: Vec<Attachment>,
+}
+
+impl Encoder {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn encode<T: Encode + ?Sized>(&mut self, value: &T) -> Result<(), EncodeError> {
+ value.encode(self)
+ }
+
+ pub fn encode_owned<T: Encode>(&mut self, value: T) -> Result<(), EncodeError> {
+ value.encode_owned(self)
+ }
+
+ pub fn append_bytes(&mut self, bytes: &[u8]) {
+ self.bytes.extend_from_slice(bytes);
+ }
+
+ pub fn encode_size(&mut self, size: usize) -> Result<(), EncodeError> {
+ let size = u32::try_from(size).map_err(|_| EncodeError::SizeTooLarge(size))?;
+ self.append_bytes(&size.to_ne_bytes());
+ Ok(())
+ }
+
+ pub fn append_attachment(&mut self, attachment: Attachment) {
+ self.attachments.push(attachment);
+ }
+
+ pub fn finish(self) -> (Vec<u8>, Vec<Attachment>) {
+ (self.bytes, self.attachments)
+ }
+}
+
+pub struct Decoder<'a> {
+ bytes: &'a [u8],
+ position: usize,
+ attachments: VecDeque<Attachment>,
+}
+
+impl<'a> Decoder<'a> {
+ pub fn new(bytes: &'a [u8], attachments: impl IntoIterator<Item = Attachment>) -> Self {
+ Self {
+ bytes,
+ position: 0,
+ attachments: attachments.into_iter().collect(),
+ }
+ }
+
+ pub fn decode<T: Decode>(&mut self) -> Result<T, DecodeError> {
+ T::decode(self)
+ }
+
+ pub fn read_bytes(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
+ let end = self.position.checked_add(count).ok_or(DecodeError::UnexpectedEnd)?;
+ let bytes = self.bytes.get(self.position..end).ok_or(DecodeError::UnexpectedEnd)?;
+ self.position = end;
+ Ok(bytes)
+ }
+
+ pub fn decode_size(&mut self) -> Result<usize, DecodeError> {
+ let size = self.decode::<u32>()? as usize;
+ if size > self.remaining_bytes().saturating_add(self.attachments.len()) {
+ return Err(DecodeError::UnexpectedEnd);
+ }
+ Ok(size)
+ }
+
+ pub fn take_attachment(&mut self) -> Result<Attachment, DecodeError> {
+ self.attachments.pop_front().ok_or(DecodeError::MissingAttachment)
+ }
+
+ pub fn remaining_bytes(&self) -> usize {
+ self.bytes.len() - self.position
+ }
+
+ pub fn remaining_attachments(&self) -> usize {
+ self.attachments.len()
+ }
+
+ pub fn is_at_end(&self) -> bool {
+ self.remaining_bytes() == 0
+ }
+}
+
+macro_rules! impl_number {
+ ($($type:ty),*) => {
+ $(
+ impl Encode for $type {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.append_bytes(&self.to_ne_bytes());
+ Ok(())
+ }
+
+ fn encode_slice(elements: &[Self], encoder: &mut Encoder) -> Result<(), EncodeError> {
+ let byte_count = elements.len().checked_mul(size_of::<Self>()).ok_or(EncodeError::SizeTooLarge(elements.len()))?;
+ encoder.bytes.reserve(byte_count);
+ for element in elements {
+ encoder.bytes.extend_from_slice(&element.to_ne_bytes());
+ }
+ Ok(())
+ }
+
+ fn encode_vec(elements: Vec<Self>, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ elements.as_slice().encode(encoder)
+ }
+ }
+
+ impl Decode for $type {
+ const MIN_ENCODED_SIZE: usize = size_of::<$type>();
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let bytes = decoder.read_bytes(size_of::<$type>())?;
+ Ok(<$type>::from_ne_bytes(bytes.try_into().map_err(|_| DecodeError::UnexpectedEnd)?))
+ }
+
+ fn decode_vec(decoder: &mut Decoder<'_>, size: usize) -> Result<Vec<Self>, DecodeError> {
+ let byte_count = size.checked_mul(size_of::<$type>()).ok_or(DecodeError::SizeTooLarge(size))?;
+ let bytes = decoder.read_bytes(byte_count)?;
+ Ok(bytes.as_chunks::<{ size_of::<$type>() }>().0.iter()
+ .map(|&chunk| <$type>::from_ne_bytes(chunk))
+ .collect())
+ }
+ }
+ )*
+ };
+}
+
+impl_number!(u16, u32, u64, i8, i16, i32, i64, f32, f64);
+
+impl Encode for u8 {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.append_bytes(&[*self]);
+ Ok(())
+ }
+
+ fn encode_slice(elements: &[Self], encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.append_bytes(elements);
+ Ok(())
+ }
+
+ fn encode_vec(elements: Vec<Self>, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ elements.as_slice().encode(encoder)
+ }
+}
+
+impl Decode for u8 {
+ const MIN_ENCODED_SIZE: usize = 1;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(decoder.read_bytes(1)?[0])
+ }
+
+ fn decode_vec(decoder: &mut Decoder<'_>, size: usize) -> Result<Vec<Self>, DecodeError> {
+ Ok(decoder.read_bytes(size)?.to_vec())
+ }
+}
+
+// NB: A size_t encodes as the 64-bit number it is on every target Ladybird supports.
+impl Encode for usize {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ (*self as u64).encode(encoder)
+ }
+}
+
+impl Decode for usize {
+ const MIN_ENCODED_SIZE: usize = 8;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ usize::try_from(decoder.decode::<u64>()?).map_err(|_| DecodeError::InvalidValue("size_t"))
+ }
+
+ fn decode_vec(decoder: &mut Decoder<'_>, size: usize) -> Result<Vec<Self>, DecodeError> {
+ let byte_count = size.checked_mul(8).ok_or(DecodeError::SizeTooLarge(size))?;
+ let bytes = decoder.read_bytes(byte_count)?;
+ bytes
+ .as_chunks::<8>()
+ .0
+ .iter()
+ .map(|&chunk| usize::try_from(u64::from_ne_bytes(chunk)).map_err(|_| DecodeError::InvalidValue("size_t")))
+ .collect()
+ }
+}
+
+impl Encode for bool {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ u8::from(*self).encode(encoder)
+ }
+}
+
+impl Decode for bool {
+ const MIN_ENCODED_SIZE: usize = 1;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ match decoder.decode::<u8>()? {
+ 0 => Ok(false),
+ 1 => Ok(true),
+ other => Err(DecodeError::InvalidBoolean(other)),
+ }
+ }
+}
+
+impl Encode for () {
+ fn encode(&self, _: &mut Encoder) -> Result<(), EncodeError> {
+ Ok(())
+ }
+}
+
+impl Decode for () {
+ fn decode(_: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(())
+ }
+}
+
+/// `String` and `StringView`: the size of the UTF-8 bytes, then the bytes.
+impl Encode for str {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.as_bytes().encode(encoder)
+ }
+}
+
+impl Encode for String {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.as_str().encode(encoder)
+ }
+}
+
+impl Decode for String {
+ const MIN_ENCODED_SIZE: usize = 4;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let size = decoder.decode_size()?;
+ let bytes = decoder.read_bytes(size)?;
+ String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::InvalidUtf8)
+ }
+}
+
+/// C++ `String`: UTF-8 bytes that may include lone surrogate encodings.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
+pub struct Utf8String(Vec<u8>);
+
+impl Utf8String {
+ pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, DecodeError> {
+ validate_utf8(&bytes)?;
+ Ok(Self(bytes))
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ pub fn into_bytes(self) -> Vec<u8> {
+ self.0
+ }
+
+ pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
+ std::str::from_utf8(&self.0)
+ }
+
+ pub fn into_string(self) -> Result<String, std::string::FromUtf8Error> {
+ String::from_utf8(self.0)
+ }
+}
+
+impl From<&str> for Utf8String {
+ fn from(string: &str) -> Self {
+ Self(string.as_bytes().to_vec())
+ }
+}
+
+impl From<String> for Utf8String {
+ fn from(string: String) -> Self {
+ Self(string.into_bytes())
+ }
+}
+
+impl Encode for Utf8String {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.as_bytes().encode(encoder)
+ }
+}
+
+impl Decode for Utf8String {
+ const MIN_ENCODED_SIZE: usize = 4;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let size = decoder.decode_size()?;
+ let bytes = decoder.read_bytes(size)?;
+ validate_utf8(bytes)?;
+ Ok(Self(bytes.to_vec()))
+ }
+}
+
+/// `ByteString`: bytes in no particular encoding, which go as `String` does.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
+pub struct ByteString(pub Vec<u8>);
+
+impl Encode for ByteString {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.0.as_slice().encode(encoder)
+ }
+}
+
+impl Decode for ByteString {
+ const MIN_ENCODED_SIZE: usize = 4;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let size = decoder.decode_size()?;
+ Ok(Self(decoder.read_bytes(size)?.to_vec()))
+ }
+}
+
+/// Validates bytes as `Utf8View::validate()` does, including lonely surrogates.
+pub fn validate_utf8(mut bytes: &[u8]) -> Result<(), DecodeError> {
+ while let Err(error) = std::str::from_utf8(bytes) {
+ bytes = &bytes[error.valid_up_to()..];
+ match bytes {
+ [0xed, 0xa0..=0xbf, 0x80..=0xbf, rest @ ..] => bytes = rest,
+ _ => return Err(DecodeError::InvalidUtf8),
+ }
+ }
+ Ok(())
+}
+
+/// `Utf16String`: whether its code units are stored as ASCII bytes, their count, then the code units.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
+pub struct Utf16String(pub Vec<u16>);
+
+impl From<&str> for Utf16String {
+ fn from(string: &str) -> Self {
+ Self(string.encode_utf16().collect())
+ }
+}
+
+impl Utf16String {
+ pub fn to_string_lossy(&self) -> String {
+ String::from_utf16_lossy(&self.0)
+ }
+}
+
+impl Encode for Utf16String {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ let is_ascii = self.0.iter().all(|&code_unit| code_unit < 0x80);
+ is_ascii.encode(encoder)?;
+ encoder.encode_size(self.0.len())?;
+ if is_ascii {
+ encoder.bytes.reserve(self.0.len());
+ encoder.bytes.extend(self.0.iter().map(|&code_unit| code_unit as u8));
+ } else {
+ u16::encode_slice(&self.0, encoder)?;
+ }
+ Ok(())
+ }
+}
+
+impl Decode for Utf16String {
+ const MIN_ENCODED_SIZE: usize = 5;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let is_ascii = decoder.decode::<bool>()?;
+ let length = decoder.decode_size()?;
+ if is_ascii {
+ let bytes = decoder.read_bytes(length)?;
+ if !bytes.is_ascii() {
+ return Err(DecodeError::InvalidValue("Utf16String with ASCII storage"));
+ }
+ return Ok(Self(bytes.iter().map(|&byte| u16::from(byte)).collect()));
+ }
+ let byte_count = length.checked_mul(2).ok_or(DecodeError::SizeTooLarge(length))?;
+ let bytes = decoder.read_bytes(byte_count)?;
+ let (code_units, _) = bytes.as_chunks::<2>();
+ Ok(Self(code_units.iter().map(|&pair| u16::from_ne_bytes(pair)).collect()))
+ }
+}
+
+/// `Vector` and spans: the size, then the elements.
+impl<T: Encode> Encode for [T] {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode_size(self.len())?;
+ T::encode_slice(self, encoder)
+ }
+}
+
+impl<T: Encode> Encode for Vec<T> {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.as_slice().encode(encoder)
+ }
+
+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ T::encode_vec(self, encoder)
+ }
+}
+
+impl<T: Decode> Decode for Vec<T> {
+ const MIN_ENCODED_SIZE: usize = 4;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let size = decoder.decode_size()?;
+ T::decode_vec(decoder, size)
+ }
+}
+
+fn decode_elements<T: Decode>(decoder: &mut Decoder<'_>, size: usize) -> Result<Vec<T>, DecodeError> {
+ if T::MIN_ENCODED_SIZE != 0 && size > decoder.remaining_bytes() / T::MIN_ENCODED_SIZE {
+ return Err(DecodeError::UnexpectedEnd);
+ }
+ let mut elements = Vec::new();
+ for _ in 0..size {
+ let element = decoder.decode()?;
+ if elements.len() == elements.capacity() {
+ // NB: Grow only after decoding an element, independently of the peer's count.
+ elements.try_reserve(1).map_err(|_| DecodeError::AllocationFailed)?;
+ }
+ elements.push(element);
+ }
+ Ok(elements)
+}
+
+/// `Array`: the size, which must match, then the elements.
+impl<T: Encode, const N: usize> Encode for [T; N] {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.as_slice().encode(encoder)
+ }
+
+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode_size(N)?;
+ for element in self {
+ element.encode_owned(encoder)?;
+ }
+ Ok(())
+ }
+}
+
+impl<T: Decode, const N: usize> Decode for [T; N] {
+ const MIN_ENCODED_SIZE: usize = 4;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let size = decoder.decode_size()?;
+ if size != N {
+ return Err(DecodeError::InvalidValue("Array size"));
+ }
+ let elements = T::decode_vec(decoder, N)?;
+ elements.try_into().map_err(|_| DecodeError::InvalidValue("Array size"))
+ }
+}
+
+/// `Optional`: whether there is a value, then the value.
+impl<T: Encode> Encode for Option<T> {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.is_some().encode(encoder)?;
+ if let Some(value) = self {
+ value.encode(encoder)?;
+ }
+ Ok(())
+ }
+
+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ self.is_some().encode(encoder)?;
+ if let Some(value) = self {
+ value.encode_owned(encoder)?;
+ }
+ Ok(())
+ }
+}
+
+impl<T: Decode> Decode for Option<T> {
+ const MIN_ENCODED_SIZE: usize = 1;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ if decoder.decode::<bool>()? {
+ return Ok(Some(decoder.decode()?));
+ }
+ Ok(None)
+ }
+}
+
+/// `IPC::File`: a file descriptor, which goes as an attachment.
+#[derive(Debug)]
+pub struct File(pub OwnedFd);
+
+impl Encode for File {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ let fd = self.0.try_clone().map_err(EncodeError::Attachment)?;
+ encoder.append_attachment(Attachment::from_fd(fd).map_err(EncodeError::Attachment)?);
+ Ok(())
+ }
+
+ fn encode_owned(self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.append_attachment(Attachment::from_fd(self.0).map_err(EncodeError::Attachment)?);
+ Ok(())
+ }
+}
+
+impl Decode for File {
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ let attachment = decoder.take_attachment()?;
+ Ok(Self(
+ attachment
+ .into_fd()
+ .map_err(|error| DecodeError::Attachment(error.to_string()))?,
+ ))
+ }
+}
+
+/// A message of an endpoint, which goes as the endpoint's magic number, the message's ID and the message's fields.
+pub trait EndpointMessage: Encode {
+ const ENDPOINT_MAGIC: u32;
+ const MESSAGE_ID: i32;
+
+ fn encode_message(self) -> Result<(Vec<u8>, Vec<Attachment>), EncodeError>
+ where
+ Self: Sized,
+ {
+ let mut encoder = Encoder::new();
+ encoder.encode(&Self::ENDPOINT_MAGIC)?;
+ encoder.encode(&Self::MESSAGE_ID)?;
+ encoder.encode_owned(self)?;
+ Ok(encoder.finish())
+ }
+}
+
+/// Reads the endpoint magic number and message ID that a message starts with.
+pub fn decode_message_header(decoder: &mut Decoder<'_>) -> Result<(u32, i32), DecodeError> {
+ Ok((decoder.decode()?, decoder.decode()?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn round_trip<T: Encode + Decode>(value: &T) -> (T, Vec<u8>) {
+ let mut encoder = Encoder::new();
+ encoder.encode(value).unwrap();
+ let (bytes, attachments) = encoder.finish();
+ let mut decoder = Decoder::new(&bytes, attachments);
+ let decoded = decoder.decode().unwrap();
+ assert!(decoder.is_at_end());
+ (decoded, bytes)
+ }
+
+ #[test]
+ fn numbers_go_as_their_bytes() {
+ let (value, bytes) = round_trip(&0x0102_0304u32);
+ assert_eq!(value, 0x0102_0304);
+ assert_eq!(bytes, 0x0102_0304u32.to_ne_bytes());
+ assert_eq!(round_trip(&-5i64).0, -5);
+ assert_eq!(round_trip(&1.5f64).0, 1.5);
+ assert_eq!(round_trip(&usize::MAX).1.len(), 8);
+ }
+
+ #[test]
+ fn numeric_vectors_decode_from_one_payload() {
+ macro_rules! check {
+ ($($type:ty),*) => {$(
+ let values: Vec<$type> = vec![0 as $type, 1 as $type, <$type>::MIN, <$type>::MAX];
+ let (decoded, bytes) = round_trip(&values);
+ assert_eq!(decoded, values);
+ let mut expected = 4u32.to_ne_bytes().to_vec();
+ for value in &values {
+ expected.extend_from_slice(&value.to_ne_bytes());
+ }
+ assert_eq!(bytes, expected);
+ let mut encoder = Encoder::new();
+ encoder.encode_owned(values.clone()).unwrap();
+ assert_eq!(encoder.finish().0, bytes);
+ for length in 4..bytes.len() {
+ assert!(Decoder::new(&bytes[..length], []).decode::<Vec<$type>>().is_err());
+ }
+ assert!(Decoder::new(&0u32.to_ne_bytes(), []).decode::<Vec<$type>>().unwrap().is_empty());
+ assert!(<$type>::decode_vec(&mut Decoder::new(&[], []), usize::MAX).is_err());
+ )*};
+ }
+ check!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64, usize);
+ }
+
+ #[test]
+ fn booleans_go_as_one_byte_and_must_be_zero_or_one() {
+ assert_eq!(round_trip(&true).1, [1]);
+ let mut decoder = Decoder::new(&[2], []);
+ assert_eq!(decoder.decode::<bool>(), Err(DecodeError::InvalidBoolean(2)));
+ }
+
+ #[test]
+ fn strings_go_as_their_size_and_bytes() {
+ let (value, bytes) = round_trip(&"héllo".to_string());
+ assert_eq!(value, "héllo");
+ let mut expected = 6u32.to_ne_bytes().to_vec();
+ expected.extend_from_slice("héllo".as_bytes());
+ assert_eq!(bytes, expected);
+
+ let mut invalid = 1u32.to_ne_bytes().to_vec();
+ invalid.push(0xff);
+ assert_eq!(
+ Decoder::new(&invalid, []).decode::<String>(),
+ Err(DecodeError::InvalidUtf8)
+ );
+ }
+
+ #[test]
+ fn cpp_strings_preserve_lone_surrogates() {
+ for bytes in [b"".as_slice(), "héllo".as_bytes(), b"a\xed\xa0\x80\xed\xbf\xbfb"] {
+ let value = Utf8String::from_bytes(bytes.to_vec()).unwrap();
+ let (decoded, encoded) = round_trip(&value);
+ assert_eq!(decoded.as_bytes(), bytes);
+ assert_eq!(&encoded[4..], bytes);
+ assert_eq!(decoded.as_str().is_ok(), std::str::from_utf8(bytes).is_ok());
+ match decoded.into_string() {
+ Ok(string) => assert_eq!(string.as_bytes(), bytes),
+ Err(error) => assert_eq!(error.into_bytes(), bytes),
+ }
+ assert_eq!(value.into_bytes(), bytes);
+ }
+ assert_eq!(Utf8String::from("héllo").as_str(), Ok("héllo"));
+ assert_eq!(Utf8String::from("hello".to_string()).into_string().unwrap(), "hello");
+ for bytes in [
+ b"\xff".as_slice(),
+ b"\xc0\x80",
+ b"\xed\xa0",
+ b"\xed\xa0\x80\xff",
+ b"\xf4\x90\x80\x80",
+ ] {
+ assert_eq!(Utf8String::from_bytes(bytes.to_vec()), Err(DecodeError::InvalidUtf8));
+ let mut encoder = Encoder::new();
+ encoder.encode(bytes).unwrap();
+ assert_eq!(
+ Decoder::new(&encoder.finish().0, []).decode::<Utf8String>(),
+ Err(DecodeError::InvalidUtf8)
+ );
+ }
+ }
+
+ #[test]
+ fn utf8_validation_accepts_lonely_surrogates() {
+ assert_eq!(validate_utf8("héllo".as_bytes()), Ok(()));
+ assert_eq!(validate_utf8(b"a\xed\xa0\x80\xed\xbf\xbfb"), Ok(()));
+ for bytes in [
+ b"\xed\xa0".as_slice(),
+ b"\xed\xa0\x80\xff",
+ b"\xc0\x80",
+ b"\xf4\x90\x80\x80",
+ ] {
+ assert_eq!(validate_utf8(bytes), Err(DecodeError::InvalidUtf8));
+ }
+ }
+
+ #[test]
+ fn utf16_strings_go_as_ascii_bytes_when_they_can() {
+ let (value, bytes) = round_trip(&Utf16String::from("ab"));
+ assert_eq!(value.to_string_lossy(), "ab");
+ assert_eq!(bytes, [1, 2, 0, 0, 0, b'a', b'b']);
+
+ for units in [vec![], vec![0x7f], vec![0x80, 0xd800, 0xffff]] {
+ let value = Utf16String(units.clone());
+ let (decoded, bytes) = round_trip(&value);
+ assert_eq!(decoded, value);
+ let is_ascii = units.iter().all(|&unit| unit < 0x80);
+ let mut expected = vec![u8::from(is_ascii)];
+ expected.extend_from_slice(&(units.len() as u32).to_ne_bytes());
+ for unit in units {
+ if is_ascii {
+ expected.push(unit as u8);
+ } else {
+ expected.extend_from_slice(&unit.to_ne_bytes());
+ }
+ }
+ assert_eq!(bytes, expected);
+ }
+ }
+
+ #[test]
+ fn optionals_and_vectors_compose() {
+ let value: Vec<Option<u16>> = vec![Some(1), None, Some(3)];
+ assert_eq!(round_trip(&value).0, value);
+ let array = [1u8, 2, 3];
+ assert_eq!(round_trip(&array).0, array);
+ }
+
+ #[test]
+ fn large_byte_buffers_go_as_their_size_and_bytes() {
+ let buffer: Vec<u8> = (0..64 * 1024 * 1024 + 1).map(|index| index as u8).collect();
+ let (decoded, bytes) = round_trip(&buffer);
+ assert_eq!(decoded, buffer);
+ assert_eq!(bytes[..4], (buffer.len() as u32).to_ne_bytes());
+ assert_eq!(bytes[4..], buffer);
+ drop(buffer);
+ let mut encoder = Encoder::new();
+ encoder.encode_owned(decoded).unwrap();
+ assert_eq!(encoder.finish().0, bytes);
+ }
+
+ #[test]
+ fn sizes_are_bounded_by_the_remaining_input() {
+ let bytes = u32::MAX.to_ne_bytes();
+ assert_eq!(Decoder::new(&bytes, []).decode_size(), Err(DecodeError::UnexpectedEnd));
+ let bytes = [1, 0, 0, 0, 42];
+ let mut decoder = Decoder::new(&bytes, []);
+ assert_eq!(decoder.decode_size(), Ok(1));
+ assert_eq!(decoder.decode::<u8>(), Ok(42));
+ }
+
+ #[test]
+ fn truncated_input_is_refused() {
+ let bytes = 4u32.to_ne_bytes();
+ assert_eq!(
+ Decoder::new(&bytes, []).decode::<Vec<u8>>(),
+ Err(DecodeError::UnexpectedEnd)
+ );
+ assert_eq!(
+ Decoder::new(&[1, 2], []).decode::<u32>(),
+ Err(DecodeError::UnexpectedEnd)
+ );
+ }
+
+ #[test]
+ fn vector_counts_must_fit_the_element_encoding() {
+ let mut bytes = (64 * 1024 * 1024u32).to_ne_bytes().to_vec();
+ bytes.resize(1024 * 1024, 0);
+ assert_eq!(
+ Decoder::new(&bytes, []).decode::<Vec<String>>(),
+ Err(DecodeError::UnexpectedEnd)
+ );
+ let mut bytes = 2u32.to_ne_bytes().to_vec();
+ bytes.extend_from_slice(&1u64.to_ne_bytes());
+ assert_eq!(
+ Decoder::new(&bytes, []).decode::<Vec<u64>>(),
+ Err(DecodeError::UnexpectedEnd)
+ );
+ }
+
+ #[test]
+ fn vectors_grow_as_elements_decode() {
+ let value = vec!["a".to_string(); 100];
+ let decoded = round_trip(&value).0;
+ assert_eq!(decoded, value);
+ assert!(decoded.capacity() <= value.len() * 2);
+
+ let (reader, writer) = std::io::pipe().unwrap();
+ let bytes = 1u32.to_ne_bytes();
+ let attachments = [Attachment::from_fd(OwnedFd::from(writer)).unwrap()];
+ let files = Decoder::new(&bytes, attachments).decode::<Vec<File>>().unwrap();
+ assert_eq!(files.len(), 1);
+ drop(files);
+ drop(reader);
+ assert!(matches!(
+ Decoder::new(&bytes, []).decode::<Vec<File>>(),
+ Err(DecodeError::UnexpectedEnd)
+ ));
+ }
+
+ #[test]
+ fn a_vector_of_custom_types_decodes_before_reserving() {
+ struct LargeValue([u8; 8192]);
+ impl Decode for LargeValue {
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ decoder.decode::<bool>()?;
+ Ok(Self([0; 8192]))
+ }
+ }
+ let mut bytes = 1024u32.to_ne_bytes().to_vec();
+ bytes.resize(4 + 1024, 2);
+ assert!(matches!(
+ Decoder::new(&bytes, []).decode::<Vec<LargeValue>>(),
+ Err(DecodeError::InvalidBoolean(2))
+ ));
+ let bytes = [1, 0, 0, 0, 1];
+ let decoded = Decoder::new(&bytes, []).decode::<Vec<LargeValue>>().unwrap();
+ assert_eq!(decoded.capacity(), 1);
+ assert_eq!(decoded[0].0[0], 0);
+ }
+
+ #[test]
+ fn files_go_as_attachments() {
+ let (reader, writer) = std::io::pipe().unwrap();
+ let mut encoder = Encoder::new();
+ encoder.encode(&File(OwnedFd::from(writer))).unwrap();
+ let (bytes, attachments) = encoder.finish();
+ assert!(bytes.is_empty());
+ assert_eq!(attachments.len(), 1);
+
+ let mut decoder = Decoder::new(&bytes, attachments);
+ let File(fd) = decoder.decode().unwrap();
+ let mut writer = std::fs::File::from(fd);
+ std::io::Write::write_all(&mut writer, b"x").unwrap();
+ drop(writer);
+ let mut buffer = Vec::new();
+ std::io::Read::read_to_end(&mut std::fs::File::from(OwnedFd::from(reader)), &mut buffer).unwrap();
+ assert_eq!(buffer, b"x");
+ }
+
+ #[test]
+ fn owned_containers_move_their_files() {
+ use std::os::fd::AsRawFd;
+ let mut readers = Vec::new();
+ let mut descriptors = Vec::new();
+ let files: Vec<Option<[File; 1]>> = (0..32)
+ .map(|_| {
+ let (reader, writer) = std::io::pipe().unwrap();
+ readers.push(reader);
+ descriptors.push(writer.as_raw_fd());
+ Some([File(OwnedFd::from(writer))])
+ })
+ .collect();
+ let mut encoder = Encoder::new();
+ encoder.encode_owned(files).unwrap();
+ let (bytes, attachments) = encoder.finish();
+ let mut decoder = Decoder::new(&bytes, attachments);
+ assert_eq!(decoder.remaining_attachments(), 32);
+ let files = decoder.decode::<Vec<Option<[File; 1]>>>().unwrap();
+ assert_eq!(decoder.remaining_attachments(), 0);
+ for (file, descriptor) in files.into_iter().zip(descriptors) {
+ let [File(fd)] = file.unwrap();
+ #[cfg(not(target_vendor = "apple"))]
+ assert_eq!(fd.as_raw_fd(), descriptor);
+ #[cfg(target_vendor = "apple")]
+ let _ = descriptor;
+ drop(fd);
+ }
+ for mut reader in readers {
+ assert_eq!(std::io::Read::read(&mut reader, &mut [0]).unwrap(), 0);
+ }
+ }
+}
diff --git a/Tests/LibIPC/CMakeLists.txt b/Tests/LibIPC/CMakeLists.txt
index c48b4fb905c..f2dea4071ba 100644
--- a/Tests/LibIPC/CMakeLists.txt
+++ b/Tests/LibIPC/CMakeLists.txt
@@ -9,3 +9,7 @@ if (APPLE)
endif()
ladybird_test("TestConnection.cpp" LibIPC LIBS LibIPC LibThreading)
ladybird_test("TestDecoder.cpp" LibIPC LIBS LibIPC)
+
+if (NOT WIN32)
+ test_rust_crate(MANIFEST_PATH ../../Libraries/LibIPC/Rust/Cargo.toml CRATE_NAME libipc_rust)
+endif()