Truly independent web browser
LibIPC: Implement the Mach bootstrap with Rust
Aliaksandr Kalenikbb7997f7a6e1
diff --git a/Libraries/LibIPC/MachBootstrapListener.cpp b/Libraries/LibIPC/MachBootstrapListener.cppindex 1de5c9a89b9..3855a8a7f3a 100644--- a/Libraries/LibIPC/MachBootstrapListener.cpp+++ b/Libraries/LibIPC/MachBootstrapListener.cpp@@ -4,133 +4,46 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Debug.h>+#include <AK/Format.h>#include <LibIPC/MachBootstrapListener.h>-#include <LibIPC/MachBootstrapMessages.h>-#include <LibThreading/Thread.h>+#include <LibIPC/RustFFI.h>namespace IPC {MachBootstrapListener::MachBootstrapListener(ByteString server_port_name)- : m_thread(Threading::Thread::construct("MachBootstrapListener"sv, [this]() -> intptr_t { thread_loop(); return 0; }))- , m_server_port_name(move(server_port_name))-{- if (auto err = allocate_server_port(); err.is_error())- dbgln("Failed to allocate server port: {}", err.error());- else- start();+ : m_server_port_name(move(server_port_name))+{+ auto handle_request = [](void* listener, i32 pid, u32 task_name_port, u32 reply_port) {+ auto& self = *static_cast<MachBootstrapListener*>(listener);+ VERIFY(self.on_bootstrap_request);+ self.on_bootstrap_request({+ .pid = pid,+ .task_name_port = Core::MachPort::adopt_right(task_name_port, Core::MachPort::PortRight::Send),+ .reply_port = Core::MachPort::adopt_right(reply_port, Core::MachPort::PortRight::SendOnce),+ });+ };+ m_listener = FFI::ipc_mach_bootstrap_listener_create(m_server_port_name.bytes(), this, handle_request);+ if (!m_listener)+ dbgln("Failed to allocate server port");}MachBootstrapListener::~MachBootstrapListener(){- stop();-}--void MachBootstrapListener::start()-{- m_thread->start();+ if (!m_listener)+ return;+ // NB: Destroying the listener stops it, after which nothing reaches this object.+ FFI::ipc_mach_bootstrap_listener_destroy(m_listener);}void MachBootstrapListener::stop(){- if (!m_thread->needs_to_be_joined())- return;-- m_should_stop.store(true, MemoryOrder::memory_order_release);-- // NB: Wake the receive call without waiting for space in the queue. A full queue already wakes the listener.- mach_msg_header_t message {};- message.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);- message.msgh_size = sizeof(message);- message.msgh_remote_port = m_server_port_send_right.port();- auto const ret = mach_msg(&message, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(message), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);- VERIFY(ret == KERN_SUCCESS || ret == MACH_SEND_TIMED_OUT);-- VERIFY(!m_thread->join().is_error());+ if (m_listener)+ FFI::ipc_mach_bootstrap_listener_stop(m_listener);}bool MachBootstrapListener::is_initialized(){- return MACH_PORT_VALID(m_server_port_recv_right.port()) && MACH_PORT_VALID(m_server_port_send_right.port());-}--ErrorOr<void> MachBootstrapListener::allocate_server_port()-{- m_server_port_recv_right = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- m_server_port_send_right = TRY(m_server_port_recv_right.insert_right(Core::MachPort::MessageRight::MakeSend));- TRY(m_server_port_recv_right.register_with_bootstrap_server(m_server_port_name));-- dbgln_if(MACH_PORT_DEBUG, "Success! we created and attached mach port {:x} to bootstrap server with name {}", m_server_port_recv_right.port(), m_server_port_name);- return {};-}--// NB: Any process that can look up the server name can send to it, including a compromised helper. Check every field-// we rely on, so that a malformed message is dropped instead of crashing the browser or stopping the listener.-static bool is_valid_bootstrap_request(ReceivedMachMessage const& message)-{- auto const& header = message.header;- if (header.msgh_id != SELF_TASK_NAME_PORT_MESSAGE_ID)- return false;- if ((header.msgh_bits & MACH_MSGH_BITS_COMPLEX) == 0 || header.msgh_size != sizeof(MessageWithSelfTaskNamePort))- return false;- if (MACH_MSGH_BITS_LOCAL(header.msgh_bits) != MACH_MSG_TYPE_MOVE_SEND)- return false;-- // The reply port is optional, but when present it must be the send-once right the client made.- auto const reply_disposition = MACH_MSGH_BITS_REMOTE(header.msgh_bits);- if (header.msgh_remote_port != MACH_PORT_NULL && reply_disposition != MACH_MSG_TYPE_MOVE_SEND_ONCE)- return false;-- auto const& body = message.body;- if (body.body.msgh_descriptor_count != 1)- return false;- if (body.port_descriptor.type != MACH_MSG_PORT_DESCRIPTOR || body.port_descriptor.disposition != MACH_MSG_TYPE_MOVE_SEND)- return false;- return true;-}--void MachBootstrapListener::thread_loop()-{- while (!m_should_stop.load(MemoryOrder::memory_order_acquire)) {- ReceivedMachMessage message {};-- // Get the pid of the child from the audit trailer so we can associate the port w/it- mach_msg_options_t const options = MACH_RCV_MSG | MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_AUDIT) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);-- auto const ret = mach_msg(&message.header, options, 0, sizeof(message), m_server_port_recv_right.port(), MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);- if (ret == MACH_RCV_TOO_LARGE || ret == MACH_RCV_HEADER_ERROR || ret == MACH_RCV_BODY_ERROR || ret == MACH_RCV_INTERRUPTED) {- // NB: The kernel has already destroyed the message and its rights. The sender cannot stop the listener.- dbgln("Ignoring Mach bootstrap message that could not be received: {}", mach_error_string(ret));- continue;- }- if (ret != KERN_SUCCESS) {- dbgln("mach_msg failed: {}", mach_error_string(ret));- break;- }-- if (m_should_stop.load(MemoryOrder::memory_order_acquire)) {- mach_msg_destroy(&message.header);- break;- }-- if (!is_valid_bootstrap_request(message)) {- dbgln("Ignoring malformed Mach bootstrap message {:x}", message.header.msgh_id);- mach_msg_destroy(&message.header);- continue;- }-- // NB: The audit trailer follows the message body, so its position is only known for a well-formed request.- auto pid = static_cast<pid_t>(message.body.trailer.msgh_audit.val[5]);-- auto task_name_port = Core::MachPort::adopt_right(message.body.port_descriptor.name, Core::MachPort::PortRight::Send);-- // Extract reply port from the message header (kernel swaps local/remote on receive)- auto reply_port = Core::MachPort::adopt_right(message.header.msgh_remote_port, Core::MachPort::PortRight::SendOnce);-- dbgln_if(MACH_PORT_DEBUG, "Received bootstrap request from pid {} (task name port {:x}, reply port {:x})", pid, task_name_port.port(), reply_port.port());- VERIFY(on_bootstrap_request);- on_bootstrap_request({ pid, move(task_name_port), move(reply_port) });- }+ return m_listener;}}diff --git a/Libraries/LibIPC/MachBootstrapListener.h b/Libraries/LibIPC/MachBootstrapListener.hindex ccb1d8ecccc..15d94fb4a9a 100644--- a/Libraries/LibIPC/MachBootstrapListener.h+++ b/Libraries/LibIPC/MachBootstrapListener.h@@ -6,13 +6,11 @@#pragma once-#include <AK/Atomic.h>#include <AK/Function.h>#include <AK/Platform.h>#include <AK/String.h>#include <AK/kmalloc.h>#include <LibCore/MachPort.h>-#include <LibThreading/Forward.h>#if !defined(AK_OS_MACH)# error "MachBootstrapListener is only available on Mach kernel-based OS's"@@ -20,16 +18,22 @@namespace IPC {+namespace FFI {++struct BootstrapListener;++}+class MachBootstrapListener {AK_MAKE_NONCOPYABLE(MachBootstrapListener);public:AK_ALLOC_WITH_KMALLOC;+ // Registers a port under the name with the bootstrap server, and takes requests there on a thread of its own.explicit MachBootstrapListener(ByteString server_port_name);~MachBootstrapListener();- void start();void stop();bool is_initialized();@@ -44,15 +48,8 @@ public:ByteString const& server_port_name() const { return m_server_port_name; }private:- void thread_loop();- ErrorOr<void> allocate_server_port();-- NonnullRefPtr<Threading::Thread> m_thread;ByteString const m_server_port_name;- Core::MachPort m_server_port_recv_right;- Core::MachPort m_server_port_send_right;-- Atomic<bool> m_should_stop { false };+ FFI::BootstrapListener* m_listener { nullptr };};}diff --git a/Libraries/LibIPC/Rust/build.rs b/Libraries/LibIPC/Rust/build.rsindex bb0c2fbd244..c0f4e2cc94b 100644--- a/Libraries/LibIPC/Rust/build.rs+++ b/Libraries/LibIPC/Rust/build.rs@@ -34,12 +34,16 @@ fn main() -> Result<(), Box<dyn Error>> {config.export.rename.insert(rust_name.to_string(), cpp_name.to_string());}- let source = "src/cpp_mach_transport.rs";- println!("cargo:rerun-if-changed={source}");- cbindgen::Builder::new()- .with_config(config)- .with_src(manifest_dir.join(source))- .generate()?- .write_to_file(out_dir.join("RustFFI.h"));+ let mut sources = vec!["src/cpp_mach_transport.rs"];+ // NB: The bootstrap of a helper's transport only exists on macOS.+ if env::var("CARGO_CFG_TARGET_OS")? == "macos" {+ sources.push("src/cpp_mach_bootstrap.rs");+ }+ let mut builder = cbindgen::Builder::new().with_config(config);+ for source in sources {+ println!("cargo:rerun-if-changed={source}");+ builder = builder.with_src(manifest_dir.join(source));+ }+ builder.generate()?.write_to_file(out_dir.join("RustFFI.h"));Ok(())}diff --git a/Libraries/LibIPC/Rust/src/cpp_mach_bootstrap.rs b/Libraries/LibIPC/Rust/src/cpp_mach_bootstrap.rsnew file mode 100644index 00000000000..ca5066c4610--- /dev/null+++ b/Libraries/LibIPC/Rust/src/cpp_mach_bootstrap.rs@@ -0,0 +1,228 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Mach bootstrap as C++ `IPC::MachBootstrapListener`, `IPC::TransportBootstrapMachServer` and+//! `IPC::bootstrap_transport_from_server_port()` reach it.++#![allow(unsafe_code)]++use core::ffi::c_void;+use core::mem::ManuallyDrop;++use crate::mach::{self, BootstrapError, BootstrapRequest, MACH_PORT_NULL, MachPort, PortRight};+use crate::mach_bootstrap::{self as bootstrap, MachBootstrapListener, TransportBootstrapServer};+use crate::transport::MachPortPair;++/// What became of a request for the ports of this process's transport.+#[repr(C)]+pub enum BootstrapOutcome {+ Received,+ KernelError,+ ServerClosedBeforeReplying,+ MalformedReply,+}++fn borrowed(name: u32, right: PortRight) -> ManuallyDrop<MachPort> {+ ManuallyDrop::new(MachPort::adopt(name, right))+}++fn release(port: MachPort) -> u32 {+ ManuallyDrop::new(port).name()+}++fn optional_send_once_right(name: u32) -> Option<MachPort> {+ (name != MACH_PORT_NULL).then(|| MachPort::adopt(name, PortRight::SendOnce))+}++/// Asks the server behind a send right that the caller keeps for the ports of this process's transport. A kernel+/// failure leaves its code in `kernel_error`.+#[unsafe(no_mangle)]+pub extern "C" fn ipc_mach_bootstrap_transport_from_server_port(+ server_port: u32,+ reply_timeout_in_milliseconds: u32,+ receive_right: &mut u32,+ send_right: &mut u32,+ kernel_error: &mut i32,+) -> BootstrapOutcome {+ let server_port = borrowed(server_port, PortRight::Send);+ match mach::bootstrap_transport_from_server_port(&server_port, reply_timeout_in_milliseconds) {+ Ok((receive, send)) => {+ *receive_right = release(receive);+ *send_right = release(send);+ BootstrapOutcome::Received+ }+ Err(BootstrapError::Kernel { code, .. }) => {+ *kernel_error = code;+ BootstrapOutcome::KernelError+ }+ Err(BootstrapError::ServerClosedBeforeReplying) => BootstrapOutcome::ServerClosedBeforeReplying,+ Err(BootstrapError::MalformedReply) => BootstrapOutcome::MalformedReply,+ }+}++/// Takes bootstrap requests on a port it registers under the name, for as long as the listener lives.+pub struct BootstrapListener(MachBootstrapListener);++struct CppBootstrapRequestHandler {+ context: *mut c_void,+ handle: unsafe extern "C" fn(*mut c_void, i32, u32, u32),+}++// SAFETY: The C++ handler is made to run on the listener's thread.+unsafe impl Send for CppBootstrapRequestHandler {}++impl CppBootstrapRequestHandler {+ fn handle(&self, request: BootstrapRequest) {+ let reply_port = request.reply_port.map_or(MACH_PORT_NULL, release);+ // SAFETY: The handler takes over both rights, and the caller keeps the context valid while the listener lives.+ unsafe {+ (self.handle)(self.context, request.pid, release(request.task_name_port), reply_port);+ }+ }+}++/// A listener that hands each request to `handle_request` on its thread, with the requester's pid, its task name+/// port and its reply port, which may be null; or null if the port could not be registered.+///+/// # Safety+///+/// `context` must stay valid for `handle_request` until the listener is stopped, and the handler must take over both+/// rights.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_listener_create(+ server_port_name: ak::Span<'_, u8>,+ context: *mut c_void,+ handle_request: unsafe extern "C" fn(*mut c_void, i32, u32, u32),+) -> *mut BootstrapListener {+ let Ok(server_port_name) = core::str::from_utf8(server_port_name.as_slice()) else {+ return core::ptr::null_mut();+ };+ let handler = CppBootstrapRequestHandler {+ context,+ handle: handle_request,+ };+ match MachBootstrapListener::new(server_port_name, move |request| handler.handle(request)) {+ Ok(listener) => Box::into_raw(Box::new(BootstrapListener(listener))),+ Err(error) => {+ eprintln!("MachBootstrapListener: Unable to register {server_port_name}: {error}");+ core::ptr::null_mut()+ }+ }+}++/// Stops taking requests, and waits until the listener's thread is done.+#[unsafe(no_mangle)]+pub extern "C" fn ipc_mach_bootstrap_listener_stop(listener: &BootstrapListener) {+ listener.0.stop();+}++/// # Safety+///+/// The listener must be one from `ipc_mach_bootstrap_listener_create()` that nothing uses afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_listener_destroy(listener: *mut BootstrapListener) {+ // SAFETY: The caller gives the listener up.+ drop(unsafe { Box::from_raw(listener) });+}++/// Holds the ports of the transports of children that have yet to ask for them.+pub struct BootstrapServer(TransportBootstrapServer);++#[unsafe(no_mangle)]+pub extern "C" fn ipc_mach_bootstrap_server_create() -> *mut BootstrapServer {+ Box::into_raw(Box::new(BootstrapServer(TransportBootstrapServer::new())))+}++/// # Safety+///+/// The server must be one from `ipc_mach_bootstrap_server_create()` that nothing uses afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_server_destroy(server: *mut BootstrapServer) {+ // SAFETY: The caller gives the server up.+ drop(unsafe { Box::from_raw(server) });+}++/// # Safety+///+/// The caller must hand over a receive right and a send right.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_server_register_child_transport(+ server: &BootstrapServer,+ pid: i32,+ receive_right: u32,+ send_right: u32,+) {+ server.0.register_child_transport(+ pid,+ MachPortPair {+ receive_right: MachPort::adopt(receive_right, PortRight::Receive),+ send_right: MachPort::adopt(send_right, PortRight::Send),+ },+ );+}++#[unsafe(no_mangle)]+pub extern "C" fn ipc_mach_bootstrap_server_unregister_child_transport(server: &BootstrapServer, pid: i32) {+ server.0.unregister_child_transport(pid);+}++/// Takes the ports held for the child, answering false if none are.+#[unsafe(no_mangle)]+pub extern "C" fn ipc_mach_bootstrap_server_take_child_transport(+ server: &BootstrapServer,+ pid: i32,+ receive_right: &mut u32,+ send_right: &mut u32,+) -> bool {+ let Some(ports) = server.0.take_child_transport(pid) else {+ return false;+ };+ *receive_right = release(ports.receive_right);+ *send_right = release(ports.send_right);+ true+}++/// Answers a bootstrap request through its reply port, which may be null, with the ports of the requester's+/// transport, and returns the kernel's answer.+///+/// # Safety+///+/// The caller must hand over the reply port's send-once right, a receive right and a send right.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_send_transport_ports_to_child(+ reply_port: u32,+ receive_right: u32,+ send_right: u32,+) -> i32 {+ let result = mach::send_transport_ports_to_child(+ optional_send_once_right(reply_port),+ MachPort::adopt(receive_right, PortRight::Receive),+ MachPort::adopt(send_right, PortRight::Send),+ );+ result.err().unwrap_or(mach::KERN_SUCCESS)+}++/// Answers a bootstrap request through its reply port, which may be null, with the ports of a new transport, and+/// returns the kernel's answer and, on success, this end of the transport.+///+/// # Safety+///+/// The caller must hand over the reply port's send-once right.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn ipc_mach_bootstrap_create_on_demand_local_transport(+ reply_port: u32,+ receive_right: &mut u32,+ send_right: &mut u32,+) -> i32 {+ match bootstrap::create_on_demand_local_transport(optional_send_once_right(reply_port)) {+ Ok(ports) => {+ *receive_right = release(ports.receive_right);+ *send_right = release(ports.send_right);+ mach::KERN_SUCCESS+ }+ Err(error) => error,+ }+}diff --git a/Libraries/LibIPC/Rust/src/lib.rs b/Libraries/LibIPC/Rust/src/lib.rsindex d6669cd15e5..97af9244cd1 100644--- a/Libraries/LibIPC/Rust/src/lib.rs+++ b/Libraries/LibIPC/Rust/src/lib.rs@@ -25,6 +25,8 @@ mod rust_panic;pub mod attachment;pub mod cpp_connection;+#[cfg(all(target_os = "macos", feature = "cpp_transport"))]+pub mod cpp_mach_bootstrap;#[cfg(all(target_vendor = "apple", feature = "cpp_transport"))]pub mod cpp_mach_transport;mod receive_queue;@@ -55,6 +57,8 @@ fn validate_message_size(payload_size: usize, attachment_count: usize) -> std::i#[cfg(target_vendor = "apple")]pub mod mach;+#[cfg(target_os = "macos")]+pub mod mach_bootstrap;pub use attachment::Attachment;pub use wire::{diff --git a/Libraries/LibIPC/Rust/src/mach.rs b/Libraries/LibIPC/Rust/src/mach.rsindex 6272d13a4c8..288ccce95ea 100644--- a/Libraries/LibIPC/Rust/src/mach.rs+++ b/Libraries/LibIPC/Rust/src/mach.rs@@ -142,6 +142,7 @@ unsafe extern "C" {fn fileport_makefd(port: PortName) -> c_int;fn task_get_special_port(task: PortName, which_port: c_int, special_port: *mut PortName) -> KernReturn;fn bootstrap_look_up(bootstrap: PortName, service_name: *const c_char, service_port: *mut PortName) -> KernReturn;+ fn bootstrap_register(bootstrap: PortName, service_name: *mut c_char, service_port: PortName) -> KernReturn;}fn task_self() -> PortName {@@ -1246,7 +1247,9 @@ const SELF_TASK_NAME_PORT_MESSAGE_ID: i32 = 0x1234_CAFE;// NB: The same number as IPC_INLINE_DATA_MESSAGE_ID, but this reply only ever arrives on the bootstrap reply port.const IPC_CHANNEL_PORTS_MESSAGE_ID: i32 = 0x4950_C002;const BOOTSTRAP_SEND_TIMEOUT_MS: u32 = 100;-const BOOTSTRAP_REPLY_TIMEOUT_MS: u32 = 5000;+/// How long a helper waits for its bootstrap server to answer, unless it has a deadline of its own.+pub const DEFAULT_BOOTSTRAP_REPLY_TIMEOUT_IN_MILLISECONDS: u32 = 5000;+const BOOTSTRAP_REQUEST_SIZE: usize = HEADER_SIZE + BODY_SIZE + PORT_DESCRIPTOR_SIZE;/// Looks up a service that a process registered with the bootstrap server, as `Core::MachPort::look_up_from_bootstrap_server()`.pub fn look_up_from_bootstrap_server(service_name: &str) -> Result<MachPort, std::io::Error> {@@ -1260,16 +1263,58 @@ pub fn look_up_from_bootstrap_server(service_name: &str) -> Result<MachPort, stdOk(MachPort::adopt(port, PortRight::Send))}-fn bootstrap_error(step: &str, result: KernReturn) -> std::io::Error {- std::io::Error::other(format!("{step}: {}", KernelError(result)))+/// Registers a receive right with the bootstrap server, for other processes to look up by the name, as+/// `Core::MachPort::register_with_bootstrap_server()` does.+pub fn register_with_bootstrap_server(receive_right: &MachPort, service_name: &str) -> Result<(), std::io::Error> {+ assert_eq!(receive_right.right(), PortRight::Receive);+ // NB: A name_t holds 128 characters, including the terminating NUL.+ if service_name.len() > 127 {+ return Err(std::io::Error::from_raw_os_error(libc::E2BIG));+ }+ let name = std::ffi::CString::new(service_name).map_err(|_| std::io::ErrorKind::InvalidInput)?;+ // NB: The name is NUL-terminated, and the call makes a send right of its own from the receive right.+ let result = unsafe { bootstrap_register(bootstrap_port, name.as_ptr().cast_mut(), receive_right.name()) };+ if result != KERN_SUCCESS {+ return Err(KernelError(result).into());+ }+ Ok(())+}++/// Why a bootstrap request did not get this process the ports of its transport.+#[derive(Debug)]+pub enum BootstrapError {+ /// A Mach call failed, at a step of the exchange.+ Kernel {+ step: &'static str,+ code: KernReturn,+ },+ /// The server let go of the reply port without answering.+ ServerClosedBeforeReplying,+ MalformedReply,}+impl std::fmt::Display for BootstrapError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Kernel { step, code } => write!(formatter, "{step}: {}", error_string(*code)),+ Self::ServerClosedBeforeReplying => formatter.write_str("Mach bootstrap server closed before replying"),+ Self::MalformedReply => formatter.write_str("malformed Mach bootstrap reply"),+ }+ }+}++impl std::error::Error for BootstrapError {}+/// Asks a `TransportBootstrapMachServer` for the ports of this process's transport, as-/// `IPC::bootstrap_transport_from_server_port()` does.+/// `IPC::bootstrap_transport_from_server_port()` does, waiting no longer than the timeout for the reply.////// Returns the receive right and the send right of this end, in that order.-pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(MachPort, MachPort), std::io::Error> {- let reply_port = MachPort::allocate_receive_right().map_err(KernelError)?;+pub fn bootstrap_transport_from_server_port(+ server_port: &MachPort,+ reply_timeout_in_milliseconds: u32,+) -> Result<(MachPort, MachPort), BootstrapError> {+ let kernel_error = |step| move |code| BootstrapError::Kernel { step, code };+ let reply_port = MachPort::allocate_receive_right().map_err(kernel_error("allocating the reply port"))?;// NB: Send only the task name port. It is enough for task_info() statistics, while the task control port would// give the server full control over this process.@@ -1277,19 +1322,18 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(M// NB: raw_task_name_port points to a local that the call writes to.let result = unsafe { task_get_special_port(task_self(), TASK_NAME_PORT, &raw mut raw_task_name_port) };if result != KERN_SUCCESS {- return Err(bootstrap_error("getting the task name port", result));+ return Err(kernel_error("getting the task name port")(result));}let task_name_port = MachPort::adopt(raw_task_name_port, PortRight::Send);- let request_size = HEADER_SIZE + BODY_SIZE + PORT_DESCRIPTOR_SIZE;- let mut request = [0u32; (HEADER_SIZE + BODY_SIZE + PORT_DESCRIPTOR_SIZE) / size_of::<u32>()];+ let mut request = [0u32; BOOTSTRAP_REQUEST_SIZE / size_of::<u32>()];{// NB: All words are initialized and u8 alignment covers the entire slice.let bytes = unsafe { request.align_to_mut::<u8>().1 };write_header(bytes,msgh_bits(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX,- request_size,+ BOOTSTRAP_REQUEST_SIZE,server_port.name(),SELF_TASK_NAME_PORT_MESSAGE_ID,);@@ -1307,7 +1351,7 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(Mmach_msg(request.as_mut_ptr().cast(),MACH_SEND_MSG | MACH_SEND_TIMEOUT,- request_size as u32,+ BOOTSTRAP_REQUEST_SIZE as u32,0,MACH_PORT_NULL,BOOTSTRAP_SEND_TIMEOUT_MS,@@ -1319,7 +1363,7 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(M// NB: A timeout returns the copied rights and the made send-once right in this header.unsafe { mach_msg_destroy(request.as_mut_ptr().cast()) };}- return Err(bootstrap_error("sending the bootstrap request", result));+ return Err(kernel_error("sending the bootstrap request")(result));}drop(task_name_port);@@ -1333,12 +1377,12 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(M0,reply_capacity,reply_port.name(),- BOOTSTRAP_REPLY_TIMEOUT_MS,+ reply_timeout_in_milliseconds,MACH_PORT_NULL,)};if result != KERN_SUCCESS {- return Err(bootstrap_error("receiving the bootstrap reply", result));+ return Err(kernel_error("receiving the bootstrap reply")(result));}// NB: Whatever this function does not adopt goes back to the kernel with the message. Adopted names are cleared@@ -1348,29 +1392,21 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(Mlet bits = read_u32(bytes, 0).unwrap_or(0);let id = read_u32(bytes, 20).unwrap_or(0) as i32;if id == MACH_NOTIFY_SEND_ONCE {- return Err(std::io::Error::new(- std::io::ErrorKind::ConnectionRefused,- "Mach bootstrap server closed before replying",- ));+ return Err(BootstrapError::ServerClosedBeforeReplying);}- let malformed = || std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed Mach bootstrap reply");if id != IPC_CHANNEL_PORTS_MESSAGE_ID|| bits & MACH_MSGH_BITS_COMPLEX == 0|| read_u32(bytes, HEADER_SIZE) != Some(2){- return Err(malformed());+ return Err(BootstrapError::MalformedReply);}let receive_offset = HEADER_SIZE + BODY_SIZE;let send_offset = receive_offset + PORT_DESCRIPTOR_SIZE;- let descriptor = |offset: usize| {- let name = read_u32(bytes, offset)?;- let descriptor_bits = read_u32(bytes, offset + 8)?;- ((descriptor_bits >> 24) as u8 == MACH_MSG_PORT_DESCRIPTOR).then_some((name, (descriptor_bits >> 16) & 0xff))- };- let (Some((receive_name, MACH_MSG_TYPE_MOVE_RECEIVE)), Some((send_name, MACH_MSG_TYPE_MOVE_SEND))) =- (descriptor(receive_offset), descriptor(send_offset))- else {- return Err(malformed());+ let (Some((receive_name, MACH_MSG_TYPE_MOVE_RECEIVE)), Some((send_name, MACH_MSG_TYPE_MOVE_SEND))) = (+ read_port_descriptor(bytes, receive_offset),+ read_port_descriptor(bytes, send_offset),+ ) else {+ return Err(BootstrapError::MalformedReply);};write_u32(bytes, receive_offset, MACH_PORT_NULL);write_u32(bytes, send_offset, MACH_PORT_NULL);@@ -1381,6 +1417,156 @@ pub fn bootstrap_transport_from_server_port(server_port: &MachPort) -> Result<(M))}+// NB: The name and disposition of a port descriptor, if it is one.+fn read_port_descriptor(bytes: &[u8], offset: usize) -> Option<(PortName, u32)> {+ let name = read_u32(bytes, offset)?;+ let descriptor_bits = read_u32(bytes, offset + 8)?;+ ((descriptor_bits >> 24) as u8 == MACH_MSG_PORT_DESCRIPTOR).then_some((name, (descriptor_bits >> 16) & 0xff))+}++/// A request for the ports of a transport, from the process the audit trailer names.+pub struct BootstrapRequest {+ pub pid: i32,+ pub task_name_port: MachPort,+ /// The send-once right to answer through, which a request need not have.+ pub reply_port: Option<MachPort>,+}++pub enum ReceivedBootstrapRequest {+ Request(BootstrapRequest),+ /// A message that is not a well-formed request, which is dropped with what it carries, and what it was.+ Ignored(&'static str),+}++/// Waits for the next message on a bootstrap server's receive right. Any process that can look up the server's name+/// can send to it, so every field relied on is checked, and the sender of a malformed message can't make this fail.+pub fn receive_bootstrap_request(server_port: &MachPort) -> Result<ReceivedBootstrapRequest, KernReturn> {+ // NB: As <mach/message.h> lays out mach_msg_audit_trailer_t, and numbers its elements.+ const AUDIT_TRAILER_SIZE: usize = 52;+ const MACH_RCV_TRAILER_AUDIT: i32 = 3;+ const PID_OFFSET_IN_AUDIT_TRAILER: usize = 20 + 5 * size_of::<u32>();+ const MACH_RCV_INTERRUPTED: KernReturn = 0x1000_4005;++ let mut buffer = MessageBuffer::new(BOOTSTRAP_REQUEST_SIZE + AUDIT_TRAILER_SIZE);+ let capacity = buffer.size() as u32;+ // NB: The buffer is aligned for a header, and the call writes at most its size into it.+ let result = unsafe {+ mach_msg(+ buffer.header_pointer(),+ MACH_RCV_MSG | (MACH_RCV_TRAILER_AUDIT << 24),+ 0,+ capacity,+ server_port.name(),+ MACH_MSG_TIMEOUT_NONE,+ MACH_PORT_NULL,+ )+ };+ match result {+ MACH_MSG_SUCCESS => {}+ // NB: The kernel has already destroyed such a message and its rights.+ MACH_RCV_TOO_LARGE | MACH_RCV_HEADER_ERROR | MACH_RCV_BODY_ERROR | MACH_RCV_INTERRUPTED => {+ return Ok(ReceivedBootstrapRequest::Ignored(+ "a Mach bootstrap message that could not be received",+ ));+ }+ error => return Err(error),+ }++ let resources = MessageResources(&mut buffer);+ let bytes = resources.0.bytes_mut();+ let bits = read_u32(bytes, 0).unwrap_or(0);+ let size = read_u32(bytes, 4).unwrap_or(0) as usize;+ let reply_port = read_u32(bytes, 8).unwrap_or(MACH_PORT_NULL);+ let id = read_u32(bytes, 20).unwrap_or(0) as i32;+ let descriptor_offset = HEADER_SIZE + BODY_SIZE;+ let is_well_formed = id == SELF_TASK_NAME_PORT_MESSAGE_ID+ && bits & MACH_MSGH_BITS_COMPLEX != 0+ && size == BOOTSTRAP_REQUEST_SIZE+ && (bits >> 8) & 0x1f == MACH_MSG_TYPE_MOVE_SEND+ // NB: The reply port is optional, but when present it must be the send-once right the client made.+ && (reply_port == MACH_PORT_NULL || bits & 0x1f == MACH_MSG_TYPE_MOVE_SEND_ONCE)+ && read_u32(bytes, HEADER_SIZE) == Some(1)+ && matches!(read_port_descriptor(bytes, descriptor_offset), Some((_, MACH_MSG_TYPE_MOVE_SEND)));+ if !is_well_formed {+ return Ok(ReceivedBootstrapRequest::Ignored("a malformed Mach bootstrap message"));+ }++ // NB: The audit trailer follows the message, so its position is only known for a well-formed request.+ let pid = read_u32(bytes, BOOTSTRAP_REQUEST_SIZE + PID_OFFSET_IN_AUDIT_TRAILER).unwrap_or(0) as i32;+ let task_name_port = read_u32(bytes, descriptor_offset).unwrap_or(MACH_PORT_NULL);+ write_u32(bytes, descriptor_offset, MACH_PORT_NULL);+ write_u32(bytes, 8, MACH_PORT_NULL);+ drop(resources);+ Ok(ReceivedBootstrapRequest::Request(BootstrapRequest {+ pid,+ task_name_port: MachPort::adopt(task_name_port, PortRight::Send),+ reply_port: (reply_port != MACH_PORT_NULL).then(|| MachPort::adopt(reply_port, PortRight::SendOnce)),+ }))+}++/// Answers a bootstrap request with the ports of the requester's transport, which the reply moves.+pub fn send_transport_ports_to_child(+ reply_port: Option<MachPort>,+ receive_right: MachPort,+ send_right: MachPort,+) -> Result<(), KernReturn> {+ const REPLY_SIZE: usize = HEADER_SIZE + BODY_SIZE + 2 * PORT_DESCRIPTOR_SIZE;+ const SEND_TIMEOUT_MS: u32 = 5000;+ const MACH_SEND_INTERRUPTED: KernReturn = 0x1000_0007;++ let reply_port = reply_port.map_or(MACH_PORT_NULL, |port| std::mem::ManuallyDrop::new(port).name());+ let receive_right = std::mem::ManuallyDrop::new(receive_right);+ let send_right = std::mem::ManuallyDrop::new(send_right);+ let mut reply = MessageBuffer::new(REPLY_SIZE);+ {+ let bytes = reply.bytes_mut();+ write_header(+ bytes,+ msgh_bits(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0) | MACH_MSGH_BITS_COMPLEX,+ REPLY_SIZE,+ reply_port,+ IPC_CHANNEL_PORTS_MESSAGE_ID,+ );+ write_u32(bytes, HEADER_SIZE, 2);+ let mut offset = HEADER_SIZE + BODY_SIZE;+ for (name, disposition) in [+ (receive_right.name(), MACH_MSG_TYPE_MOVE_RECEIVE),+ (send_right.name(), MACH_MSG_TYPE_MOVE_SEND),+ ] {+ write_u32(bytes, offset, name);+ write_u32(+ bytes,+ offset + 8,+ (disposition << 16) | (u32::from(MACH_MSG_PORT_DESCRIPTOR) << 24),+ );+ offset += PORT_DESCRIPTOR_SIZE;+ }+ }+ // NB: The reply moves every right it names, and outlives the call.+ let result = unsafe {+ mach_msg(+ reply.header_pointer(),+ MACH_SEND_MSG | MACH_SEND_TIMEOUT,+ REPLY_SIZE as u32,+ 0,+ MACH_PORT_NULL,+ SEND_TIMEOUT_MS,+ MACH_PORT_NULL,+ )+ };+ if result == MACH_MSG_SUCCESS {+ return Ok(());+ }+ // NB: These errors leave the reply's rights with this task. The child may have exited before the reply.+ if matches!(+ result,+ MACH_SEND_INVALID_DEST | MACH_SEND_TIMED_OUT | MACH_SEND_INTERRUPTED | MACH_SEND_NO_BUFFER+ ) {+ drop(MessageResources(&mut reply));+ }+ Err(result)+}+#[cfg(test)]mod tests {use super::*;diff --git a/Libraries/LibIPC/Rust/src/mach_bootstrap.rs b/Libraries/LibIPC/Rust/src/mach_bootstrap.rsnew file mode 100644index 00000000000..67a87104690--- /dev/null+++ b/Libraries/LibIPC/Rust/src/mach_bootstrap.rs@@ -0,0 +1,412 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The server side of the Mach bootstrap, which hands a process that it spawned the ports of its transport.+//!+//! A helper looks up the name its spawner registered with the bootstrap server, and sends a request there with a+//! reply port. The listener takes requests on the registered port, and the server answers each with the ports it+//! holds for the requester's pid, or with a new transport.++use std::collections::HashMap;+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, MutexGuard};+use std::thread::JoinHandle;++use crate::mach::{self, BootstrapRequest, KernReturn, KernelError, MachPort, ReceivedBootstrapRequest};+use crate::transport::MachPortPair;++fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {+ mutex.lock().unwrap_or_else(|error| error.into_inner())+}++/// Takes the bootstrap requests that arrive on a port registered with the bootstrap server, on a thread of its own.+pub struct MachBootstrapListener {+ // NB: Shared with the listener's thread, and kept here as well, so that the port stays alive for the wakeup that+ // stop() sends even when the thread has already returned.+ #[expect(dead_code, reason = "Only held to keep the port alive")]+ server_receive_right: Arc<MachPort>,+ server_send_right: MachPort,+ should_stop: Arc<AtomicBool>,+ thread: Mutex<Option<JoinHandle<()>>>,+}++impl MachBootstrapListener {+ /// Registers a new port under the name, and hands each request that arrives there to `on_request`, on the+ /// listener's thread.+ pub fn new(+ server_port_name: &str,+ on_request: impl Fn(BootstrapRequest) + Send + 'static,+ ) -> std::io::Result<Self> {+ let server_receive_right = MachPort::allocate_receive_right().map_err(KernelError)?;+ let server_send_right = server_receive_right.make_send_right().map_err(KernelError)?;+ mach::register_with_bootstrap_server(&server_receive_right, server_port_name)?;+ let server_receive_right = Arc::new(server_receive_right);+ let should_stop = Arc::new(AtomicBool::new(false));+ let thread = std::thread::Builder::new()+ .name("MachBootstrapListener".to_string())+ .spawn({+ let server_receive_right = Arc::clone(&server_receive_right);+ let should_stop = Arc::clone(&should_stop);+ move || listen(&server_receive_right, &should_stop, on_request)+ })?;+ Ok(Self {+ server_receive_right,+ server_send_right,+ should_stop,+ thread: Mutex::new(Some(thread)),+ })+ }++ /// Stops taking requests, and waits until the listener's thread is done. Stopping again, or meanwhile, waits for+ /// that as well.+ pub fn stop(&self) {+ // NB: The lock is held through the join, so that a concurrent stop also returns only once the thread is done.+ let mut listener_thread = lock(&self.thread);+ let Some(thread) = listener_thread.take() else {+ return;+ };+ self.should_stop.store(true, Ordering::Release);+ // NB: Wake the receive without waiting for room in the queue. A full queue already wakes the listener.+ let result = mach::send_header_only_message(&self.server_send_right, 0, Some(0));+ assert!(+ result == mach::MACH_MSG_SUCCESS || result == mach::MACH_SEND_TIMED_OUT,+ "the bootstrap listener is woken"+ );+ let _ = thread.join();+ }+}++impl Drop for MachBootstrapListener {+ fn drop(&mut self) {+ self.stop();+ }+}++fn listen(server_receive_right: &MachPort, should_stop: &AtomicBool, on_request: impl Fn(BootstrapRequest)) {+ while !should_stop.load(Ordering::Acquire) {+ let received = match mach::receive_bootstrap_request(server_receive_right) {+ Ok(received) => received,+ Err(error) => {+ eprintln!("MachBootstrapListener: mach_msg failed: {}", mach::error_string(error));+ return;+ }+ };+ // NB: Dropping what arrived as the listener stops gives back what it carries.+ if should_stop.load(Ordering::Acquire) {+ return;+ }+ match received {+ ReceivedBootstrapRequest::Request(request) => on_request(request),+ ReceivedBootstrapRequest::Ignored(what) => eprintln!("MachBootstrapListener: Ignoring {what}"),+ }+ }+}++/// Answers a bootstrap request with the ports of a new transport, and returns this end of it.+pub fn create_on_demand_local_transport(reply_port: Option<MachPort>) -> Result<MachPortPair, KernReturn> {+ let local_receive_right = MachPort::allocate_receive_right()?;+ let local_send_right = local_receive_right.make_send_right()?;+ let remote_receive_right = MachPort::allocate_receive_right()?;+ let remote_send_right = remote_receive_right.make_send_right()?;++ // NB: Either peer may send messages before the other has constructed its transport.+ local_receive_right.raise_queue_limit();+ remote_receive_right.raise_queue_limit();++ mach::send_transport_ports_to_child(reply_port, remote_receive_right, local_send_right)?;+ Ok(MachPortPair {+ receive_right: local_receive_right,+ send_right: remote_send_right,+ })+}++struct ChildTransport {+ ports: MachPortPair,+ // NB: Tells the exit watcher which registration an exit belongs to, as a later child can get the pid of an earlier+ // one.+ serial: u64,+}++#[derive(Default)]+struct ChildTransports {+ by_pid: HashMap<i32, ChildTransport>,+ next_serial: u64,+}++/// Holds the ports of the transports of the children that have yet to ask for them. Until a child asks, nothing would+/// tell the other end of its transport that the child is gone, so the server lets go of the ports of a child that+/// exits before it asks, from a thread of its own.+pub struct TransportBootstrapServer {+ child_transports: Arc<Mutex<ChildTransports>>,+ child_exit_queue: Option<Arc<ChildExitQueue>>,+ child_exit_watcher: Mutex<Option<JoinHandle<()>>>,+}++impl Default for TransportBootstrapServer {+ fn default() -> Self {+ Self::new()+ }+}++impl TransportBootstrapServer {+ pub fn new() -> Self {+ let child_exit_queue = match ChildExitQueue::new() {+ Ok(queue) => Some(Arc::new(queue)),+ Err(error) => {+ eprintln!(+ "Unable to create the queue that reports children that exit before they take their transport: \+ {error}"+ );+ None+ }+ };+ Self {+ child_transports: Arc::default(),+ child_exit_queue,+ child_exit_watcher: Mutex::new(None),+ }+ }++ /// Holds the ports for the child until it asks for them, or exits. Ports still held for the pid are those of an+ /// earlier child that exited before it took them, and whose exit has not been handled yet. They are replaced.+ pub fn register_child_transport(&self, pid: i32, ports: MachPortPair) {+ let mut child_transports = lock(&self.child_transports);+ let serial = child_transports.next_serial;+ child_transports.next_serial += 1;++ if let Some(child_exit_queue) = &self.child_exit_queue {+ // NB: Without a watcher, nothing would let go of the ports of a child that exits before it asks, and the+ // other end of its transport would never hear that it is gone. Letting go of them now tells it.+ if !self.start_watching_for_child_exits(child_exit_queue) {+ return;+ }+ if let Err(error) = child_exit_queue.watch_for_exit(pid, serial) {+ // NB: The child is gone already, so it never takes these ports. Letting go of them tells the other+ // end.+ if error.raw_os_error() == Some(libc::ESRCH) {+ return;+ }+ eprintln!("Unable to watch for the exit of child {pid}: {error}");+ }+ }++ child_transports.by_pid.insert(pid, ChildTransport { ports, serial });+ }++ /// Lets go of the ports of a child that was ended before it asked for them.+ pub fn unregister_child_transport(&self, pid: i32) {+ drop(self.take_child_transport(pid));+ }++ /// Takes the ports held for the child, for it to have them.+ pub fn take_child_transport(&self, pid: i32) -> Option<MachPortPair> {+ // NB: The watch goes under the lock, or it could go after a registration for a new child with the same pid.+ let mut child_transports = lock(&self.child_transports);+ let taken = child_transports.by_pid.remove(&pid)?;+ self.stop_watching_for_child_exit(pid);+ drop(child_transports);+ Some(taken.ports)+ }++ // NB: Answers whether a watcher runs.+ fn start_watching_for_child_exits(&self, child_exit_queue: &Arc<ChildExitQueue>) -> bool {+ let mut child_exit_watcher = lock(&self.child_exit_watcher);+ if child_exit_watcher.is_some() {+ return true;+ }+ let child_exit_queue = Arc::clone(child_exit_queue);+ let child_transports = Arc::clone(&self.child_transports);+ match std::thread::Builder::new()+ .name("ChildExitWatch".to_string())+ .spawn(move || watch_for_child_exits(&child_exit_queue, &child_transports))+ {+ Ok(thread) => {+ *child_exit_watcher = Some(thread);+ true+ }+ Err(error) => {+ eprintln!("Unable to start watching for children that exit: {error}");+ false+ }+ }+ }++ fn stop_watching_for_child_exit(&self, pid: i32) {+ // NB: This fails for a child whose exit was reported already, which is fine.+ if let Some(child_exit_queue) = &self.child_exit_queue {+ child_exit_queue.stop_watching_for_exit(pid);+ }+ }+}++impl Drop for TransportBootstrapServer {+ fn drop(&mut self) {+ let Some(thread) = lock(&self.child_exit_watcher).take() else {+ return;+ };+ if let Some(child_exit_queue) = &self.child_exit_queue {+ child_exit_queue.wake_to_stop();+ }+ let _ = thread.join();+ }+}++fn watch_for_child_exits(child_exit_queue: &ChildExitQueue, child_transports: &Mutex<ChildTransports>) {+ loop {+ match child_exit_queue.wait() {+ Ok(ChildExitEvent::Exited { pid, serial }) => {+ let mut child_transports = lock(child_transports);+ if child_transports+ .by_pid+ .get(&pid)+ .is_some_and(|child_transport| child_transport.serial == serial)+ {+ child_transports.by_pid.remove(&pid);+ }+ }+ Ok(ChildExitEvent::Stop) => return,+ Ok(ChildExitEvent::Other) => {}+ Err(error) => {+ eprintln!("Unable to wait for children to exit: {error}");+ return;+ }+ }+ }+}++enum ChildExitEvent {+ Exited { pid: i32, serial: u64 },+ Stop,+ Other,+}++/// A kqueue that reports children that exit, and a user event that wakes its waiter to stop.+struct ChildExitQueue {+ kqueue: OwnedFd,+}++// NB: What wakes the child exit watcher when the server goes away.+const STOP_WATCHING_EVENT_IDENTIFIER: usize = 1;++impl ChildExitQueue {+ #[allow(unsafe_code)]+ fn new() -> std::io::Result<Self> {+ // SAFETY: kqueue() takes no arguments, and returns a new descriptor or -1.+ let raw = unsafe { libc::kqueue() };+ if raw < 0 {+ return Err(std::io::Error::last_os_error());+ }+ // SAFETY: The descriptor is new, and nothing else owns it.+ let queue = Self {+ kqueue: unsafe { OwnedFd::from_raw_fd(raw) },+ };+ queue.change(+ STOP_WATCHING_EVENT_IDENTIFIER,+ libc::EVFILT_USER,+ libc::EV_ADD | libc::EV_CLEAR,+ 0,+ 0,+ )?;+ Ok(queue)+ }++ fn watch_for_exit(&self, pid: i32, serial: u64) -> std::io::Result<()> {+ self.change(+ pid as usize,+ libc::EVFILT_PROC,+ libc::EV_ADD | libc::EV_ONESHOT,+ libc::NOTE_EXIT,+ serial as usize,+ )+ }++ fn stop_watching_for_exit(&self, pid: i32) {+ let _ = self.change(pid as usize, libc::EVFILT_PROC, libc::EV_DELETE, 0, 0);+ }++ fn wake_to_stop(&self) {+ self.change(+ STOP_WATCHING_EVENT_IDENTIFIER,+ libc::EVFILT_USER,+ 0,+ libc::NOTE_TRIGGER,+ 0,+ )+ .expect("the child exit watcher is woken");+ }++ #[allow(unsafe_code)]+ fn change(+ &self,+ identifier: usize,+ filter: i16,+ flags: u16,+ filter_flags: u32,+ data: usize,+ ) -> std::io::Result<()> {+ let change = libc::kevent {+ ident: identifier,+ filter,+ flags,+ fflags: filter_flags,+ data: 0,+ udata: data as *mut libc::c_void,+ };+ // SAFETY: The change list holds one initialized event, and the event list is empty.+ let result = unsafe {+ libc::kevent(+ self.kqueue.as_raw_fd(),+ &raw const change,+ 1,+ std::ptr::null_mut(),+ 0,+ std::ptr::null(),+ )+ };+ if result < 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ }++ #[allow(unsafe_code)]+ fn wait(&self) -> std::io::Result<ChildExitEvent> {+ loop {+ // SAFETY: An all-zero kevent is a valid value, which the call overwrites.+ let mut event: libc::kevent = unsafe { std::mem::zeroed() };+ // SAFETY: The event list holds room for one event, and the change list is empty.+ let count = unsafe {+ libc::kevent(+ self.kqueue.as_raw_fd(),+ std::ptr::null(),+ 0,+ &raw mut event,+ 1,+ std::ptr::null(),+ )+ };+ if count < 0 {+ let error = std::io::Error::last_os_error();+ if error.kind() == std::io::ErrorKind::Interrupted {+ continue;+ }+ return Err(error);+ }+ if count == 0 {+ continue;+ }+ return Ok(match event.filter {+ libc::EVFILT_USER => ChildExitEvent::Stop,+ libc::EVFILT_PROC => ChildExitEvent::Exited {+ pid: event.ident as i32,+ serial: event.udata as usize as u64,+ },+ _ => ChildExitEvent::Other,+ });+ }+ }+}diff --git a/Libraries/LibIPC/TransportBootstrapMach.cpp b/Libraries/LibIPC/TransportBootstrapMach.cppindex 9d5dd480c87..6830a154f17 100644--- a/Libraries/LibIPC/TransportBootstrapMach.cpp+++ b/Libraries/LibIPC/TransportBootstrapMach.cpp@@ -4,231 +4,66 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Assertions.h>#include <AK/ByteString.h>-#include <AK/Mutex.h>#include <AK/Optional.h>#include <LibCore/MachPort.h>-#include <LibCore/System.h>-#include <LibIPC/MachBootstrapMessages.h>+#include <LibIPC/RustFFI.h>#include <LibIPC/TransportBootstrapMach.h>-#include <LibIPC/TransportMachPort.h>-#include <LibThreading/Thread.h>--#include <errno.h>-#include <mach/mach.h>-#include <sys/event.h>-#include <unistd.h>namespace IPC {-ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port, AK::Duration reply_timeout)+static TransportBootstrapMachPorts adopt_transport_ports(u32 receive_right, u32 send_right){- auto reply_port = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));-- // NB: Send only the task name port. It is enough for task_info() statistics, while the task control port from- // mach_task_self() would give the server full control over this process, including its memory.- mach_port_t raw_task_name_port = MACH_PORT_NULL;- auto const name_port_result = task_get_special_port(mach_task_self(), TASK_NAME_PORT, &raw_task_name_port);- if (name_port_result != KERN_SUCCESS)- return Core::mach_error_to_error(name_port_result);- auto task_name_port = Core::MachPort::adopt_right(raw_task_name_port, Core::MachPort::PortRight::Send);-- MessageWithSelfTaskNamePort message {};- message.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX;- message.header.msgh_size = sizeof(message);- message.header.msgh_remote_port = server_port.port();- message.header.msgh_local_port = reply_port.port();- message.header.msgh_id = SELF_TASK_NAME_PORT_MESSAGE_ID;- message.body.msgh_descriptor_count = 1;- message.port_descriptor.name = task_name_port.port();- message.port_descriptor.disposition = MACH_MSG_TYPE_COPY_SEND;- message.port_descriptor.type = MACH_MSG_PORT_DESCRIPTOR;-- mach_msg_timeout_t const send_timeout = 100;- auto const send_result = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, message.header.msgh_size, 0, MACH_PORT_NULL, send_timeout, MACH_PORT_NULL);- if (send_result != KERN_SUCCESS)- return Core::mach_error_to_error(send_result);-- ReceivedIPCChannelPortsMessage reply {};- auto const recv_result = mach_msg(&reply.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(reply),- reply_port.port(), static_cast<mach_msg_timeout_t>(reply_timeout.to_milliseconds()), MACH_PORT_NULL);- if (recv_result != KERN_SUCCESS)- return Core::mach_error_to_error(recv_result);-- if (reply.header.msgh_id == MACH_NOTIFY_SEND_ONCE)- return Error::from_string_literal("Mach bootstrap server closed before replying");-- VERIFY(reply.header.msgh_id == IPC_CHANNEL_PORTS_MESSAGE_ID);- VERIFY(reply.body.msgh_descriptor_count == 2);- VERIFY(reply.receive_port.type == MACH_MSG_PORT_DESCRIPTOR);- VERIFY(reply.receive_port.disposition == MACH_MSG_TYPE_MOVE_RECEIVE);- VERIFY(reply.send_port.type == MACH_MSG_PORT_DESCRIPTOR);- VERIFY(reply.send_port.disposition == MACH_MSG_TYPE_MOVE_SEND);-return TransportBootstrapMachPorts {- .receive_right = Core::MachPort::adopt_right(reply.receive_port.name, Core::MachPort::PortRight::Receive),- .send_right = Core::MachPort::adopt_right(reply.send_port.name, Core::MachPort::PortRight::Send),+ .receive_right = Core::MachPort::adopt_right(receive_right, Core::MachPort::PortRight::Receive),+ .send_right = Core::MachPort::adopt_right(send_right, Core::MachPort::PortRight::Send),};}-ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_mach_server(StringView server_name)-{- auto server_port = TRY(Core::MachPort::look_up_from_bootstrap_server(ByteString { server_name }));- return bootstrap_transport_from_server_port(server_port);-}--ErrorOr<void> TransportBootstrapMachServer::send_transport_ports_to_child(Core::MachPort reply_port, TransportBootstrapMachPorts ports)+ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port, AK::Duration reply_timeout){- MessageWithIPCChannelPorts message {};- message.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0) | MACH_MSGH_BITS_COMPLEX;- message.header.msgh_size = sizeof(message);- message.header.msgh_remote_port = reply_port.release();- message.header.msgh_local_port = MACH_PORT_NULL;- message.header.msgh_id = IPC_CHANNEL_PORTS_MESSAGE_ID;- message.body.msgh_descriptor_count = 2;- message.receive_port.name = ports.receive_right.release();- message.receive_port.disposition = MACH_MSG_TYPE_MOVE_RECEIVE;- message.receive_port.type = MACH_MSG_PORT_DESCRIPTOR;- message.send_port.name = ports.send_right.release();- message.send_port.disposition = MACH_MSG_TYPE_MOVE_SEND;- message.send_port.type = MACH_MSG_PORT_DESCRIPTOR;-- mach_msg_timeout_t const timeout = 5000;- auto const ret = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(message), 0, MACH_PORT_NULL, timeout, MACH_PORT_NULL);- if (ret != KERN_SUCCESS) {- // NB: These errors leave the message's rights with the sender. The child may have exited before the reply.- if (ret == MACH_SEND_INVALID_DEST || ret == MACH_SEND_TIMED_OUT || ret == MACH_SEND_INTERRUPTED || ret == MACH_SEND_NO_BUFFER)- mach_msg_destroy(&message.header);- return Core::mach_error_to_error(ret);+ u32 receive_right = MACH_PORT_NULL;+ u32 send_right = MACH_PORT_NULL;+ i32 kernel_error = KERN_SUCCESS;+ auto const reply_timeout_in_milliseconds = static_cast<u32>(clamp<i64>(reply_timeout.to_milliseconds(), 0, NumericLimits<u32>::max()));+ switch (FFI::ipc_mach_bootstrap_transport_from_server_port(server_port.port(), reply_timeout_in_milliseconds, &receive_right, &send_right, &kernel_error)) {+ case FFI::BootstrapOutcome::Received:+ return adopt_transport_ports(receive_right, send_right);+ case FFI::BootstrapOutcome::KernelError:+ return Core::mach_error_to_error(kernel_error);+ case FFI::BootstrapOutcome::ServerClosedBeforeReplying:+ return Error::from_string_literal("Mach bootstrap server closed before replying");+ case FFI::BootstrapOutcome::MalformedReply:+ return Error::from_string_literal("Malformed Mach bootstrap reply");}- return {};+ VERIFY_NOT_REACHED();}-ErrorOr<TransportBootstrapMachPorts> TransportBootstrapMachServer::create_on_demand_local_transport(Core::MachPort reply_port)+ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_mach_server(StringView server_name){- auto local_receive_right = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- auto local_send_right = TRY(local_receive_right.insert_right(Core::MachPort::MessageRight::MakeSend));-- auto remote_receive_right = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- auto remote_send_right = TRY(remote_receive_right.insert_right(Core::MachPort::MessageRight::MakeSend));-- // Either peer may send messages before the other has constructed its transport.- TransportMachPort::raise_receive_queue_limit(local_receive_right);- TransportMachPort::raise_receive_queue_limit(remote_receive_right);-- TRY(send_transport_ports_to_child(move(reply_port), TransportBootstrapMachPorts {- .receive_right = move(remote_receive_right),- .send_right = move(local_send_right),- }));-- return TransportBootstrapMachPorts {- .receive_right = move(local_receive_right),- .send_right = move(remote_send_right),- };+ auto server_port = TRY(Core::MachPort::look_up_from_bootstrap_server(ByteString { server_name }));+ return bootstrap_transport_from_server_port(server_port);}-// What wakes the child exit watcher when the server goes away.-static constexpr uintptr_t stop_watching_event_identifier = 1;-TransportBootstrapMachServer::TransportBootstrapMachServer()- : m_child_exit_queue(kqueue())+ : m_server(FFI::ipc_mach_bootstrap_server_create()){- if (m_child_exit_queue < 0) {- dbgln("Unable to create the queue that reports children that exit before they take their transport: {}", Error::from_errno(errno));- return;- }-- struct kevent change {};- EV_SET(&change, stop_watching_event_identifier, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, nullptr);- VERIFY(kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) == 0);}TransportBootstrapMachServer::~TransportBootstrapMachServer(){- if (m_child_exit_watcher) {- struct kevent change {};- EV_SET(&change, stop_watching_event_identifier, EVFILT_USER, 0, NOTE_TRIGGER, 0, nullptr);- VERIFY(kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) == 0);- (void)m_child_exit_watcher->join();- }- if (m_child_exit_queue >= 0)- (void)::close(m_child_exit_queue);+ FFI::ipc_mach_bootstrap_server_destroy(m_server);}void TransportBootstrapMachServer::register_child_transport(pid_t pid, TransportBootstrapMachPorts ports){- // NB: Ports that are still registered for this PID are those of an earlier child that exited before it took them,- // and whose exit has not been handled yet. They are replaced.- auto serial = m_next_child_transport_serial++;-- if (m_child_exit_queue >= 0) {- if (!m_child_exit_watcher) {- m_child_exit_watcher = Threading::Thread::construct("ChildExitWatch"sv, [this]() -> intptr_t {- child_exit_watcher_loop();- return 0;- });- m_child_exit_watcher->start();- }-- // NB: The serial tells the watcher which registration an exit belongs to, as a later child can get the PID of- // an earlier one.- struct kevent change {};- EV_SET(&change, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, reinterpret_cast<void*>(static_cast<uintptr_t>(serial)));- if (kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) < 0) {- // The child is gone already, so it never takes these ports. Letting go of them tells the other end.- if (errno == ESRCH)- return;- dbgln("Unable to watch for the exit of child {}: {}", pid, Error::from_errno(errno));- }- }-- m_child_transports.set(pid, ChildTransport { move(ports), serial });-}--void TransportBootstrapMachServer::stop_watching_for_child_exit(pid_t pid)-{- if (m_child_exit_queue < 0)- return;- // NB: This fails for a child whose exit was reported already, which is fine.- struct kevent change {};- EV_SET(&change, pid, EVFILT_PROC, EV_DELETE, 0, 0, nullptr);- (void)kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr);+ FFI::ipc_mach_bootstrap_server_register_child_transport(m_server, pid, ports.receive_right.release(), ports.send_right.release());}void TransportBootstrapMachServer::unregister_child_transport(pid_t pid){MutexLocker locker(m_child_registration_mutex);- if (m_child_transports.remove(pid))- stop_watching_for_child_exit(pid);-}--void TransportBootstrapMachServer::child_exit_watcher_loop()-{- for (;;) {- struct kevent event {};- auto count = kevent(m_child_exit_queue, nullptr, 0, &event, 1, nullptr);- if (count < 0) {- if (errno == EINTR)- continue;- dbgln("Unable to wait for children to exit: {}", Error::from_errno(errno));- return;- }- if (count == 0)- continue;- if (event.filter == EVFILT_USER)- return;- if (event.filter != EVFILT_PROC)- continue;-- auto pid = static_cast<pid_t>(event.ident);- auto serial = static_cast<u64>(reinterpret_cast<uintptr_t>(event.udata));-- MutexLocker locker(m_child_registration_mutex);- auto child_transport = m_child_transports.get(pid);- if (child_transport.has_value() && child_transport->serial == serial)- m_child_transports.remove(pid);- }+ FFI::ipc_mach_bootstrap_server_unregister_child_transport(m_server, pid);}ErrorOr<TransportBootstrapMachServer::BootstrapRequestResult> TransportBootstrapMachServer::handle_bootstrap_request(pid_t pid, Core::MachPort reply_port)@@ -236,18 +71,26 @@ ErrorOr<TransportBootstrapMachServer::BootstrapRequestResult> TransportBootstrapOptional<TransportBootstrapMachPorts> child_transport;{MutexLocker locker(m_child_registration_mutex);- if (auto registered = m_child_transports.take(pid); registered.has_value()) {- stop_watching_for_child_exit(pid);- child_transport = move(registered->ports);- }+ u32 receive_right = MACH_PORT_NULL;+ u32 send_right = MACH_PORT_NULL;+ if (FFI::ipc_mach_bootstrap_server_take_child_transport(m_server, pid, &receive_right, &send_right))+ child_transport = adopt_transport_ports(receive_right, send_right);}if (child_transport.has_value()) {- TRY(send_transport_ports_to_child(move(reply_port), child_transport.release_value()));+ auto ports = child_transport.release_value();+ auto const result = FFI::ipc_mach_bootstrap_send_transport_ports_to_child(reply_port.release(), ports.receive_right.release(), ports.send_right.release());+ if (result != KERN_SUCCESS)+ return Core::mach_error_to_error(result);return ChildTransportHandled {};}- return OnDemandTransport { .ports = TRY(create_on_demand_local_transport(move(reply_port))) };+ u32 receive_right = MACH_PORT_NULL;+ u32 send_right = MACH_PORT_NULL;+ auto const result = FFI::ipc_mach_bootstrap_create_on_demand_local_transport(reply_port.release(), &receive_right, &send_right);+ if (result != KERN_SUCCESS)+ return Core::mach_error_to_error(result);+ return OnDemandTransport { .ports = adopt_transport_ports(receive_right, send_right) };}}diff --git a/Libraries/LibIPC/TransportBootstrapMach.h b/Libraries/LibIPC/TransportBootstrapMach.hindex 1e5706c9e19..78aebcb0303 100644--- a/Libraries/LibIPC/TransportBootstrapMach.h+++ b/Libraries/LibIPC/TransportBootstrapMach.h@@ -6,7 +6,6 @@#pragma once-#include <AK/HashMap.h>#include <AK/Platform.h>#include <AK/StringView.h>#include <AK/Time.h>@@ -17,12 +16,16 @@#endif#include <AK/Mutex.h>-#include <AK/RefPtr.h>#include <LibCore/MachPort.h>-#include <LibThreading/Forward.h>namespace IPC {+namespace FFI {++struct BootstrapServer;++}+struct TransportBootstrapMachPorts {Core::MachPort receive_right;Core::MachPort send_right;@@ -59,23 +62,8 @@ public:ErrorOr<BootstrapRequestResult> handle_bootstrap_request(pid_t, Core::MachPort reply_port);private:- static ErrorOr<void> send_transport_ports_to_child(Core::MachPort reply_port, TransportBootstrapMachPorts ports);- static ErrorOr<TransportBootstrapMachPorts> create_on_demand_local_transport(Core::MachPort reply_port);-- struct ChildTransport {- TransportBootstrapMachPorts ports;- u64 serial { 0 };- };-- void stop_watching_for_child_exit(pid_t);- void child_exit_watcher_loop();-Mutex m_child_registration_mutex;- HashMap<pid_t, ChildTransport> m_child_transports;- u64 m_next_child_transport_serial { 1 };-- int m_child_exit_queue { -1 };- RefPtr<Threading::Thread> m_child_exit_watcher;+ FFI::BootstrapServer* m_server { nullptr };};}diff --git a/Services/WebRTCClient/src/lib.rs b/Services/WebRTCClient/src/lib.rsindex eb5415fc480..9e1c9668d02 100644--- a/Services/WebRTCClient/src/lib.rs+++ b/Services/WebRTCClient/src/lib.rs@@ -61,7 +61,8 @@ fn take_over_transport(server_name: &str) -> Result<Transport> {let server_port = mach::look_up_from_bootstrap_server(server_name).with_context(|| format!("looking up Mach server '{server_name}'"))?;let (receive_right, send_right) =- mach::bootstrap_transport_from_server_port(&server_port).context("bootstrapping the transport")?;+ mach::bootstrap_transport_from_server_port(&server_port, mach::DEFAULT_BOOTSTRAP_REPLY_TIMEOUT_IN_MILLISECONDS)+ .context("bootstrapping the transport")?;Ok(Transport::new(receive_right, send_right)?)}