Skip to content

Truly independent web browser

LibIPC+Meta: Let an IPC message name Rust as its receiver or sender

Aliaksandr Kalenik948d0a8d4647
diff --git a/Cargo.lock b/Cargo.lock
index fc13e2c51fb..56594e31464 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1802,6 +1802,7 @@ dependencies = [
name = "libipc_rust"
version = "0.1.0"
dependencies = [
+ "ak",
"libc",
]
diff --git a/Libraries/LibIPC/CMakeLists.txt b/Libraries/LibIPC/CMakeLists.txt
index 78e32f77f1d..b0668ce5d8a 100644
--- a/Libraries/LibIPC/CMakeLists.txt
+++ b/Libraries/LibIPC/CMakeLists.txt
@@ -6,8 +6,10 @@ set(SOURCES
File.cpp
Message.cpp
RawAttachment.cpp
+ RawMessage.cpp
ReceivedMessageBytes.cpp
StartupTransport.cpp
+ ThreadSafeMessagePoster.cpp
TransportHandle.cpp
)
diff --git a/Libraries/LibIPC/Connection.cpp b/Libraries/LibIPC/Connection.cpp
index 40d36192084..7b1d62807ac 100644
--- a/Libraries/LibIPC/Connection.cpp
+++ b/Libraries/LibIPC/Connection.cpp
@@ -202,7 +202,7 @@ ConnectionBase::PeerEOF ConnectionBase::drain_messages_from_peer()
bool parse_error = false;
auto schedule_shutdown = m_transport->read_as_many_messages_as_possible_without_blocking([&](auto&& raw_message) {
auto bytes = raw_message.bytes.bytes();
- if (auto message = try_parse_message(bytes, raw_message.attachments)) {
+ if (auto message = try_parse_message(raw_message.bytes, raw_message.attachments)) {
m_unprocessed_messages.append(message.release_nonnull());
} else {
dbgln("Failed to parse IPC message {:hex-dump}", bytes);
diff --git a/Libraries/LibIPC/Connection.h b/Libraries/LibIPC/Connection.h
index 5a06d13bf2f..6a3b46d5ee5 100644
--- a/Libraries/LibIPC/Connection.h
+++ b/Libraries/LibIPC/Connection.h
@@ -19,6 +19,8 @@
#include <LibIPC/Attachment.h>
#include <LibIPC/Forward.h>
#include <LibIPC/Message.h>
+#include <LibIPC/RawMessage.h>
+#include <LibIPC/ReceivedMessageBytes.h>
#include <LibIPC/Transport.h>
namespace IPC {
@@ -127,7 +129,7 @@ protected:
explicit ConnectionBase(IPC::Stub&, NonnullOwnPtr<Transport>, u32 local_endpoint_magic);
virtual void shutdown_with_error(Error const&);
- virtual OwnPtr<Message> try_parse_message(ReadonlyBytes, Queue<Attachment>&) = 0;
+ virtual OwnPtr<Message> try_parse_message(ReceivedMessageBytes const&, Queue<Attachment>&) = 0;
ErrorOr<void> post_sync_request(Message const&);
OwnPtr<IPC::Message> wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id, MayCancel = MayCancel::No);
@@ -165,8 +167,18 @@ public:
}
protected:
- virtual OwnPtr<Message> try_parse_message(ReadonlyBytes bytes, Queue<Attachment>& attachments) override
+ virtual OwnPtr<Message> try_parse_message(ReceivedMessageBytes const& received_bytes, Queue<Attachment>& attachments) override
{
+ auto bytes = received_bytes.bytes();
+ if (auto header = RawMessage::read_header(bytes); header.has_value() && header->endpoint_magic == LocalEndpoint::static_magic()) {
+ if (auto message_name = LocalEndpoint::name_of_request_that_arrives_raw(header->message_id); message_name.has_value()) {
+ Vector<Attachment> attachments_of_message;
+ while (!attachments.is_empty())
+ attachments_of_message.append(attachments.dequeue());
+ return make<RawMessage>(*header, *message_name, received_bytes, move(attachments_of_message));
+ }
+ }
+
auto local_message = LocalEndpoint::decode_message(bytes, attachments);
if (!local_message.is_error())
return local_message.release_value();
diff --git a/Libraries/LibIPC/RawAttachment.cpp b/Libraries/LibIPC/RawAttachment.cpp
index ffc7c5843b6..4182e4445f7 100644
--- a/Libraries/LibIPC/RawAttachment.cpp
+++ b/Libraries/LibIPC/RawAttachment.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibIPC/Message.h>
#include <LibIPC/RawAttachment.h>
namespace IPC {
@@ -41,4 +42,11 @@ Vector<RawAttachment> release_raw_attachments(Vector<Attachment> attachments)
return raw;
}
+MessageBuffer adopt_encoded_message(ReadonlyBytes bytes, ReadonlySpan<RawAttachment> attachments)
+{
+ MessageDataType data;
+ MUST(data.try_append(bytes.data(), bytes.size()));
+ return { move(data), adopt_raw_attachments(attachments) };
+}
+
}
diff --git a/Libraries/LibIPC/RawAttachment.h b/Libraries/LibIPC/RawAttachment.h
index fc4eca029b8..209577bcb0f 100644
--- a/Libraries/LibIPC/RawAttachment.h
+++ b/Libraries/LibIPC/RawAttachment.h
@@ -10,6 +10,7 @@
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibIPC/Attachment.h>
+#include <LibIPC/Forward.h>
namespace IPC {
@@ -18,8 +19,10 @@ struct RawAttachment {
int value;
u32 disposition;
};
+static_assert(sizeof(RawAttachment) == 8, "RawAttachment of libipc_rust is written to match this by hand");
Vector<Attachment> adopt_raw_attachments(ReadonlySpan<RawAttachment>);
Vector<RawAttachment> release_raw_attachments(Vector<Attachment>);
+MessageBuffer adopt_encoded_message(ReadonlyBytes, ReadonlySpan<RawAttachment>);
}
diff --git a/Libraries/LibIPC/RawMessage.cpp b/Libraries/LibIPC/RawMessage.cpp
new file mode 100644
index 00000000000..f2f28a8ad54
--- /dev/null
+++ b/Libraries/LibIPC/RawMessage.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ByteReader.h>
+#include <LibIPC/RawMessage.h>
+
+namespace IPC {
+
+Optional<RawMessage::Header> RawMessage::read_header(ReadonlyBytes bytes)
+{
+ if (bytes.size() < sizeof(u32) + sizeof(i32))
+ return {};
+ Header header;
+ AK::ByteReader::load(bytes.data(), header.endpoint_magic);
+ AK::ByteReader::load(bytes.data() + sizeof(u32), header.message_id);
+ return header;
+}
+
+RawMessage::RawMessage(Header header, StringView message_name, ReceivedMessageBytes bytes, Vector<Attachment> attachments)
+ : m_header(header)
+ , m_message_name(message_name)
+ , m_bytes(move(bytes))
+ , m_attachments(move(attachments))
+{
+}
+
+RawMessage::~RawMessage() = default;
+
+ErrorOr<MessageBuffer> RawMessage::encode() const
+{
+ return Error::from_string_literal("A message that arrived undecoded cannot be encoded");
+}
+
+RawMessage::OutcomeInRust RawMessage::hand_to_rust(Function<void(FfiRawMessage)> const& hand_over)
+{
+ auto attachments = release_raw_attachments(move(m_attachments));
+ OutcomeInRust outcome;
+ hand_over({
+ .bytes_including_header = m_bytes.bytes(),
+ .attachments = attachments,
+ .outcome = &outcome,
+ .respond = [](void* outcome, ReadonlyBytes bytes, ReadonlySpan<RawAttachment> attachments) { static_cast<OutcomeInRust*>(outcome)->response = make<MessageBuffer>(adopt_encoded_message(bytes, attachments)); },
+ .did_misbehave = [](void* outcome, ReadonlyBytes what_the_peer_did) { static_cast<OutcomeInRust*>(outcome)->misbehavior = ByteString { what_the_peer_did }; },
+ });
+ return outcome;
+}
+
+}
diff --git a/Libraries/LibIPC/RawMessage.h b/Libraries/LibIPC/RawMessage.h
new file mode 100644
index 00000000000..14fed57569e
--- /dev/null
+++ b/Libraries/LibIPC/RawMessage.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteString.h>
+#include <AK/Function.h>
+#include <AK/Optional.h>
+#include <AK/OwnPtr.h>
+#include <AK/StringView.h>
+#include <AK/Vector.h>
+#include <LibIPC/Attachment.h>
+#include <LibIPC/Message.h>
+#include <LibIPC/RawAttachment.h>
+#include <LibIPC/ReceivedMessageBytes.h>
+
+namespace IPC {
+
+// A message as Rust is handed it, with where what Rust makes of it goes: `libipc_rust::cpp_connection::RawMessage`.
+struct FfiRawMessage {
+ ReadonlyBytes bytes_including_header;
+ ReadonlySpan<RawAttachment> attachments;
+ void* outcome;
+ void (*respond)(void* outcome, ReadonlyBytes, ReadonlySpan<RawAttachment>);
+ void (*did_misbehave)(void* outcome, ReadonlyBytes what_the_peer_did);
+};
+static_assert(sizeof(FfiRawMessage) == 7 * sizeof(void*), "RawMessage of libipc_rust is written to match this by hand");
+
+class RawMessage final : public Message {
+public:
+ struct Header {
+ u32 endpoint_magic { 0 };
+ i32 message_id { 0 };
+ };
+ static Optional<Header> read_header(ReadonlyBytes);
+
+ RawMessage(Header, StringView message_name, ReceivedMessageBytes, Vector<Attachment>);
+ virtual ~RawMessage() override;
+
+ virtual u32 endpoint_magic() const override { return m_header.endpoint_magic; }
+ virtual int message_id() const override { return m_header.message_id; }
+ virtual StringView message_name() const override { return m_message_name; }
+ virtual ErrorOr<MessageBuffer> encode() const override;
+
+ struct OutcomeInRust {
+ // What the sender did that it must not do, for which its connection is closed.
+ Optional<ByteString> misbehavior;
+ // The response of a synchronous message.
+ OwnPtr<MessageBuffer> response;
+ };
+ // Rust decodes the message and hands it to a stub of its endpoint, which `hand_over` reaches with what it is given.
+ OutcomeInRust hand_to_rust(Function<void(FfiRawMessage)> const& hand_over);
+
+private:
+ Header m_header;
+ StringView m_message_name;
+ ReceivedMessageBytes m_bytes;
+ Vector<Attachment> m_attachments;
+};
+
+}
diff --git a/Libraries/LibIPC/Rust/Cargo.toml b/Libraries/LibIPC/Rust/Cargo.toml
index 9c484fc39f8..c638d6f23bb 100644
--- a/Libraries/LibIPC/Rust/Cargo.toml
+++ b/Libraries/LibIPC/Rust/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
+ak = { path = "../../../AK/Rust" }
libc = "0.2"
[lints]
diff --git a/Libraries/LibIPC/Rust/src/cpp_connection.rs b/Libraries/LibIPC/Rust/src/cpp_connection.rs
index c41fb4490d6..3c793221ba0 100644
--- a/Libraries/LibIPC/Rust/src/cpp_connection.rs
+++ b/Libraries/LibIPC/Rust/src/cpp_connection.rs
@@ -4,13 +4,15 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What Rust and a connection whose transport C++ owns hand each other.
+//! Messages that Rust encodes and decodes on a connection whose transport C++ owns: what a C++ `IPC::Connection`
+//! hands over undecoded, and what it posts for Rust.
#![allow(unsafe_code)]
-use core::ffi::c_int;
+use core::ffi::{c_int, c_void};
use crate::attachment::Attachment;
+use crate::wire::{DispatchError, EncodeError, EncodedMessage, EndpointMessage, Misbehavior};
/// A Mach port name and its disposition on Apple, and a descriptor elsewhere: `IPC::RawAttachment`.
#[repr(C)]
@@ -97,3 +99,111 @@ impl RawAttachment {
}
}
}
+
+/// A message that a C++ connection received and hands over undecoded, with where what Rust makes of it goes:
+/// `IPC::FfiRawMessage`.
+#[repr(C)]
+pub struct RawMessage<'a> {
+ bytes_including_header: ak::Span<'a, u8>,
+ attachments: ak::Span<'a, RawAttachment>,
+ outcome: *mut c_void,
+ respond: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>),
+ did_misbehave: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),
+}
+
+impl RawMessage<'_> {
+ /// Has `dispatch`, the dispatcher of the message's endpoint over a stub, decode the message and hand it to that
+ /// stub. The connection gets the response of a synchronous message, or what its peer did that it must not do.
+ ///
+ /// # Safety
+ ///
+ /// The message must be one `IPC::RawMessage::hand_to_rust()` made, which is handed to a stub once.
+ pub unsafe fn hand_to(
+ self,
+ dispatch: impl FnOnce(&[u8], Vec<Attachment>) -> Result<Option<EncodedMessage>, DispatchError>,
+ ) {
+ // SAFETY: The C++ message hands over what each of its raw attachments names.
+ let attachments = unsafe { RawAttachment::take_all(self.attachments.as_slice()) };
+ let did_misbehave = |what_the_peer_did: &str| {
+ // SAFETY: The C++ message copies the text.
+ unsafe { (self.did_misbehave)(self.outcome, ak::Span::new(what_the_peer_did.as_bytes())) };
+ };
+ match dispatch(self.bytes_including_header.as_slice(), attachments) {
+ Ok(None) => {}
+ Ok(Some((bytes, attachments))) => {
+ let raw_attachments: Vec<RawAttachment> =
+ attachments.into_iter().map(RawAttachment::from_attachment).collect();
+ // SAFETY: The C++ message copies the bytes and takes every attachment over.
+ unsafe { (self.respond)(self.outcome, ak::Span::new(&bytes), ak::Span::new(&raw_attachments)) };
+ }
+ Err(DispatchError::Decode(error)) => did_misbehave(&format!("Message does not decode: {error:?}")),
+ Err(DispatchError::Misbehavior(Misbehavior(what_the_peer_did))) => did_misbehave(what_the_peer_did),
+ Err(DispatchError::EncodeResponse(error)) => panic!("The response to a message does not encode: {error:?}"),
+ }
+ }
+}
+
+/// One reference to an `IPC::ThreadSafeMessagePoster`, and how to reach it: `IPC::FfiThreadSafeMessagePoster`.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiThreadSafeMessagePoster {
+ poster_with_one_reference: *mut c_void,
+ try_post: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, RawAttachment>) -> bool,
+ r#ref: unsafe extern "C" fn(*mut c_void),
+ unref: unsafe extern "C" fn(*mut c_void),
+}
+
+const _: () = {
+ assert!(size_of::<RawAttachment>() == 8);
+ assert!(size_of::<RawMessage<'_>>() == 7 * size_of::<usize>());
+ assert!(size_of::<FfiThreadSafeMessagePoster>() == 4 * size_of::<usize>());
+};
+
+/// Posts messages to the transport of a C++ connection from any thread.
+pub struct ThreadSafeMessagePoster(FfiThreadSafeMessagePoster);
+
+// SAFETY: The C++ poster counts its references atomically and posts under its own lock.
+unsafe impl Send for ThreadSafeMessagePoster {}
+unsafe impl Sync for ThreadSafeMessagePoster {}
+
+impl ThreadSafeMessagePoster {
+ /// # Safety
+ ///
+ /// `ffi` must hold one reference to a live `IPC::ThreadSafeMessagePoster`, which the caller gives up.
+ pub unsafe fn adopt(ffi: FfiThreadSafeMessagePoster) -> Self {
+ Self(ffi)
+ }
+
+ /// Answers whether the peer could still be reached.
+ pub fn try_post<M: EndpointMessage>(&self, message: M) -> Result<bool, EncodeError> {
+ let (bytes, attachments) = message.encode_message()?;
+ Ok(self.try_post_encoded(&bytes, attachments))
+ }
+
+ pub fn try_post_encoded(&self, bytes: &[u8], attachments: Vec<Attachment>) -> bool {
+ let raw_attachments: Vec<RawAttachment> = attachments.into_iter().map(RawAttachment::from_attachment).collect();
+ // SAFETY: This holds a reference to the poster, which copies the bytes and takes every attachment over.
+ unsafe {
+ (self.0.try_post)(
+ self.0.poster_with_one_reference,
+ ak::Span::new(bytes),
+ ak::Span::new(&raw_attachments),
+ )
+ }
+ }
+}
+
+impl Clone for ThreadSafeMessagePoster {
+ fn clone(&self) -> Self {
+ // SAFETY: This holds a reference to the poster.
+ unsafe { (self.0.r#ref)(self.0.poster_with_one_reference) };
+ Self(self.0)
+ }
+}
+
+impl Drop for ThreadSafeMessagePoster {
+ fn drop(&mut self) {
+ // SAFETY: This gives up the reference it holds.
+ unsafe { (self.0.unref)(self.0.poster_with_one_reference) };
+ }
+}
diff --git a/Libraries/LibIPC/Rust/src/lib.rs b/Libraries/LibIPC/Rust/src/lib.rs
index d1dda00f19b..e7e5410c20e 100644
--- a/Libraries/LibIPC/Rust/src/lib.rs
+++ b/Libraries/LibIPC/Rust/src/lib.rs
@@ -42,7 +42,10 @@ fn validate_message_size(payload_size: usize, attachment_count: usize) -> std::i
pub mod mach;
pub use attachment::Attachment;
-pub use wire::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, EndpointMessage};
+pub use wire::{
+ Decode, DecodeError, Decoder, DispatchError, Encode, EncodeError, EncodedMessage, Encoder, EndpointMessage,
+ Misbehavior,
+};
#[cfg(all(test, unix))]
mod tests {
diff --git a/Libraries/LibIPC/Rust/src/wire.rs b/Libraries/LibIPC/Rust/src/wire.rs
index 672c6a85e53..bb5b493940b 100644
--- a/Libraries/LibIPC/Rust/src/wire.rs
+++ b/Libraries/LibIPC/Rust/src/wire.rs
@@ -634,6 +634,39 @@ pub fn decode_message_header(decoder: &mut Decoder<'_>) -> Result<(u32, i32), De
Ok((decoder.decode()?, decoder.decode()?))
}
+/// A message as it goes to a transport: its bytes, which start with its header, and its attachments.
+pub type EncodedMessage = (Vec<u8>, Vec<Attachment>);
+
+/// What a peer did that it must not do, for which its connection is closed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Misbehavior(pub &'static str);
+
+/// Why the stub of an endpoint did not get to answer a message.
+#[derive(Debug)]
+pub enum DispatchError {
+ Decode(DecodeError),
+ Misbehavior(Misbehavior),
+ EncodeResponse(EncodeError),
+}
+
+impl From<DecodeError> for DispatchError {
+ fn from(error: DecodeError) -> Self {
+ Self::Decode(error)
+ }
+}
+
+impl From<Misbehavior> for DispatchError {
+ fn from(misbehavior: Misbehavior) -> Self {
+ Self::Misbehavior(misbehavior)
+ }
+}
+
+impl From<EncodeError> for DispatchError {
+ fn from(error: EncodeError) -> Self {
+ Self::EncodeResponse(error)
+ }
+}
+
#[cfg(all(test, unix))]
mod tests {
use super::*;
diff --git a/Libraries/LibIPC/ThreadSafeMessagePoster.cpp b/Libraries/LibIPC/ThreadSafeMessagePoster.cpp
new file mode 100644
index 00000000000..86f5d068441
--- /dev/null
+++ b/Libraries/LibIPC/ThreadSafeMessagePoster.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibIPC/Message.h>
+#include <LibIPC/ThreadSafeMessagePoster.h>
+
+namespace IPC {
+
+bool ThreadSafeMessagePoster::try_post(MessageBuffer& buffer)
+{
+ MutexLocker locker(m_mutex);
+ if (!m_transport || !m_transport->is_open())
+ return false;
+ return !buffer.transfer_message(*m_transport).is_error();
+}
+
+void ThreadSafeMessagePoster::detach_from_transport()
+{
+ MutexLocker locker(m_mutex);
+ m_transport = nullptr;
+}
+
+static bool try_post_bytes_and_raw_attachments(void* poster, ReadonlyBytes bytes, ReadonlySpan<RawAttachment> attachments)
+{
+ auto buffer = adopt_encoded_message(bytes, attachments);
+ return static_cast<ThreadSafeMessagePoster*>(poster)->try_post(buffer);
+}
+
+FfiThreadSafeMessagePoster ThreadSafeMessagePoster::to_ffi_with_one_reference()
+{
+ ref();
+ return {
+ .poster_with_one_reference = this,
+ .try_post = try_post_bytes_and_raw_attachments,
+ .ref = [](void* poster) { static_cast<ThreadSafeMessagePoster*>(poster)->ref(); },
+ .unref = [](void* poster) { static_cast<ThreadSafeMessagePoster*>(poster)->unref(); },
+ };
+}
+
+}
diff --git a/Libraries/LibIPC/ThreadSafeMessagePoster.h b/Libraries/LibIPC/ThreadSafeMessagePoster.h
new file mode 100644
index 00000000000..d11b40cc6e9
--- /dev/null
+++ b/Libraries/LibIPC/ThreadSafeMessagePoster.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/Mutex.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Span.h>
+#include <LibIPC/Forward.h>
+#include <LibIPC/RawAttachment.h>
+#include <LibIPC/Transport.h>
+
+namespace IPC {
+
+struct FfiThreadSafeMessagePoster {
+ void* poster_with_one_reference;
+ bool (*try_post)(void* poster, ReadonlyBytes, ReadonlySpan<RawAttachment>);
+ void (*ref)(void* poster);
+ void (*unref)(void* poster);
+};
+static_assert(sizeof(FfiThreadSafeMessagePoster) == 4 * sizeof(void*), "FfiThreadSafeMessagePoster of libipc_rust is written to match this by hand");
+
+class ThreadSafeMessagePoster final : public AtomicRefCounted<ThreadSafeMessagePoster> {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ static NonnullRefPtr<ThreadSafeMessagePoster> create(Transport& transport) { return adopt_ref(*new ThreadSafeMessagePoster(transport)); }
+
+ [[nodiscard]] bool try_post(MessageBuffer&);
+ void detach_from_transport();
+
+ FfiThreadSafeMessagePoster to_ffi_with_one_reference();
+
+private:
+ explicit ThreadSafeMessagePoster(Transport& transport)
+ : m_transport(&transport)
+ {
+ }
+
+ Mutex m_mutex;
+ Transport* m_transport { nullptr };
+};
+
+}
diff --git a/Meta/Generators/generate_ipc_definitions.py b/Meta/Generators/generate_ipc_definitions.py
index 4e634da22d9..e41858bad1a 100644
--- a/Meta/Generators/generate_ipc_definitions.py
+++ b/Meta/Generators/generate_ipc_definitions.py
@@ -89,6 +89,15 @@ class Message:
def response_name(self) -> str:
return f"{pascal_case(self.name)}Response"
+ def is_received_in_rust(self) -> bool:
+ return "RustReceiver" in self.attributes
+
+ def is_sent_from_rust(self) -> bool:
+ return "RustSender" in self.attributes
+
+ def has_cpp_class(self) -> bool:
+ return not (self.is_received_in_rust() and self.is_sent_from_rust())
+
@dataclass
class Endpoint:
@@ -112,9 +121,23 @@ class Endpoint:
return False
return self.binds(message)
+ def has_messages_received_in_rust(self) -> bool:
+ return any(message.is_received_in_rust() for message in self.messages)
+
+ def names_rust_for_some_message(self) -> bool:
+ return any(message.is_received_in_rust() or message.is_sent_from_rust() for message in self.messages)
+
def validate(self) -> None:
+ for message in self.messages:
+ if message.is_sent_from_rust() and message.is_synchronous:
+ raise RuntimeError(
+ f"{self.name}::{message.name} is synchronous, and Rust cannot wait for a response yet: "
+ f"it cannot be [RustSender]"
+ )
if self.route is None:
return
+ if self.names_rust_for_some_message():
+ raise RuntimeError(f"{self.name} is routed, so its messages cannot be [RustReceiver] or [RustSender]")
for message in self.messages:
if not self.routes(message):
continue
@@ -853,8 +876,9 @@ def write_proxy_method(
def write_proxy_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> None:
name = f"{endpoint.name}Proxy"
- connection_parameter = "IPC::ConnectionBase& connection" if endpoint.messages else "IPC::ConnectionBase&"
- initializer = " : m_connection(connection)\n" if endpoint.messages else ""
+ messages = [message for message in endpoint.messages if not message.is_sent_from_rust()]
+ connection_parameter = "IPC::ConnectionBase& connection" if messages else "IPC::ConnectionBase&"
+ initializer = " : m_connection(connection)\n" if messages else ""
out.write(f"""
{class_declaration(endpoint, name)} {{
public:
@@ -865,14 +889,14 @@ public:
{initializer} {{
}}
""")
- for message in endpoint.messages:
+ for message in messages:
write_proxy_method(out, implementation, endpoint, message, message.inputs, message.is_synchronous, is_try=False)
if message.is_synchronous:
write_proxy_method(
out, implementation, endpoint, message, message.inputs, is_synchronous=False, is_try=False
)
write_proxy_method(out, implementation, endpoint, message, message.inputs, is_synchronous=True, is_try=True)
- if endpoint.messages:
+ if messages:
out.write("\nprivate:\n IPC::ConnectionBase& m_connection;\n")
out.write("};\n")
@@ -901,8 +925,8 @@ public:
switch (message_id) {""")
for message in endpoint.messages:
- names = [message.name]
- if message.is_synchronous:
+ names = [] if message.is_received_in_rust() else [message.name]
+ if message.is_synchronous and message.has_cpp_class():
names.append(message.response_name())
for name in names:
@@ -925,6 +949,30 @@ public:
"static ErrorOr<NonnullOwnPtr<IPC::Message>> decode_message(ReadonlyBytes buffer, [[maybe_unused]] Queue<IPC::Attachment>& attachments)",
body.getvalue(),
)
+ body = io.StringIO()
+ if endpoint.has_messages_received_in_rust():
+ body.write("\n switch (message_id) {")
+ for message in endpoint.messages:
+ if not message.is_received_in_rust():
+ continue
+ pascal_name = pascal_case(message.name)
+ body.write(f"""
+ case (int)Messages::{endpoint.name}::MessageID::{pascal_name}:
+ return "{endpoint.name}::{pascal_name}"sv;""")
+ body.write("""
+ default:
+ return {};
+ }
+""")
+ else:
+ body.write(" return {};\n")
+ write_method(
+ out,
+ implementation,
+ f"{endpoint.name}Endpoint",
+ "static Optional<StringView> name_of_request_that_arrives_raw([[maybe_unused]] i32 message_id)",
+ body.getvalue(),
+ )
out.write("};\n")
@@ -933,6 +981,8 @@ def write_stub_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) ->
# anything of it is decided by the types themselves.
argument_types: List[str] = []
for message in endpoint.messages:
+ if message.is_received_in_rust():
+ continue
for parameter in message.inputs:
if parameter.type not in argument_types:
argument_types.append(parameter.type)
@@ -941,6 +991,22 @@ def write_stub_class(out: TextIO, implementation: TextIO, endpoint: Endpoint) ->
if argument_types:
bases += f"\n , public IPC::SenderClaimReceivers<{', '.join(argument_types)}>"
+ # A claim is verified on the decoded arguments, which this stub never has for a message Rust receives.
+ types_received_in_rust: List[str] = []
+ for message in endpoint.messages:
+ if not message.is_received_in_rust():
+ continue
+ for parameter in message.inputs:
+ if parameter.type not in types_received_in_rust:
+ types_received_in_rust.append(parameter.type)
+ for type in types_received_in_rust:
+ out.write(
+ f"\nstatic_assert(__is_empty(IPC::SenderClaimReceiver<{type}>),"
+ f' "A message Rust receives cannot carry a claim by its sender: {type}");'
+ )
+ if types_received_in_rust:
+ out.write("\n")
+
out.write(f"""
{class_declaration(endpoint, f"{endpoint.name}Stub")} : {bases} {{
public:
@@ -958,7 +1024,9 @@ public:
pascal_name = pascal_case(message.name)
body.write(f"\n case (int)Messages::{endpoint.name}::MessageID::{pascal_name}:\n")
- if message.inputs:
+ if message.is_received_in_rust():
+ body.write(" return handle_raw(static_cast<IPC::RawMessage&>(*message));")
+ elif message.inputs:
body.write(f" return handle_{message.name}(*message);")
else:
body.write(f" return handle_{message.name}();")
@@ -977,6 +1045,8 @@ public:
)
for message in endpoint.messages:
+ if message.is_received_in_rust():
+ continue
pascal_name = pascal_case(message.name)
arg_parts: List[str] = []
@@ -1027,6 +1097,8 @@ public:
out.write("\n")
for message in endpoint.messages:
+ if message.is_received_in_rust():
+ continue
return_type = "void"
if message.is_synchronous and message.outputs:
@@ -1035,6 +1107,9 @@ public:
params = ", ".join(f"{p.type} {p.name}" for p in message.inputs)
out.write(f" virtual {return_type} {message.name}({params}) = 0;\n")
+ if endpoint.has_messages_received_in_rust():
+ out.write(" virtual ErrorOr<OwnPtr<IPC::MessageBuffer>> handle_raw(IPC::RawMessage&) = 0;\n")
+
out.write("};\n")
@@ -1198,6 +1273,8 @@ def write_endpoint(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> N
implementation.write(f"\nnamespace Messages::{endpoint.name} {{\n")
write_message_ids_enum(out, endpoint)
for message in endpoint.messages:
+ if not message.has_cpp_class():
+ continue
response_name = ""
if message.is_synchronous:
response_name = message.response_name()
@@ -1444,6 +1521,7 @@ def build(
#include <AK/Result.h>
#include <LibIPC/File.h>
#include <LibIPC/Message.h>
+#include <LibIPC/RawMessage.h>
#include <LibIPC/SenderClaim.h>
#include <LibIPC/Stub.h>
@@ -1672,6 +1750,57 @@ def write_rust_message_struct(out: TextIO, name: str, message_id: int, parameter
out.write(" }\n }\n")
+def write_rust_stub(out: TextIO, endpoint: Endpoint) -> None:
+ # The receiver of the messages that Rust decodes, as the C++ stub of the endpoint is of the others: one method
+ # for each message, which takes the message and answers with the response of a synchronous one.
+ received = [message for message in endpoint.messages if message.is_received_in_rust()]
+ if not received:
+ return
+
+ result = "::std::result::Result"
+ out.write("\n pub trait Stub {\n")
+ for message in received:
+ message_type = f"messages::{rust_field_name(pascal_case(message.name))}"
+ response_type = "()"
+ if message.is_synchronous:
+ response_type = f"messages::{rust_field_name(pascal_case(message.response_name()))}"
+ out.write(
+ f" fn {rust_field_name(message.name)}(&mut self, message: {message_type}) -> "
+ f"{result}<{response_type}, ::libipc_rust::wire::Misbehavior>;\n"
+ )
+ out.write(" }\n")
+
+ out.write(f"""
+ /// Decodes a message of this endpoint, allowing unused bytes and attachments as C++ does, hands it to the stub, and
+ /// answers with the encoded response of a synchronous message.
+ pub fn dispatch<S: Stub + ?Sized>(stub: &mut S, bytes: &[u8], attachments: ::std::vec::Vec<::libipc_rust::Attachment>) -> {result}<::std::option::Option<::libipc_rust::wire::EncodedMessage>, ::libipc_rust::wire::DispatchError> {{
+ let mut decoder = ::libipc_rust::wire::Decoder::new(bytes, attachments);
+ let (magic, id) = ::libipc_rust::wire::decode_message_header(&mut decoder)?;
+ if magic != ENDPOINT_MAGIC {{
+ return {result}::Err(::libipc_rust::wire::DecodeError::InvalidValue("endpoint magic").into());
+ }}
+ match id {{
+""")
+ for message in received:
+ message_type = f"messages::{rust_field_name(pascal_case(message.name))}"
+ method = rust_field_name(message.name)
+ out.write(f" <{message_type} as ::libipc_rust::wire::EndpointMessage>::MESSAGE_ID => {{\n")
+ if message.is_synchronous:
+ out.write(f" let response = stub.{method}(decoder.decode()?)?;\n")
+ out.write(
+ f" {result}::Ok(::std::option::Option::Some("
+ "::libipc_rust::wire::EndpointMessage::encode_message(response)?))\n"
+ )
+ else:
+ out.write(f" stub.{method}(decoder.decode()?)?;\n")
+ out.write(f" {result}::Ok(::std::option::Option::None)\n")
+ out.write(" }\n")
+ out.write(f""" _ => {result}::Err(::libipc_rust::wire::DecodeError::InvalidValue("message ID").into()),
+ }}
+ }}
+""")
+
+
def write_rust_endpoint(out: TextIO, endpoint: Endpoint) -> None:
out.write(f"""
#[allow(clippy::all, dead_code)]
@@ -1680,20 +1809,35 @@ pub mod {rust_field_name(snake_case(endpoint.name))} {{
""")
out.write("\n pub mod messages {\n")
+ only_messages_naming_rust = endpoint.names_rust_for_some_message()
message_output = io.StringIO()
variants: List[str] = []
message_id = 0
for message in endpoint.messages:
message_id += 1
- write_rust_message_struct(message_output, message.name, message_id, message.inputs)
- variants.append(rust_field_name(pascal_case(message.name)))
+ request_id = message_id
if message.is_synchronous:
message_id += 1
+ if only_messages_naming_rust and not (message.is_received_in_rust() or message.is_sent_from_rust()):
+ continue
+ write_rust_message_struct(message_output, message.name, request_id, message.inputs)
+ if not only_messages_naming_rust:
+ variants.append(rust_field_name(pascal_case(message.name)))
+ if message.is_synchronous:
write_rust_message_struct(message_output, message.response_name(), message_id, message.outputs)
- variants.append(rust_field_name(pascal_case(message.response_name())))
+ if not only_messages_naming_rust:
+ variants.append(rust_field_name(pascal_case(message.response_name())))
out.write(textwrap.indent(message_output.getvalue(), " "))
- out.write(" }\n\n pub enum Message {\n")
+ out.write(" }\n")
+ if only_messages_naming_rust:
+ write_rust_stub(out, endpoint)
+ out.write("}\n")
+ return
+ if not variants:
+ out.write("}\n")
+ return
+ out.write("\n pub enum Message {\n")
for variant in variants:
out.write(f" {variant}(messages::{variant}),\n")
out.write(" }\n")
diff --git a/Tests/LibIPC/TestConnection.cpp b/Tests/LibIPC/TestConnection.cpp
index 8b6992b2bd0..d0866fc4af5 100644
--- a/Tests/LibIPC/TestConnection.cpp
+++ b/Tests/LibIPC/TestConnection.cpp
@@ -110,8 +110,9 @@ public:
}
protected:
- OwnPtr<IPC::Message> try_parse_message(ReadonlyBytes bytes, Queue<IPC::Attachment>&) override
+ OwnPtr<IPC::Message> try_parse_message(IPC::ReceivedMessageBytes const& received_bytes, Queue<IPC::Attachment>&) override
{
+ auto bytes = received_bytes.bytes();
if (bytes.size() != sizeof(u32))
return nullptr;
return make<TestMessage>(static_cast<int>(AK::ByteReader::load32(bytes.data())));
diff --git a/Tests/Meta/test-ipc-generator.py b/Tests/Meta/test-ipc-generator.py
index a52a9479800..77ae5d5d861 100644
--- a/Tests/Meta/test-ipc-generator.py
+++ b/Tests/Meta/test-ipc-generator.py
@@ -34,6 +34,14 @@ def generate(contents: str) -> str:
class TestIPCGenerator(unittest.TestCase):
+ def test_messages_received_in_rust_carry_no_claim_by_their_sender(self) -> None:
+ header, _ = generate_files(
+ "endpoint Test { [RustReceiver] update(Web::PageId page_id, u32 value) =| other(u64 value) =| }"
+ )
+ self.assertIn("static_assert(__is_empty(IPC::SenderClaimReceiver<Web::PageId>),", header)
+ self.assertIn("static_assert(__is_empty(IPC::SenderClaimReceiver<u32>),", header)
+ self.assertNotIn("IPC::SenderClaimReceiver<u64>)", header)
+
def test_non_template_implementations_are_only_in_the_cpp_file(self) -> None:
header, implementation = generate_files(ENDPOINT)
self.assertIn('#include "TestEndpoint.h"', implementation)
@@ -611,6 +619,33 @@ class TestIPCRustGenerator(unittest.TestCase):
self.assertIn('InvalidValue("message ID")', generated)
self.assertNotIn("decoder.is_at_end()", generated)
+ def test_messages_received_in_rust_get_a_stub_and_a_dispatcher(self) -> None:
+ generated = self.generate(
+ "endpoint Test { [RustReceiver] update(u32 value) =| [RustReceiver] query() => (u32 value) other() =| }"
+ )
+ self.assertIn(
+ """\
+ pub trait Stub {
+ fn update(&mut self, message: messages::Update) -> ::std::result::Result<(), ::libipc_rust::wire::Misbehavior>;
+ fn query(&mut self, message: messages::Query) -> ::std::result::Result<messages::QueryResponse, ::libipc_rust::wire::Misbehavior>;
+ }
+""",
+ generated,
+ )
+ self.assertIn(
+ """\
+ <messages::Query as ::libipc_rust::wire::EndpointMessage>::MESSAGE_ID => {
+ let response = stub.query(decoder.decode()?)?;
+ ::std::result::Result::Ok(::std::option::Option::Some(::libipc_rust::wire::EndpointMessage::encode_message(response)?))
+ }
+""",
+ generated,
+ )
+ self.assertNotIn("pub enum Message", generated)
+ self.assertNotIn("Other", generated)
+
+ self.assertNotIn("Stub", self.generate("endpoint Test { [RustSender] update(u32 value) =| }"))
+
def test_owned_encoding_moves_every_field(self) -> None:
generated = self.generate("endpoint Test { send(Vector<IPC::File> files) =| }")
self.assertIn("fn encode_owned(self,", generated)