Skip to content

Truly independent web browser

Tests/LibIPC: Exchange messages with a generated Rust endpoint

Andreas Kling04d1f1b96760
diff --git a/Cargo.lock b/Cargo.lock
index 04ff171aafe..951a52bb05f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1270,6 +1270,15 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+[[package]]
+name = "rust_echo_server"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "libipc_rust",
+ "rustc-demangle",
+]
+
[[package]]
name = "rustc-demangle"
version = "0.1.28"
diff --git a/Cargo.toml b/Cargo.toml
index 3560d94edfc..87a020aca0b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,6 +20,7 @@ members = [
"Libraries/LibWeb/Rust",
"Libraries/LibWeb/HTML/Parser/Rust",
"Libraries/RustAllocator",
+ "Tests/LibIPC/RustEchoServer",
]
exclude = [
"Libraries/LibJS/Flap",
diff --git a/Meta/CMake/rust_crate.cmake b/Meta/CMake/rust_crate.cmake
index bac43d64dc7..ecf66156dc7 100644
--- a/Meta/CMake/rust_crate.cmake
+++ b/Meta/CMake/rust_crate.cmake
@@ -307,12 +307,13 @@ function(build_rust_binary)
endfunction()
function(test_rust_crate)
- cmake_parse_arguments(PARSE_ARGV 0 ARG "" "MANIFEST_PATH;CRATE_NAME" "")
+ cmake_parse_arguments(PARSE_ARGV 0 ARG "" "MANIFEST_PATH;CRATE_NAME" "ENVIRONMENT")
_rust_crate_common_setup(
MANIFEST_PATH "${ARG_MANIFEST_PATH}"
CRATE_NAME ${ARG_CRATE_NAME}
TARGET_DIR "${CMAKE_BINARY_DIR}/cargo/tests/${ARG_CRATE_NAME}"
)
+ list(APPEND cargo_env ${ARG_ENVIRONMENT})
# cargo test accepts harness arguments after --, not rustc arguments.
list(FIND cargo_common_flags "--" rustc_flags_start)
list(SUBLIST cargo_common_flags 0 ${rustc_flags_start} cargo_test_flags)
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index f647e6fc2d3..ca977850171 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -35,6 +35,7 @@ if (NOT WIN32)
"${CMAKE_COMMAND}" -E env
${rust_test_env}
"CARGO_TARGET_DIR=${CMAKE_BINARY_DIR}/cargo/build"
+ "RUST_ECHO_SERVER_ENDPOINT=${CMAKE_CURRENT_BINARY_DIR}/LibIPC/RustEchoServerEndpoint.rs"
"${RUST_CARGO}" test --workspace
--manifest-path "${LADYBIRD_SOURCE_DIR}/Cargo.toml"
--target "${RUST_TARGET_TRIPLE}"
@@ -78,6 +79,7 @@ if (NOT WIN32)
COMMAND_EXPAND_LISTS
)
add_custom_target(rust-tests ALL DEPENDS "${rust_tests_stamp}")
+ add_dependencies(rust-tests generate_RustEchoServerEndpoint.h)
add_test(NAME RustWorkspace COMMAND ${rust_workspace_test_command})
add_test(NAME Flap COMMAND ${flap_test_command})
diff --git a/Tests/LibIPC/CMakeLists.txt b/Tests/LibIPC/CMakeLists.txt
index f2dea4071ba..15595ab3545 100644
--- a/Tests/LibIPC/CMakeLists.txt
+++ b/Tests/LibIPC/CMakeLists.txt
@@ -7,6 +7,18 @@ if (APPLE)
ladybird_test("TestMachBootstrap.cpp" LibIPC LIBS LibIPC LibCore)
endif()
endif()
+if (NOT WIN32)
+ compile_ipc(RustEchoServer.ipc RustEchoServerEndpoint.h RUST_OUTPUT RustEchoServerEndpoint.rs)
+ set(rust_echo_environment "RUST_ECHO_SERVER_ENDPOINT=${CMAKE_CURRENT_BINARY_DIR}/RustEchoServerEndpoint.rs")
+ import_rust_crate(MANIFEST_PATH RustEchoServer/Cargo.toml CRATE_NAME rust_echo_server ENVIRONMENT ${rust_echo_environment})
+ add_dependencies(rust_echo_server-build generate_RustEchoServerEndpoint.h)
+ test_rust_crate(MANIFEST_PATH RustEchoServer/Cargo.toml CRATE_NAME rust_echo_server ENVIRONMENT ${rust_echo_environment})
+ add_dependencies(rust_echo_server-test generate_RustEchoServerEndpoint.h)
+ ladybird_test("TestRustEchoServer.cpp" LibIPC LIBS LibIPC LibCore rust_echo_server)
+ target_sources(TestRustEchoServer PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/RustEchoServerEndpoint.cpp")
+ target_include_directories(TestRustEchoServer PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+ add_dependencies(TestRustEchoServer generate_RustEchoServerEndpoint.h)
+endif()
ladybird_test("TestConnection.cpp" LibIPC LIBS LibIPC LibThreading)
ladybird_test("TestDecoder.cpp" LibIPC LIBS LibIPC)
diff --git a/Tests/LibIPC/RustEchoServer.ipc b/Tests/LibIPC/RustEchoServer.ipc
new file mode 100644
index 00000000000..9ecc6663b0e
--- /dev/null
+++ b/Tests/LibIPC/RustEchoServer.ipc
@@ -0,0 +1,14 @@
+// Copyright (c) 2026-present, the Ladybird developers.
+
+#include <AK/ByteString.h>
+#include <AK/Utf16String.h>
+#include <LibIPC/File.h>
+
+endpoint RustEchoServer
+{
+ echo(u32 number, String text, Utf16String utf16_text, Vector<Optional<i64>> values, ByteBuffer bytes) => (u32 number, String text, Utf16String utf16_text, Vector<Optional<i64>> values, ByteBuffer bytes)
+ write_to_file(IPC::File file, ByteString contents) => ()
+ echo_files(Vector<IPC::File> files) => (Vector<IPC::File> files)
+ stop() =|
+ echo_utf8([UTF8] ByteString text, [UTF8] ByteBuffer bytes) => ([UTF8] ByteString text, [UTF8] ByteBuffer bytes)
+}
diff --git a/Tests/LibIPC/RustEchoServer/Cargo.toml b/Tests/LibIPC/RustEchoServer/Cargo.toml
new file mode 100644
index 00000000000..78999efd140
--- /dev/null
+++ b/Tests/LibIPC/RustEchoServer/Cargo.toml
@@ -0,0 +1,19 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+[package]
+name = "rust_echo_server"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["staticlib"]
+
+[dependencies]
+ak = { path = "../../../AK/Rust" }
+rustc-demangle = "0.1"
+libipc_rust = { path = "../../../Libraries/LibIPC/Rust" }
+
+[lints]
+workspace = true
diff --git a/Tests/LibIPC/RustEchoServer/build.rs b/Tests/LibIPC/RustEchoServer/build.rs
new file mode 100644
index 00000000000..660978c3259
--- /dev/null
+++ b/Tests/LibIPC/RustEchoServer/build.rs
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::env;
+use std::error::Error;
+use std::path::PathBuf;
+use std::process::Command;
+
+fn main() -> Result<(), Box<dyn Error>> {
+ println!("cargo:rerun-if-env-changed=RUST_ECHO_SERVER_ENDPOINT");
+ let endpoint = if let Some(path) = env::var_os("RUST_ECHO_SERVER_ENDPOINT") {
+ let path = PathBuf::from(path);
+ println!("cargo:rerun-if-changed={}", path.display());
+ path
+ } else {
+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
+ let definition = manifest_dir.join("../RustEchoServer.ipc");
+ let generator = manifest_dir.join("../../../Meta/Generators/generate_ipc_definitions.py");
+ println!("cargo:rerun-if-changed={}", definition.display());
+ println!("cargo:rerun-if-changed={}", generator.display());
+ // NB: The generator imports these from Meta/Utils.
+ for module in ["lexer.py", "utils.py"] {
+ println!(
+ "cargo:rerun-if-changed={}",
+ manifest_dir.join("../../../Meta/Utils").join(module).display()
+ );
+ }
+ let output = PathBuf::from(env::var("OUT_DIR")?).join("RustEchoServerEndpoint.rs");
+ let status = Command::new("python3")
+ .arg(generator)
+ .arg("--input")
+ .arg(definition)
+ .arg("--rust-output")
+ .arg(&output)
+ .status()?;
+ if !status.success() {
+ return Err("IPC endpoint generation failed".into());
+ }
+ output
+ };
+ println!("cargo:rustc-env=RUST_ECHO_SERVER_ENDPOINT={}", endpoint.display());
+ Ok(())
+}
diff --git a/Tests/LibIPC/RustEchoServer/src/lib.rs b/Tests/LibIPC/RustEchoServer/src/lib.rs
new file mode 100644
index 00000000000..9ab02e6fa42
--- /dev/null
+++ b/Tests/LibIPC/RustEchoServer/src/lib.rs
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A Rust endpoint that TestRustEchoServer speaks with over the platform's transport, using code that the IPC compiler
+//! generated for both languages from RustEchoServer.ipc.
+
+#[path = "../../../../Libraries/RustDemangle.rs"]
+mod rust_demangle;
+
+#[path = "../../../../Libraries/RustPanic.rs"]
+mod rust_panic;
+
+use std::io::Write;
+
+use libipc_rust::EndpointMessage;
+#[cfg(not(target_vendor = "apple"))]
+use libipc_rust::transport_socket::TransportSocket as Transport;
+#[cfg(target_vendor = "apple")]
+use libipc_rust::{
+ mach::{MachPort, PortRight},
+ transport::TransportMachPort as Transport,
+};
+
+include!(env!("RUST_ECHO_SERVER_ENDPOINT"));
+
+use rust_echo_server::{
+ Message,
+ messages::{EchoFilesResponse, EchoResponse, EchoUtf8Response, WriteToFileResponse},
+};
+
+#[cfg(test)]
+mod tests;
+
+fn reply(transport: &Transport, message: impl EndpointMessage) -> std::io::Result<()> {
+ let (bytes, attachments) = message.encode_message().expect("the reply encodes");
+ transport.post_message(bytes, attachments)
+}
+
+fn serve(transport: Transport) {
+ while let Some(received) = transport.receive() {
+ let (bytes, attachments) = received.into_parts();
+ let message = match Message::decode(bytes.as_ref(), attachments) {
+ Ok(message) => message,
+ Err(error) => {
+ eprintln!("RustEchoServer: Refusing a message: {error:?}");
+ break;
+ }
+ };
+ let replied = match message {
+ Message::Echo(echo) => reply(
+ &transport,
+ EchoResponse {
+ number: echo.number,
+ text: echo.text,
+ utf16_text: echo.utf16_text,
+ values: echo.values,
+ bytes: echo.bytes,
+ },
+ ),
+ Message::WriteToFile(request) => {
+ let mut file = std::fs::File::from(request.file.0);
+ file.write_all(&request.contents.0).expect("the file is writable");
+ reply(&transport, WriteToFileResponse)
+ }
+ Message::EchoFiles(request) => reply(&transport, EchoFilesResponse { files: request.files }),
+ Message::EchoUtf8(request) => reply(
+ &transport,
+ EchoUtf8Response {
+ text: request.text,
+ bytes: request.bytes,
+ },
+ ),
+ Message::Stop(_) => break,
+ Message::EchoResponse(_)
+ | Message::WriteToFileResponse(_)
+ | Message::EchoFilesResponse(_)
+ | Message::EchoUtf8Response(_) => {
+ eprintln!("RustEchoServer: Refusing a response sent to it");
+ break;
+ }
+ };
+ if let Err(error) = replied {
+ eprintln!("RustEchoServer: Could not reply: {error}");
+ break;
+ }
+ }
+ transport.flush();
+}
+
+/// Serves the endpoint on a thread of its own, taking over a receive right and a send right that this task holds.
+#[cfg(target_vendor = "apple")]
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_echo_server_serve(receive_right: u32, send_right: u32) {
+ let receive_right = MachPort::adopt(receive_right, PortRight::Receive);
+ let send_right = MachPort::adopt(send_right, PortRight::Send);
+ let transport = Transport::new(receive_right, send_right).expect("the transport starts");
+ std::thread::spawn(move || serve(transport));
+}
+
+/// Serves the endpoint on a thread of its own, taking over a connected Unix domain socket.
+#[cfg(not(target_vendor = "apple"))]
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_echo_server_serve(socket_fd: std::os::fd::RawFd) {
+ use std::os::fd::FromRawFd;
+ // NB: The caller gives up its descriptor of a connected socket, which nothing else owns.
+ let socket = unsafe { std::os::unix::net::UnixStream::from_raw_fd(socket_fd) };
+ let transport = Transport::new(socket).expect("the transport starts");
+ std::thread::spawn(move || serve(transport));
+}
diff --git a/Tests/LibIPC/RustEchoServer/src/tests.rs b/Tests/LibIPC/RustEchoServer/src/tests.rs
new file mode 100644
index 00000000000..dec2dff261a
--- /dev/null
+++ b/Tests/LibIPC/RustEchoServer/src/tests.rs
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+use libipc_rust::DecodeError;
+use rust_echo_server::messages::Stop;
+
+#[test]
+fn generated_messages_check_the_endpoint_and_message_number() {
+ let (bytes, _) = Stop.encode_message().unwrap();
+ assert!(matches!(Message::decode(&bytes, vec![]), Ok(Message::Stop(_))));
+ for range in [0..4, 4..8] {
+ let mut invalid = bytes.clone();
+ invalid[range].fill(0);
+ assert!(matches!(
+ Message::decode(&invalid, vec![]),
+ Err(DecodeError::InvalidValue(_))
+ ));
+ }
+}
+
+#[test]
+fn generated_messages_refuse_truncated_bytes_and_accept_trailing_bytes_like_cpp() {
+ let (mut bytes, _) = Stop.encode_message().unwrap();
+ for length in 0..bytes.len() {
+ assert!(Message::decode(&bytes[..length], vec![]).is_err());
+ }
+ bytes.push(0);
+ assert!(matches!(Message::decode(&bytes, vec![]), Ok(Message::Stop(_))));
+}
+
+#[test]
+fn generated_messages_accept_unused_attachments_like_cpp() {
+ let (bytes, _) = Stop.encode_message().unwrap();
+ let (mut reader, writer) = std::io::pipe().unwrap();
+ let attachment = libipc_rust::Attachment::from_fd(writer.into()).unwrap();
+ assert!(matches!(
+ Message::decode(&bytes, vec![attachment]),
+ Ok(Message::Stop(_))
+ ));
+ assert_eq!(std::io::Read::read(&mut reader, &mut [0]).unwrap(), 0);
+}
+
+#[test]
+fn generated_utf8_validation_matches_cpp() {
+ use libipc_rust::wire::ByteString;
+ use libipc_rust::{Encode, EncodeError, Encoder};
+ use rust_echo_server::messages::{EchoUtf8, EchoUtf8Response};
+
+ for bytes in [
+ b"".as_slice(),
+ "héllo".as_bytes(),
+ &[0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf],
+ ] {
+ let (encoded, attachments) = EchoUtf8 {
+ text: ByteString(bytes.to_vec()),
+ bytes: bytes.to_vec(),
+ }
+ .encode_message()
+ .unwrap();
+ let Message::EchoUtf8(decoded) = Message::decode(&encoded, attachments).unwrap() else {
+ panic!("expected EchoUtf8");
+ };
+ assert_eq!(decoded.text.0, bytes);
+ assert_eq!(decoded.bytes, bytes);
+ let (encoded, attachments) = EchoUtf8Response {
+ text: decoded.text,
+ bytes: decoded.bytes,
+ }
+ .encode_message()
+ .unwrap();
+ let Message::EchoUtf8Response(decoded) = Message::decode(&encoded, attachments).unwrap() else {
+ panic!("expected EchoUtf8Response");
+ };
+ assert_eq!(decoded.text.0, bytes);
+ assert_eq!(decoded.bytes, bytes);
+ }
+ for bytes in [
+ b"\xff".as_slice(),
+ b"\xc0\x80",
+ b"\xe2\x82",
+ b"\xed\xa0\x80\xff",
+ b"\xf4\x90\x80\x80",
+ ] {
+ for (text, bytes) in [(bytes.to_vec(), vec![]), (vec![], bytes.to_vec())] {
+ for response in [false, true] {
+ let mut encoded = Encoder::new();
+ encoded.encode(&rust_echo_server::ENDPOINT_MAGIC).unwrap();
+ let id = if response {
+ EchoUtf8Response::MESSAGE_ID
+ } else {
+ EchoUtf8::MESSAGE_ID
+ };
+ encoded.encode(&id).unwrap();
+ encoded.encode(&ByteString(text.clone())).unwrap();
+ encoded.encode(&bytes).unwrap();
+ assert!(matches!(
+ Message::decode(&encoded.finish().0, vec![]),
+ Err(DecodeError::InvalidUtf8)
+ ));
+ let mut encoder = Encoder::new();
+ let (borrowed, owned) = if response {
+ let message = EchoUtf8Response {
+ text: ByteString(text.clone()),
+ bytes: bytes.clone(),
+ };
+ (message.encode(&mut encoder), message.encode_message())
+ } else {
+ let message = EchoUtf8 {
+ text: ByteString(text.clone()),
+ bytes: bytes.clone(),
+ };
+ (message.encode(&mut encoder), message.encode_message())
+ };
+ assert!(matches!(borrowed, Err(EncodeError::InvalidValue("UTF-8"))));
+ assert!(matches!(owned, Err(EncodeError::InvalidValue("UTF-8"))));
+ }
+ }
+ }
+}
+
+#[test]
+fn generated_owned_messages_move_files() {
+ use libipc_rust::wire::File;
+ use std::os::fd::AsRawFd;
+
+ let (_reader, writer) = std::io::pipe().unwrap();
+ let descriptor = writer.as_raw_fd();
+ let files = vec![File(writer.into())];
+ let (bytes, attachments) = EchoFilesResponse { files }.encode_message().unwrap();
+ let Message::EchoFilesResponse(decoded) = Message::decode(&bytes, attachments).unwrap() else {
+ panic!("expected EchoFilesResponse");
+ };
+ assert_eq!(decoded.files.len(), 1);
+ #[cfg(not(target_vendor = "apple"))]
+ assert_eq!(decoded.files[0].0.as_raw_fd(), descriptor);
+ #[cfg(target_vendor = "apple")]
+ let _ = descriptor;
+}
+
+#[test]
+fn server_flushes_posted_replies_before_returning_on_errors() {
+ use libipc_rust::wire::ByteString;
+ use rust_echo_server::messages::{EchoUtf8, EchoUtf8Response};
+
+ for invalid in [
+ vec![0],
+ EchoUtf8Response {
+ text: ByteString(vec![]),
+ bytes: vec![],
+ }
+ .encode_message()
+ .unwrap()
+ .0,
+ ] {
+ let (server, handle) = Transport::create_paired().unwrap();
+ #[cfg(target_vendor = "apple")]
+ let client = Transport::from_handle(handle).unwrap();
+ #[cfg(not(target_vendor = "apple"))]
+ let client = Transport::new(handle).unwrap();
+ let thread = std::thread::spawn(move || serve(server));
+ for number in 0..100u32 {
+ reply(
+ &client,
+ EchoUtf8 {
+ text: ByteString(number.to_string().into_bytes()),
+ bytes: vec![],
+ },
+ )
+ .unwrap();
+ }
+ client.post_message(invalid, vec![]).unwrap();
+ for number in 0..100u32 {
+ let received = client.receive().unwrap();
+ let (bytes, attachments) = received.into_parts();
+ let Message::EchoUtf8Response(response) = Message::decode(bytes.as_ref(), attachments).unwrap() else {
+ panic!("expected EchoUtf8Response");
+ };
+ assert_eq!(response.text.0, number.to_string().as_bytes());
+ }
+ thread.join().unwrap();
+ assert!(client.receive().is_none());
+ }
+}
diff --git a/Tests/LibIPC/TestRustEchoServer.cpp b/Tests/LibIPC/TestRustEchoServer.cpp
new file mode 100644
index 00000000000..cbda5116ba9
--- /dev/null
+++ b/Tests/LibIPC/TestRustEchoServer.cpp
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/System.h>
+#include <LibIPC/Transport.h>
+#include <LibTest/TestCase.h>
+#include <RustEchoServerEndpoint.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/resource.h>
+
+// NB: Starts the Rust endpoint, which the IPC compiler generated Rust code for from the same definition as the C++ code
+// this test uses, and returns this end of a transport to it.
+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
+extern "C" void rust_echo_server_serve(mach_port_t receive_right, mach_port_t send_right);
+
+static NonnullOwnPtr<IPC::Transport> start_server()
+{
+ auto our_receive_right = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));
+ auto server_send_right = MUST(our_receive_right.insert_right(Core::MachPort::MessageRight::MakeSend));
+ auto server_receive_right = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));
+ auto our_send_right = MUST(server_receive_right.insert_right(Core::MachPort::MessageRight::MakeSend));
+ IPC::TransportMachPort::raise_receive_queue_limit(server_receive_right);
+ rust_echo_server_serve(server_receive_right.release(), server_send_right.release());
+ return make<IPC::TransportMachPort>(move(our_receive_right), move(our_send_right));
+}
+#else
+extern "C" void rust_echo_server_serve(int socket_fd);
+
+static NonnullOwnPtr<IPC::Transport> start_server()
+{
+ int fds[2] {};
+ MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, fds));
+ rust_echo_server_serve(fds[1]);
+ auto socket = MUST(Core::LocalSocket::adopt_fd(fds[0]));
+ MUST(socket->set_blocking(false));
+ return make<IPC::TransportSocket>(move(socket));
+}
+#endif
+
+static void send(IPC::Transport& transport, ErrorOr<IPC::MessageBuffer> encoded)
+{
+ auto buffer = MUST(move(encoded));
+ auto attachments = buffer.take_attachments();
+ MUST(transport.post_message(buffer.take_data(), attachments));
+}
+
+template<typename Response>
+static NonnullOwnPtr<Response> receive(IPC::Transport& transport)
+{
+ OwnPtr<IPC::Message> message;
+ while (!message) {
+ transport.wait_until_readable();
+ auto should_shutdown = transport.read_as_many_messages_as_possible_without_blocking([&](IPC::Transport::Message&& received) {
+ VERIFY(!message);
+ message = MUST(RustEchoServerEndpoint::decode_message(received.bytes.bytes(), received.attachments));
+ });
+ VERIFY(message || should_shutdown == IPC::Transport::ShouldShutdown::No);
+ }
+ VERIFY(message->message_id() == Response::static_message_id());
+ return adopt_own(static_cast<Response&>(*message.leak_ptr()));
+}
+
+TEST_CASE(values_make_a_round_trip_through_rust)
+{
+ auto transport = start_server();
+ auto utf16_text = Utf16String::from_utf8("naïve ✓"sv);
+ Vector<Optional<i64>> values { 1, {}, -3 };
+ auto bytes = MUST(ByteBuffer::copy("bytes"sv.bytes()));
+ send(*transport, Messages::RustEchoServer::Echo::static_encode(42, "héllo"sv, utf16_text.utf16_view(), values.span(), bytes.bytes()));
+
+ auto response = receive<Messages::RustEchoServer::EchoResponse>(*transport);
+ EXPECT_EQ(response->number(), 42u);
+ EXPECT_EQ(response->text(), "héllo"sv);
+ EXPECT_EQ(response->utf16_text(), utf16_text);
+ EXPECT_EQ(response->values(), values);
+ EXPECT_EQ(response->bytes(), bytes);
+}
+
+TEST_CASE(strings_with_lone_surrogates_make_a_round_trip_through_rust)
+{
+ auto transport = start_server();
+ auto text = MUST(String::from_utf8("a\xed\xa0\x80z"sv));
+ send(*transport, Messages::RustEchoServer::Echo::static_encode(1, text, Utf16View {}, {}, {}));
+ auto response = receive<Messages::RustEchoServer::EchoResponse>(*transport);
+ EXPECT_EQ(response->text().bytes(), text.bytes());
+}
+
+TEST_CASE(large_payloads_make_a_round_trip_through_rust)
+{
+ auto transport = start_server();
+ auto bytes = MUST(ByteBuffer::create_uninitialized(100'000));
+ for (size_t i = 0; i < bytes.size(); ++i)
+ bytes[i] = static_cast<u8>(i * 7);
+ Vector<Optional<i64>> values;
+ send(*transport, Messages::RustEchoServer::Echo::static_encode(1, ""sv, Utf16View {}, values.span(), bytes.bytes()));
+
+ auto response = receive<Messages::RustEchoServer::EchoResponse>(*transport);
+ EXPECT_EQ(response->bytes(), bytes);
+}
+
+TEST_CASE(files_go_to_rust_as_attachments)
+{
+ auto transport = start_server();
+ auto pipe = MUST(Core::System::pipe2(O_CLOEXEC));
+ send(*transport, Messages::RustEchoServer::WriteToFile::static_encode(IPC::File::adopt_fd(pipe[1]), "from rust"sv));
+ (void)receive<Messages::RustEchoServer::WriteToFileResponse>(*transport);
+
+ char buffer[32] = {};
+ auto read = MUST(Core::System::read(pipe[0], { buffer, sizeof(buffer) }));
+ EXPECT_EQ(StringView(buffer, read), "from rust"sv);
+ MUST(Core::System::close(pipe[0]));
+}
+
+// NB: Linux fails sending descriptors once all those the user has in flight exceed the sender's limit, which other
+// processes running at the same time count towards, so raise it as LibMain does for every process.
+static void raise_descriptor_limit()
+{
+ rlimit limit {};
+ VERIFY(getrlimit(RLIMIT_NOFILE, &limit) == 0);
+ limit.rlim_cur = min<rlim_t>(limit.rlim_max, 65536);
+#if defined(AK_OS_MACOS) || defined(AK_OS_IOS)
+ // NB: macOS rejects a descriptor limit above OPEN_MAX, but still needs one above its default of 256.
+ limit.rlim_cur = min<rlim_t>(limit.rlim_cur, OPEN_MAX);
+#endif
+ VERIFY(setrlimit(RLIMIT_NOFILE, &limit) == 0);
+}
+
+TEST_CASE(many_files_make_a_round_trip_through_rust)
+{
+ // NB: More files than one sendmsg() carries, so that on sockets some go ahead of the message.
+ static constexpr size_t file_count = 200;
+ raise_descriptor_limit();
+ auto transport = start_server();
+ Vector<int> readers;
+ Vector<IPC::File> files;
+ for (size_t i = 0; i < file_count; ++i) {
+ auto pipe = MUST(Core::System::pipe2(O_CLOEXEC));
+ readers.append(pipe[0]);
+ files.append(IPC::File::adopt_fd(pipe[1]));
+ }
+ send(*transport, Messages::RustEchoServer::EchoFiles::static_encode(files));
+
+ auto returned_files = receive<Messages::RustEchoServer::EchoFilesResponse>(*transport)->take_files();
+ EXPECT_EQ(returned_files.size(), file_count);
+ for (size_t i = 0; i < min(returned_files.size(), file_count); ++i) {
+ auto fd = returned_files[i].take_fd();
+ MUST(Core::System::write(fd, "!"sv.bytes()));
+ MUST(Core::System::close(fd));
+ char buffer = 0;
+ EXPECT_EQ(MUST(Core::System::read(readers[i], { &buffer, 1 })), 1uz);
+ EXPECT_EQ(buffer, '!');
+ }
+ for (auto reader : readers)
+ MUST(Core::System::close(reader));
+}
+
+TEST_CASE(the_rust_end_closing_ends_the_connection)
+{
+ auto transport = start_server();
+ send(*transport, Messages::RustEchoServer::Stop::static_encode());
+ auto should_shutdown = IPC::Transport::ShouldShutdown::No;
+ while (should_shutdown == IPC::Transport::ShouldShutdown::No) {
+ transport->wait_until_readable();
+ should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([](auto&&) { VERIFY_NOT_REACHED(); });
+ }
+}
+
+TEST_CASE(utf8_attributes_match_cpp_validation)
+{
+ for (auto text : { ""sv, "héllo"sv, "\xed\xa0\x80\xed\xbf\xbf"sv }) {
+ auto transport = start_server();
+ send(*transport, Messages::RustEchoServer::EchoUtf8::static_encode(text, text.bytes()));
+ auto response = receive<Messages::RustEchoServer::EchoUtf8Response>(*transport);
+ EXPECT_EQ(response->text(), text);
+ EXPECT_EQ(response->bytes().bytes(), text.bytes());
+ }
+ for (auto text : { "\xff"sv, "\xc0\x80"sv, "\xe2\x82"sv, "\xed\xa0\x80\xff"sv, "\xf4\x90\x80\x80"sv }) {
+ for (auto invalid_text : { true, false }) {
+ auto string = invalid_text ? text : ""sv;
+ auto bytes = invalid_text ? ""sv.bytes() : text.bytes();
+ auto buffer = MUST(Messages::RustEchoServer::EchoUtf8::static_encode(string, bytes));
+ Queue<IPC::Attachment> attachments;
+ EXPECT(RustEchoServerEndpoint::decode_message(buffer.data(), attachments).is_error());
+ auto response = MUST(Messages::RustEchoServer::EchoUtf8Response::static_encode(string, bytes));
+ EXPECT(RustEchoServerEndpoint::decode_message(response.data(), attachments).is_error());
+ }
+ }
+}
+
+TEST_CASE(cpp_decoder_accepts_unused_attachments)
+{
+ auto buffer = MUST(Messages::RustEchoServer::Stop::static_encode());
+ auto pipe = MUST(Core::System::pipe2(O_CLOEXEC));
+ Queue<IPC::Attachment> attachments;
+ attachments.enqueue(IPC::Attachment::from_fd(pipe[1]));
+ EXPECT(!RustEchoServerEndpoint::decode_message(buffer.data(), attachments).is_error());
+ EXPECT_EQ(attachments.size(), 1u);
+ MUST(Core::System::close(pipe[0]));
+}
+
+TEST_CASE(cpp_and_rust_decoders_accept_trailing_bytes)
+{
+ auto buffer = MUST(Messages::RustEchoServer::EchoUtf8::static_encode("hello"sv, {}));
+ auto bytes = buffer.take_data();
+ MUST(bytes.try_append(0));
+ Queue<IPC::Attachment> attachments;
+ EXPECT(!RustEchoServerEndpoint::decode_message(bytes, attachments).is_error());
+ auto transport = start_server();
+ Vector<IPC::Attachment> outgoing_attachments;
+ MUST(transport->post_message(move(bytes), outgoing_attachments));
+ auto response = receive<Messages::RustEchoServer::EchoUtf8Response>(*transport);
+ EXPECT_EQ(response->text(), "hello"sv);
+}