Truly independent web browser
Meta+LibIPC: Let Rust send synchronous messages through a C++ connection
Aliaksandr Kalenik9efa7e7e1d6a
diff --git a/Libraries/LibIPC/Connection.cpp b/Libraries/LibIPC/Connection.cppindex f958f14c44f..b2b5ac63a6d 100644--- a/Libraries/LibIPC/Connection.cpp+++ b/Libraries/LibIPC/Connection.cpp@@ -86,6 +86,12 @@ ErrorOr<void> ConnectionBase::post_message(MessageBuffer& buffer)}ErrorOr<void> ConnectionBase::post_sync_request(Message const& request)+{+ auto buffer = TRY(request.encode());+ return post_sync_request(buffer);+}++ErrorOr<void> ConnectionBase::post_sync_request(MessageBuffer& request){auto result = post_message(request);// NB: No response can come if the peer has closed the connection. If that peer owns this process, then shut down@@ -96,6 +102,58 @@ ErrorOr<void> ConnectionBase::post_sync_request(Message const& request)return result;}+bool ConnectionBase::send_raw_sync_request(MessageBuffer& request, u32 response_endpoint_magic, i32 response_message_id, Function<void(FfiRawMessage)> const& hand_over_response)+{+ if (post_sync_request(request).is_error())+ return false;+ auto response = wait_for_specific_endpoint_message_impl(response_endpoint_magic, response_message_id, MayCancel::Yes);+ if (!response)+ return false;+ auto outcome = static_cast<RawMessage&>(*response).hand_to_rust(hand_over_response);+ if (outcome.misbehavior.has_value()) {+ dbgln("IPC::ConnectionBase ({:p}) got a response it cannot use ({}), disconnecting.", this, *outcome.misbehavior);+ shutdown();+ return false;+ }+ return true;+}++bool ConnectionBase::send_sync_request_from_rust(void* connection, ReadonlyBytes bytes, ReadonlySpan<RawAttachment> attachments, u32 response_endpoint_magic, i32 response_message_id, void* response_sink, void (*take_response)(void* response_sink, FfiRawMessage))+{+ auto& self = *static_cast<ConnectionBase*>(connection);+ VERIFY(self.m_owner_thread_id.is_current_thread());+ auto request = adopt_encoded_message(bytes, attachments);+ return self.send_raw_sync_request(request, response_endpoint_magic, response_message_id, [&](FfiRawMessage response) {+ take_response(response_sink, response);+ });+}++void ConnectionBase::ref_from_rust(void* connection)+{+ auto& self = *static_cast<ConnectionBase*>(connection);+ VERIFY(self.m_owner_thread_id.is_current_thread());+ self.ref();+}++void ConnectionBase::unref_from_rust(void* connection)+{+ auto& self = *static_cast<ConnectionBase*>(connection);+ VERIFY(self.m_owner_thread_id.is_current_thread());+ self.unref();+}++FfiConnection ConnectionBase::to_ffi_with_one_reference()+{+ VERIFY(m_owner_thread_id.is_current_thread());+ ref();+ return {+ .connection_with_one_reference = this,+ .send_sync_request = send_sync_request_from_rust,+ .ref = ref_from_rust,+ .unref = unref_from_rust,+ };+}+void ConnectionBase::shutdown(){VERIFY(m_owner_thread_id.is_current_thread());diff --git a/Libraries/LibIPC/Connection.h b/Libraries/LibIPC/Connection.hindex 3b3981ba68a..371ec222d30 100644--- a/Libraries/LibIPC/Connection.h+++ b/Libraries/LibIPC/Connection.h@@ -53,6 +53,14 @@ private:Transport* m_transport_waited_on { nullptr };};+struct FfiConnection {+ void* connection_with_one_reference;+ bool (*send_sync_request)(void* connection, ReadonlyBytes, ReadonlySpan<RawAttachment>, u32 response_endpoint_magic, i32 response_message_id, void* response_sink, void (*take_response)(void* response_sink, FfiRawMessage));+ void (*ref)(void* connection);+ void (*unref)(void* connection);+};+static_assert(sizeof(FfiConnection) == 4 * sizeof(void*), "FfiConnection of libipc_rust is written to match this by hand");+class ConnectionBase : public Core::EventReceiver {C_OBJECT_ABSTRACT(ConnectionBase);@@ -93,6 +101,8 @@ public:// Dispatch every message the peer has already sent on this connection, without waiting for new ones.void dispatch_pending_messages();+ FfiConnection to_ffi_with_one_reference();+template<typename RequestType, typename... Args>NonnullOwnPtr<typename RequestType::ResponseType> send_sync(Args&&... args){@@ -156,6 +166,7 @@ protected:virtual OwnPtr<Message> try_parse_message(ReceivedMessageBytes const&, Queue<Attachment>&) = 0;ErrorOr<void> post_sync_request(Message const&);+ ErrorOr<void> post_sync_request(MessageBuffer&);OwnPtr<IPC::Message> wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id, MayCancel = MayCancel::No, Optional<MonotonicTime> deadline = {});void wait_for_transport_to_become_readable(Optional<MonotonicTime> deadline = {});enum class PeerEOF {@@ -166,6 +177,11 @@ protected:void handle_messages();+ bool send_raw_sync_request(MessageBuffer&, u32 response_endpoint_magic, i32 response_message_id, Function<void(FfiRawMessage)> const& hand_over_response);+ static bool send_sync_request_from_rust(void* connection, ReadonlyBytes, ReadonlySpan<RawAttachment>, u32 response_endpoint_magic, i32 response_message_id, void* response_sink, void (*take_response)(void* response_sink, FfiRawMessage));+ static void ref_from_rust(void* connection);+ static void unref_from_rust(void* connection);+AK::ThreadID m_owner_thread_id { AK::ThreadID::current() };IPC::Stub& m_local_stub;@@ -194,8 +210,13 @@ protected: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()) {+ if (auto header = RawMessage::read_header(bytes); header.has_value()) {+ Optional<StringView> message_name;+ if (header->endpoint_magic == LocalEndpoint::static_magic())+ message_name = LocalEndpoint::name_of_request_that_arrives_raw(header->message_id);+ else if (header->endpoint_magic == PeerEndpoint::static_magic())+ message_name = PeerEndpoint::name_of_response_that_arrives_raw(header->message_id);+ if (message_name.has_value()) {Vector<Attachment> attachments_of_message;while (!attachments.is_empty())attachments_of_message.append(attachments.dequeue());diff --git a/Libraries/LibIPC/Rust/src/cpp_connection.rs b/Libraries/LibIPC/Rust/src/cpp_connection.rsindex 7ed7a793a77..11f7d304db8 100644--- a/Libraries/LibIPC/Rust/src/cpp_connection.rs+++ b/Libraries/LibIPC/Rust/src/cpp_connection.rs@@ -10,10 +10,12 @@#![allow(unsafe_code)]use core::ffi::{c_int, c_void};+use core::marker::PhantomData;use crate::attachment::Attachment;use crate::wire::{Decode, DecodeError, Decoder, DispatchError, EncodeError, EncodedMessage, EndpointMessage, Misbehavior,+ SyncMessage, decode_message_header,};/// A Mach port name and its disposition on Apple, and a descriptor elsewhere: `IPC::RawAttachment`.@@ -170,12 +172,111 @@ pub struct FfiThreadSafeMessagePoster {unref: unsafe extern "C" fn(*mut c_void),}+/// One reference to an `IPC::ConnectionBase`, and how to make synchronous requests on it: `IPC::FfiConnection`.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiConnection {+ connection_with_one_reference: *mut c_void,+ send_sync_request: unsafe extern "C" fn(+ *mut c_void,+ ak::Span<'_, u8>,+ ak::Span<'_, RawAttachment>,+ u32,+ i32,+ *mut c_void,+ unsafe extern "C" fn(*mut c_void, RawMessage<'_>),+ ) -> 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>());+ assert!(size_of::<FfiConnection>() == 4 * size_of::<usize>());};+/// Makes synchronous requests on a C++ connection, on the thread that owns it.+pub struct CppConnection {+ ffi: FfiConnection,+ _used_on_the_thread_that_owns_the_connection: PhantomData<*const ()>,+}++impl CppConnection {+ /// # Safety+ ///+ /// `ffi` must hold one reference to a live `IPC::ConnectionBase` of this thread, which the caller gives up.+ pub unsafe fn adopt(ffi: FfiConnection) -> Self {+ Self {+ ffi,+ _used_on_the_thread_that_owns_the_connection: PhantomData,+ }+ }++ /// Waits for the response without handling any other message meanwhile. None if the request does not encode, or if+ /// the peer could not be reached or answered with what does not decode, after which C++ has shut the connection+ /// down.+ pub fn send_sync<M: SyncMessage>(&self, request: M) -> Option<M::Response> {+ unsafe extern "C" fn take_response<R: EndpointMessage + Decode>(+ response_sink: *mut c_void,+ response: RawMessage<'_>,+ ) {+ // SAFETY: send_sync() passes its sink of the response type, and C++ hands the response over once.+ unsafe {+ let response_sink = &mut *response_sink.cast::<Option<R>>();+ response.hand_to(|bytes, attachments| {+ let mut decoder = Decoder::new(bytes, attachments);+ let (magic, id) = decode_message_header(&mut decoder)?;+ if magic != R::ENDPOINT_MAGIC || id != R::MESSAGE_ID {+ return Err(DecodeError::InvalidValue("response header").into());+ }+ *response_sink = Some(decoder.decode()?);+ Ok(None)+ });+ }+ }++ let Ok((bytes, attachments)) = request.encode_message() else {+ return None;+ };+ let raw_attachments: Vec<RawAttachment> = attachments.into_iter().map(RawAttachment::from_attachment).collect();+ let mut response: Option<M::Response> = None;+ // SAFETY: This holds a reference to the connection, which copies the bytes and takes every attachment over, and+ // hands the response to take_response() before the call returns.+ let answered = unsafe {+ (self.ffi.send_sync_request)(+ self.ffi.connection_with_one_reference,+ ak::Span::new(&bytes),+ ak::Span::new(&raw_attachments),+ <M::Response as EndpointMessage>::ENDPOINT_MAGIC,+ <M::Response as EndpointMessage>::MESSAGE_ID,+ (&raw mut response).cast(),+ take_response::<M::Response>,+ )+ };+ if answered { response } else { None }+ }+}++impl Clone for CppConnection {+ fn clone(&self) -> Self {+ // SAFETY: This holds a reference to the connection.+ unsafe { (self.ffi.r#ref)(self.ffi.connection_with_one_reference) };+ Self {+ ffi: self.ffi,+ _used_on_the_thread_that_owns_the_connection: PhantomData,+ }+ }+}++impl Drop for CppConnection {+ fn drop(&mut self) {+ // SAFETY: This gives up the reference it holds.+ unsafe { (self.ffi.unref)(self.ffi.connection_with_one_reference) };+ }+}+/// Posts messages to the transport of a C++ connection from any thread.pub struct ThreadSafeMessagePoster(FfiThreadSafeMessagePoster);diff --git a/Libraries/LibIPC/Rust/src/wire.rs b/Libraries/LibIPC/Rust/src/wire.rsindex 9b8e4200ae6..083b9f33604 100644--- a/Libraries/LibIPC/Rust/src/wire.rs+++ b/Libraries/LibIPC/Rust/src/wire.rs@@ -690,6 +690,11 @@ pub trait EndpointMessage: Encode {}}+/// A synchronous message, and the message that answers it.+pub trait SyncMessage: EndpointMessage {+ type Response: EndpointMessage + Decode;+}+/// Reads the endpoint magic number and message ID that a message starts with.pub fn decode_message_header(decoder: &mut Decoder<'_>) -> Result<(u32, i32), DecodeError> {Ok((decoder.decode()?, decoder.decode()?))diff --git a/Meta/Generators/generate_ipc_definitions.py b/Meta/Generators/generate_ipc_definitions.pyindex e34d8c1eed3..7d6f88df3ba 100644--- a/Meta/Generators/generate_ipc_definitions.py+++ b/Meta/Generators/generate_ipc_definitions.py@@ -130,12 +130,6 @@ class Endpoint: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:returnif self.names_rust_for_some_message():@@ -975,7 +969,7 @@ public:for message in endpoint.messages:names = [] if message.is_received_in_rust() else [message.name]- if message.is_synchronous and message.has_cpp_class():+ if message.is_synchronous and message.has_cpp_class() and not message.is_sent_from_rust():names.append(message.response_name())for name in names:@@ -1022,6 +1016,31 @@ public:"static Optional<StringView> name_of_request_that_arrives_raw([[maybe_unused]] i32 message_id)",body.getvalue(),)+ body = io.StringIO()+ responses_sent_to_rust = [+ message for message in endpoint.messages if message.is_synchronous and message.is_sent_from_rust()+ ]+ if responses_sent_to_rust:+ body.write("\n switch (message_id) {")+ for message in responses_sent_to_rust:+ pascal_name = pascal_case(message.response_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_response_that_arrives_raw([[maybe_unused]] i32 message_id)",+ body.getvalue(),+ )out.write("};\n")@@ -1899,6 +1918,14 @@ pub mod {rust_field_name(snake_case(endpoint.name))} {{write_rust_message_struct(message_output, message.response_name(), message_id, message.outputs)if not only_messages_naming_rust:variants.append(rust_field_name(pascal_case(message.response_name())))+ if message.is_sent_from_rust():+ request_type = rust_field_name(pascal_case(message.name))+ response_type = rust_field_name(pascal_case(message.response_name()))+ message_output.write(f"""+ impl ::libipc_rust::wire::SyncMessage for {request_type} {{+ type Response = {response_type};+ }}+""")out.write(textwrap.indent(message_output.getvalue(), " "))out.write(" }\n")diff --git a/Tests/Meta/test-ipc-generator.py b/Tests/Meta/test-ipc-generator.pyindex 3ab04178ae2..fec07166813 100644--- a/Tests/Meta/test-ipc-generator.py+++ b/Tests/Meta/test-ipc-generator.py@@ -42,6 +42,21 @@ class TestIPCGenerator(unittest.TestCase):self.assertIn("static_assert(__is_empty(IPC::SenderClaimReceiver<u32>),", header)self.assertNotIn("IPC::SenderClaimReceiver<u64>)", header)+ def test_responses_to_synchronous_messages_sent_from_rust_arrive_raw(self) -> None:+ generated = generate("endpoint Test { [RustSender] query(u32 value) => (u32 answer) other() => (u32 answer) }")+ decoder = generated.split("decode_message(")[2].split("name_of_request_that_arrives_raw")[0]+ self.assertNotIn("MessageID::QueryResponse:", decoder)+ self.assertIn("MessageID::OtherResponse:", decoder)+ raw_responses = generated.split("name_of_response_that_arrives_raw(")[2]+ self.assertIn(+ """\+ case (int)Messages::Test::MessageID::QueryResponse:+ return "Test::QueryResponse"sv;""",+ raw_responses,+ )+ self.assertNotIn("OtherResponse", raw_responses.split("default:")[0])+ self.assertIn("class QueryResponse final : public IPC::Message", generated)+def test_non_template_implementations_are_only_in_the_cpp_file(self) -> None:header, implementation = generate_files(ENDPOINT)self.assertIn('#include "TestEndpoint.h"', implementation)@@ -696,6 +711,18 @@ class TestIPCRustGenerator(unittest.TestCase):self.assertNotIn("Stub", self.generate("endpoint Test { [RustSender] update(u32 value) =| }"))+ def test_synchronous_messages_sent_from_rust_name_their_response(self) -> None:+ generated = self.generate("endpoint Test { [RustSender] query(u32 value) => (u32 answer) other() =| }")+ self.assertIn(+ """\+ impl ::libipc_rust::wire::SyncMessage for Query {+ type Response = QueryResponse;+ }+""",+ generated,+ )+ self.assertEqual(generated.count("SyncMessage"), 1)+def test_utf8_is_validated_on_requests_and_responses(self) -> None:for cpp_type, expression in [("ByteString", "&self.text.0"),