Skip to content

Truly independent web browser

LibIPC+LibWeb: Move the raw attachment helpers into LibIPC

Aliaksandr Kalenik8496e4a36619
diff --git a/Libraries/LibIPC/CMakeLists.txt b/Libraries/LibIPC/CMakeLists.txt
index 2cdddb3e206..78e32f77f1d 100644
--- a/Libraries/LibIPC/CMakeLists.txt
+++ b/Libraries/LibIPC/CMakeLists.txt
@@ -5,6 +5,7 @@ set(SOURCES
Encoder.cpp
File.cpp
Message.cpp
+ RawAttachment.cpp
ReceivedMessageBytes.cpp
StartupTransport.cpp
TransportHandle.cpp
diff --git a/Libraries/LibIPC/RawAttachment.cpp b/Libraries/LibIPC/RawAttachment.cpp
new file mode 100644
index 00000000000..ffc7c5843b6
--- /dev/null
+++ b/Libraries/LibIPC/RawAttachment.cpp
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibIPC/RawAttachment.h>
+
+namespace IPC {
+
+Vector<Attachment> adopt_raw_attachments(ReadonlySpan<RawAttachment> raw_attachments)
+{
+ Vector<Attachment> attachments;
+ for (auto const& raw : raw_attachments) {
+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
+ auto disposition = static_cast<Core::MachPort::MessageRight>(raw.disposition);
+ auto right = Core::MachPort::PortRight::Send;
+ if (disposition == Core::MachPort::MessageRight::MoveReceive || disposition == Core::MachPort::MessageRight::MakeSend || disposition == Core::MachPort::MessageRight::MakeSendOnce)
+ right = Core::MachPort::PortRight::Receive;
+ else if (disposition == Core::MachPort::MessageRight::MoveSendOnce)
+ right = Core::MachPort::PortRight::SendOnce;
+ attachments.append(Attachment::from_mach_port(Core::MachPort::adopt_right(static_cast<mach_port_t>(raw.value), right), disposition));
+#else
+ attachments.append(Attachment::from_fd(raw.value));
+#endif
+ }
+ return attachments;
+}
+
+Vector<RawAttachment> release_raw_attachments(Vector<Attachment> attachments)
+{
+ Vector<RawAttachment> raw;
+ for (auto& attachment : attachments) {
+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
+ auto disposition = to_underlying(attachment.message_right());
+ raw.append({ static_cast<int>(attachment.release_mach_port().release()), disposition });
+#else
+ raw.append({ attachment.to_fd(), 0 });
+#endif
+ }
+ return raw;
+}
+
+}
diff --git a/Libraries/LibIPC/RawAttachment.h b/Libraries/LibIPC/RawAttachment.h
new file mode 100644
index 00000000000..fc4eca029b8
--- /dev/null
+++ b/Libraries/LibIPC/RawAttachment.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Span.h>
+#include <AK/Types.h>
+#include <AK/Vector.h>
+#include <LibIPC/Attachment.h>
+
+namespace IPC {
+
+// A Mach port name and its disposition on Apple, and a descriptor elsewhere.
+struct RawAttachment {
+ int value;
+ u32 disposition;
+};
+
+Vector<Attachment> adopt_raw_attachments(ReadonlySpan<RawAttachment>);
+Vector<RawAttachment> release_raw_attachments(Vector<Attachment>);
+
+}
diff --git a/Libraries/LibIPC/Rust/src/cpp_connection.rs b/Libraries/LibIPC/Rust/src/cpp_connection.rs
new file mode 100644
index 00000000000..c41fb4490d6
--- /dev/null
+++ b/Libraries/LibIPC/Rust/src/cpp_connection.rs
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What Rust and a connection whose transport C++ owns hand each other.
+
+#![allow(unsafe_code)]
+
+use core::ffi::c_int;
+
+use crate::attachment::Attachment;
+
+/// A Mach port name and its disposition on Apple, and a descriptor elsewhere: `IPC::RawAttachment`.
+#[repr(C)]
+pub struct RawAttachment {
+ value: c_int,
+ disposition: u32,
+}
+
+impl RawAttachment {
+ /// # Safety
+ ///
+ /// The raw attachment must hand over one owned descriptor or Mach right.
+ unsafe fn into_attachment(self) -> Attachment {
+ #[cfg(target_vendor = "apple")]
+ {
+ use crate::mach::{
+ MACH_MSG_TYPE_MAKE_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE, MACH_MSG_TYPE_MOVE_RECEIVE,
+ MACH_MSG_TYPE_MOVE_SEND_ONCE, MachPort, PortRight,
+ };
+ let right = match self.disposition {
+ MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MAKE_SEND | MACH_MSG_TYPE_MAKE_SEND_ONCE => {
+ PortRight::Receive
+ }
+ MACH_MSG_TYPE_MOVE_SEND_ONCE => PortRight::SendOnce,
+ _ => PortRight::Send,
+ };
+ Attachment::from_mach_port(MachPort::adopt(self.value as u32, right), self.disposition)
+ }
+ #[cfg(all(unix, not(target_vendor = "apple")))]
+ {
+ use std::os::fd::FromRawFd;
+ // SAFETY: The caller hands over the descriptor.
+ Attachment::from(unsafe { std::os::fd::OwnedFd::from_raw_fd(self.value) })
+ }
+ #[cfg(windows)]
+ {
+ // SAFETY: The caller hands over the descriptor.
+ Attachment::from_descriptor(unsafe { crate::transport_windows::OwnedDescriptor::from_raw(self.value) })
+ }
+ }
+
+ /// # Safety
+ ///
+ /// Each of the raw attachments must hand over its descriptor or Mach right.
+ pub unsafe fn take_all(raw: &[Self]) -> Vec<Attachment> {
+ raw.iter()
+ .map(|attachment| {
+ let owned = Self {
+ value: attachment.value,
+ disposition: attachment.disposition,
+ };
+ // SAFETY: The caller hands over what each raw attachment names.
+ unsafe { owned.into_attachment() }
+ })
+ .collect()
+ }
+
+ pub fn from_attachment(attachment: Attachment) -> Self {
+ #[cfg(target_vendor = "apple")]
+ {
+ let (port, disposition) = attachment.into_mach_port();
+ Self {
+ value: core::mem::ManuallyDrop::new(port).name() as c_int,
+ disposition,
+ }
+ }
+ #[cfg(all(unix, not(target_vendor = "apple")))]
+ {
+ use std::os::fd::IntoRawFd;
+ Self {
+ value: attachment
+ .into_fd()
+ .expect("a Unix attachment is a descriptor")
+ .into_raw_fd(),
+ disposition: 0,
+ }
+ }
+ #[cfg(windows)]
+ {
+ Self {
+ value: attachment.into_descriptor().into_raw(),
+ disposition: 0,
+ }
+ }
+ }
+}
diff --git a/Libraries/LibIPC/Rust/src/lib.rs b/Libraries/LibIPC/Rust/src/lib.rs
index ae0a524874f..d1dda00f19b 100644
--- a/Libraries/LibIPC/Rust/src/lib.rs
+++ b/Libraries/LibIPC/Rust/src/lib.rs
@@ -11,6 +11,7 @@
#![deny(unsafe_code)]
pub mod attachment;
+pub mod cpp_connection;
mod receive_queue;
#[cfg(all(unix, not(target_vendor = "apple")))]
mod shared_memory;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
index 8b77ab55cd5..f8d328d686e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
@@ -1041,7 +1041,7 @@ impl SocketTransport {
) -> bool {
// SAFETY: The read lends its VM, rooted result list and bytes, and hands over every attachment.
let (vm, records) = unsafe { &*context.cast::<(&Vm, &MarkedVec<'_, TransferRecordRef>)>() };
- let attachments = unsafe { RawAttachment::take_all(attachments, count) };
+ let attachments = unsafe { RawAttachment::take_all(ak::slice_from_raw_parts(attachments, count)) };
let mut decoder = Decoder::new(bytes.as_slice(), attachments);
match TransferRecord::decode(vm, &mut decoder) {
Ok(record) => {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
index db477956faf..3001337c23c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/transfer_data_holder.rs
@@ -8,7 +8,8 @@
//! https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects
use core::cell::RefCell;
-use core::ffi::{c_int, c_void};
+use core::ffi::c_void;
+pub(crate) use libipc_rust::cpp_connection::RawAttachment;
use libipc_rust::{Attachment, Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};
use std::collections::VecDeque;
@@ -16,92 +17,6 @@ use crate::html::message_port::TransportHandle;
use crate::html::port_channel::{PortChannelEnd, claim_parked_end, park_end};
use crate::html::structured_serialize::transfer_record::PortMessage;
-#[repr(C)]
-pub(crate) struct RawAttachment {
- value: c_int,
- disposition: u32,
-}
-
-impl RawAttachment {
- /// # Safety
- ///
- /// The raw attachment must hand over one owned descriptor or Mach right.
- unsafe fn into_attachment(self) -> Attachment {
- #[cfg(target_vendor = "apple")]
- {
- use libipc_rust::mach::{
- MACH_MSG_TYPE_MAKE_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE, MACH_MSG_TYPE_MOVE_RECEIVE,
- MACH_MSG_TYPE_MOVE_SEND_ONCE, MachPort, PortRight,
- };
- let right = match self.disposition {
- MACH_MSG_TYPE_MOVE_RECEIVE | MACH_MSG_TYPE_MAKE_SEND | MACH_MSG_TYPE_MAKE_SEND_ONCE => {
- PortRight::Receive
- }
- MACH_MSG_TYPE_MOVE_SEND_ONCE => PortRight::SendOnce,
- _ => PortRight::Send,
- };
- Attachment::from_mach_port(MachPort::adopt(self.value as u32, right), self.disposition)
- }
- #[cfg(all(unix, not(target_vendor = "apple")))]
- {
- use std::os::fd::FromRawFd;
- Attachment::from(unsafe { std::os::fd::OwnedFd::from_raw_fd(self.value) })
- }
- #[cfg(windows)]
- {
- Attachment::from_descriptor(unsafe {
- libipc_rust::transport_windows::OwnedDescriptor::from_raw(self.value)
- })
- }
- }
-
- /// # Safety
- ///
- /// `raw` must point to `count` raw attachments, each of which hands over its descriptor or Mach right.
- pub(crate) unsafe fn take_all(raw: *const Self, count: usize) -> Vec<Attachment> {
- // SAFETY: The caller lends the raw attachments and hands over what each one names.
- unsafe { ak::slice_from_raw_parts(raw, count) }
- .iter()
- .map(|attachment| {
- let owned = Self {
- value: attachment.value,
- disposition: attachment.disposition,
- };
- unsafe { owned.into_attachment() }
- })
- .collect()
- }
-
- pub(crate) fn from_attachment(attachment: Attachment) -> Self {
- #[cfg(target_vendor = "apple")]
- {
- let (port, disposition) = attachment.into_mach_port();
- Self {
- value: core::mem::ManuallyDrop::new(port).name() as c_int,
- disposition,
- }
- }
- #[cfg(all(unix, not(target_vendor = "apple")))]
- {
- use std::os::fd::IntoRawFd;
- Self {
- value: attachment
- .into_fd()
- .expect("a Unix attachment is a descriptor")
- .into_raw_fd(),
- disposition: 0,
- }
- }
- #[cfg(windows)]
- {
- Self {
- value: attachment.into_descriptor().into_raw(),
- disposition: 0,
- }
- }
- }
-}
-
pub(crate) type ReceivePayload = unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, *const RawAttachment, usize);
unsafe extern "C" {
@@ -245,7 +160,7 @@ impl TransferPayload {
count: usize,
) {
// SAFETY: The caller lends this result slot and bytes, and transfers every raw attachment.
- let attachments = unsafe { RawAttachment::take_all(attachments, count) };
+ let attachments = unsafe { RawAttachment::take_all(ak::slice_from_raw_parts(attachments, count)) };
unsafe {
*context.cast::<Option<Self>>() = Some(Self::new(bytes.as_slice().to_vec(), attachments));
};
diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cpp
index 0412187f901..1805e930111 100644
--- a/Libraries/LibWeb/HTML/MessagePort.cpp
+++ b/Libraries/LibWeb/HTML/MessagePort.cpp
@@ -217,7 +217,7 @@ void web_bindings_transport_handle_take(IPC::TransportHandle* handle, void* cont
IPC::MessageBuffer buffer;
IPC::Encoder encoder(buffer);
MUST(encoder.encode(*owner));
- auto attachments = release_transfer_attachments(buffer.take_attachments());
+ auto attachments = IPC::release_raw_attachments(buffer.take_attachments());
receive(context, buffer.data().span(), attachments.data(), attachments.size());
}
@@ -225,7 +225,7 @@ IPC::Transport* web_bindings_transport_handle_create_transport(ReadonlyBytes byt
{
FixedMemoryStream stream(bytes);
Queue<IPC::Attachment> queue;
- for (auto& attachment : adopt_transfer_attachments(attachments, count))
+ for (auto& attachment : IPC::adopt_raw_attachments({ attachments, count }))
queue.enqueue(move(attachment));
IPC::Decoder decoder(stream, queue);
auto handle = MUST(decoder.decode<IPC::TransportHandle>());
@@ -236,7 +236,7 @@ bool web_bindings_message_port_transport_send(IPC::Transport* transport, Readonl
{
IPC::MessageDataType data;
MUST(data.try_append(bytes.data(), bytes.size()));
- IPC::MessageBuffer buffer { move(data), adopt_transfer_attachments(attachments, count) };
+ IPC::MessageBuffer buffer { move(data), IPC::adopt_raw_attachments({ attachments, count }) };
if (auto result = buffer.transfer_message(*transport); result.is_error()) {
dbgln("Failed to post message: {}", result.error());
return false;
@@ -254,7 +254,7 @@ bool web_bindings_message_port_transport_read_messages(IPC::Transport* transport
Vector<IPC::Attachment> attachments;
while (!message.attachments.is_empty())
attachments.append(message.attachments.dequeue());
- auto raw_attachments = release_transfer_attachments(move(attachments));
+ auto raw_attachments = IPC::release_raw_attachments(move(attachments));
failed_to_decode = !receive(context, message.bytes.bytes(), raw_attachments.data(), raw_attachments.size());
});
return failed_to_decode || should_shutdown == IPC::Transport::ShouldShutdown::Yes;
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index 53007b57dfa..870ad419351 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -19,6 +19,7 @@
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
#include <LibIPC/Message.h>
+#include <LibIPC/RawAttachment.h>
#include <LibJS/Forward.h>
#include <LibJS/Runtime/Object.h>
#include <LibWeb/Bindings/IntrinsicDefinitions.h>
@@ -35,14 +36,7 @@ class HostObject;
namespace Web::HTML {
-// A Mach port name and its disposition on Apple, and a descriptor elsewhere.
-struct TransferAttachment {
- int value;
- u32 disposition;
-};
-
-Vector<IPC::Attachment> adopt_transfer_attachments(TransferAttachment const*, size_t count);
-Vector<TransferAttachment> release_transfer_attachments(Vector<IPC::Attachment>);
+using TransferAttachment = IPC::RawAttachment;
struct StructuredSerializeOptions {
GC::RootVector<GC::Ref<JS::Object>> transfer;
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index bcf2d8cd0e5..35ff552f260 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -36,43 +36,6 @@ using namespace Web::HTML;
using ReceiveTransferPayload = void (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t);
-namespace Web::HTML {
-
-Vector<IPC::Attachment> adopt_transfer_attachments(TransferAttachment const* raw, size_t count)
-{
- Vector<IPC::Attachment> attachments;
- for (size_t i = 0; i < count; ++i) {
-#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
- auto disposition = static_cast<Core::MachPort::MessageRight>(raw[i].disposition);
- auto right = Core::MachPort::PortRight::Send;
- if (disposition == Core::MachPort::MessageRight::MoveReceive || disposition == Core::MachPort::MessageRight::MakeSend || disposition == Core::MachPort::MessageRight::MakeSendOnce)
- right = Core::MachPort::PortRight::Receive;
- else if (disposition == Core::MachPort::MessageRight::MoveSendOnce)
- right = Core::MachPort::PortRight::SendOnce;
- attachments.append(IPC::Attachment::from_mach_port(Core::MachPort::adopt_right(static_cast<mach_port_t>(raw[i].value), right), disposition));
-#else
- attachments.append(IPC::Attachment::from_fd(raw[i].value));
-#endif
- }
- return attachments;
-}
-
-Vector<TransferAttachment> release_transfer_attachments(Vector<IPC::Attachment> attachments)
-{
- Vector<TransferAttachment> raw;
- for (auto& attachment : attachments) {
-#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
- auto disposition = to_underlying(attachment.message_right());
- raw.append({ static_cast<int>(attachment.release_mach_port().release()), disposition });
-#else
- raw.append({ attachment.to_fd(), 0 });
-#endif
- }
- return raw;
-}
-
-}
-
extern "C" {
void web_structured_serialize_set_ipc_record(IPCSerializationRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);
@@ -218,14 +181,14 @@ TransferDataEncoder* web_structured_serialize_transfer_data_holder_create(Readon
{
IPC::MessageDataType data;
MUST(data.try_append(bytes.data(), bytes.size()));
- return new TransferDataEncoder(IPC::MessageBuffer { move(data), adopt_transfer_attachments(attachments, count) });
+ return new TransferDataEncoder(IPC::MessageBuffer { move(data), IPC::adopt_raw_attachments({ attachments, count }) });
}
void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder* holder, void* context, ReceiveTransferPayload receive)
{
auto owner = adopt_own(*holder);
auto buffer = owner->take_buffer();
- auto attachments = release_transfer_attachments(buffer.take_attachments());
+ auto attachments = IPC::release_raw_attachments(buffer.take_attachments());
receive(context, buffer.data().span(), attachments.data(), attachments.size());
}