Skip to content

Truly independent web browser

LibWeb: Frame MessagePort transport messages in Rust

Shannon Booth9ca4a1cb15db
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs
index 58649ab0aad..e5402011614 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/transport.rs
@@ -12,7 +12,6 @@ use core::any::Any;
use core::ffi::c_void;
use core::ptr::NonNull;
-use crate::html::structured_serialize::cpp::OwnedSerializedTransferRecord;
use crate::html::structured_serialize::transfer_data_holder::{
RawAttachment, ReceivePayload, TransferPayload, append_attachments,
};
@@ -42,11 +41,16 @@ unsafe extern "C" {
fn web_bindings_message_port_transport_is_open(transport: *mut c_void) -> bool;
fn web_bindings_message_port_transport_close(transport: *mut c_void);
fn web_bindings_message_port_transport_close_after_sending_all_pending_messages(transport: *mut c_void);
- fn web_bindings_message_port_transport_send(transport: *mut c_void, record: *mut c_void) -> bool;
+ fn web_bindings_message_port_transport_send(
+ transport: *mut c_void,
+ bytes: ak::Span<'_, u8>,
+ attachments: *const RawAttachment,
+ count: usize,
+ ) -> bool;
fn web_bindings_message_port_transport_read_messages(
transport: *mut c_void,
records: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ append: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, *const RawAttachment, usize) -> bool,
) -> bool;
}
@@ -223,9 +227,20 @@ impl MessagePortTransport {
/// Sends the record to the peer as one message. False if the transport failed, which LibWeb logs.
pub(crate) fn send(&self, vm: &Vm, record: TransferRecordRef) -> bool {
- let record = TransferRecord::into_cpp(record, vm);
- // SAFETY: This owns the transport, and the call borrows the record.
- unsafe { web_bindings_message_port_transport_send(self.raw.as_ptr(), record.record().as_raw()) }
+ let mut encoder = Encoder::new();
+ TransferRecord::encode_into(record, vm, &mut encoder).expect("a message record encodes");
+ let (bytes, attachments) = encoder.finish();
+ TransferPayload { bytes, attachments }.with_raw(|bytes, attachments| {
+ // SAFETY: This owns the transport. The call copies the bytes and takes every native attachment.
+ unsafe {
+ web_bindings_message_port_transport_send(
+ self.raw.as_ptr(),
+ bytes,
+ attachments.as_ptr(),
+ attachments.len(),
+ )
+ }
+ })
}
/// Appends every message that has arrived, each a record, and tells whether the peer is gone.
@@ -234,11 +249,26 @@ impl MessagePortTransport {
vm: &Vm,
records: &MarkedVec<'_, TransferRecordRef>,
) -> ShouldShutdown {
- unsafe extern "C" fn append(context: *mut c_void, record: *mut c_void) {
- // SAFETY: The read lends its VM and rooted list, and C++ hands over the carrier.
+ unsafe extern "C" fn append(
+ context: *mut c_void,
+ bytes: ak::Span<'_, u8>,
+ attachments: *const RawAttachment,
+ count: usize,
+ ) -> 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 carrier = unsafe { OwnedSerializedTransferRecord::from_raw(record) };
- records.push(TransferRecord::from_cpp(vm, carrier.record()));
+ let attachments = unsafe { RawAttachment::take_all(attachments, count) };
+ let mut decoder = Decoder::new(bytes.as_slice(), attachments);
+ match TransferRecord::decode(vm, &mut decoder) {
+ Ok(record) => {
+ records.push(record);
+ true
+ }
+ Err(error) => {
+ eprintln!("Failed to decode a MessagePort message: {error:?}");
+ false
+ }
+ }
}
let mut context = (vm, records);
// SAFETY: This owns the transport, and lends the records for the call.
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 75b61c06e90..b071bd05c01 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -119,8 +119,6 @@ void web_bindings_message_port_transport_set_up_read_hook(IPC::Transport*, void*
bool web_bindings_message_port_transport_is_open(IPC::Transport*);
void web_bindings_message_port_transport_close(IPC::Transport*);
void web_bindings_message_port_transport_close_after_sending_all_pending_messages(IPC::Transport*);
-bool web_bindings_message_port_transport_send(IPC::Transport*, HTML::SerializedTransferRecord const*);
-bool web_bindings_message_port_transport_read_messages(IPC::Transport*, void* records, void (*append)(void*, HTML::SerializedTransferRecord*));
void* web_css_wrap_object(void* realm, void* cell);
void* web_css_realm_document(void* realm);
@@ -326,40 +324,6 @@ void web_bindings_message_port_transport_close_after_sending_all_pending_message
transport->close_after_sending_all_pending_messages();
}
-// Sends the record to the peer as one message, or logs the failure and returns false.
-bool web_bindings_message_port_transport_send(IPC::Transport* transport, HTML::SerializedTransferRecord const* record)
-{
- IPC::MessageBuffer buffer;
- IPC::Encoder encoder(buffer);
- MUST(encoder.encode(*record));
- if (auto result = buffer.transfer_message(*transport); result.is_error()) {
- dbgln("Failed to post message: {}", result.error());
- return false;
- }
- return true;
-}
-
-// Hands over every message that has arrived as the record it carries, and returns whether the peer is gone, so that
-// nothing more arrives. A message that is not a record is treated as the peer going away, along with what follows it.
-bool web_bindings_message_port_transport_read_messages(IPC::Transport* transport, void* records, void (*append)(void*, HTML::SerializedTransferRecord*))
-{
- bool failed_to_decode = false;
- auto should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
- if (failed_to_decode)
- return;
- FixedMemoryStream stream { message.bytes.bytes() };
- IPC::Decoder decoder { stream, message.attachments };
- auto record = decoder.decode<HTML::SerializedTransferRecord>();
- if (record.is_error()) {
- dbgln("Failed to decode a MessagePort message: {}", record.error());
- failed_to_decode = true;
- return;
- }
- append(records, new HTML::SerializedTransferRecord(record.release_value()));
- });
- return failed_to_decode || should_shutdown == IPC::Transport::ShouldShutdown::Yes;
-}
-
JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason)
{
auto& realm = *static_cast<JS::Realm*>(current_realm);
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index 33ee5cdf449..d8f1d1bc5c1 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -60,7 +60,8 @@ static Vector<IPC::Attachment> adopt_attachments(TransferAttachment const* raw,
return attachments;
}
-static void hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attachments, void* context, ReceiveTransferPayload receive)
+template<typename Receive>
+static auto hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attachments, void* context, Receive receive)
{
Vector<TransferAttachment> raw;
for (auto& attachment : attachments) {
@@ -71,7 +72,7 @@ static void hand_over_payload(ReadonlyBytes bytes, Vector<IPC::Attachment> attac
raw.append({ attachment.to_fd(), 0 });
#endif
}
- receive(context, bytes, raw.data(), raw.size());
+ return receive(context, bytes, raw.data(), raw.size());
}
extern "C" {
@@ -98,6 +99,8 @@ void web_structured_serialize_transfer_data_holder_take(TransferDataEncoder*, vo
void web_structured_serialize_transfer_handle_take(IPC::TransportHandle*, void*, ReceiveTransferPayload);
IPC::Transport* web_structured_serialize_transfer_handle_create_transport(ReadonlyBytes, TransferAttachment const*, size_t);
bool web_structured_serialize_validate_shared_memory(int, size_t);
+bool web_bindings_message_port_transport_send(IPC::Transport*, ReadonlyBytes, TransferAttachment const*, size_t);
+bool web_bindings_message_port_transport_read_messages(IPC::Transport*, void*, bool (*)(void*, ReadonlyBytes, TransferAttachment const*, size_t));
SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t, TransferDataEncoder* const*, size_t);
void web_structured_serialize_transfer_record_destroy(SerializedTransferRecord*);
void web_structured_serialize_transfer_record_take(SerializedTransferRecord*, void*, void (*)(void*, ReadonlyBytes, JSObject* const*, size_t, int const*, size_t const*, size_t), void (*)(void*, TransferDataEncoder*));
@@ -262,6 +265,33 @@ bool web_structured_serialize_validate_shared_memory(int descriptor, size_t size
return !buffer.value().validate_backing_size().is_error();
}
+bool web_bindings_message_port_transport_send(IPC::Transport* transport, ReadonlyBytes bytes, TransferAttachment const* attachments, size_t count)
+{
+ IPC::MessageDataType data;
+ MUST(data.try_append(bytes.data(), bytes.size()));
+ IPC::MessageBuffer buffer { move(data), adopt_attachments(attachments, count) };
+ if (auto result = buffer.transfer_message(*transport); result.is_error()) {
+ dbgln("Failed to post message: {}", result.error());
+ return false;
+ }
+ return true;
+}
+
+bool web_bindings_message_port_transport_read_messages(IPC::Transport* transport, void* context, bool (*receive)(void*, ReadonlyBytes, TransferAttachment const*, size_t))
+{
+ bool failed_to_decode = false;
+ auto should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {
+ // The peer is treated as gone after a malformed record. Later messages still release all their attachments.
+ if (failed_to_decode)
+ return;
+ Vector<IPC::Attachment> attachments;
+ while (!message.attachments.is_empty())
+ attachments.append(message.attachments.dequeue());
+ failed_to_decode = !hand_over_payload(message.bytes.bytes(), move(attachments), context, receive);
+ });
+ return failed_to_decode || should_shutdown == IPC::Transport::ShouldShutdown::Yes;
+}
+
// Takes over the descriptors and the data holders.
SerializedTransferRecord* web_structured_serialize_transfer_record_create(ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t shared_array_buffer_count, int const* shared_memory, size_t const* sizes, size_t shared_memory_count, TransferDataEncoder* const* holders, size_t holder_count)
{