Truly independent web browser
LibIPC: Send large message payloads through shared memory
Tim Ledbetterd8afe7ddba44
diff --git a/Libraries/LibIPC/HandleBroker.cpp b/Libraries/LibIPC/HandleBroker.cppindex b3c8559d46f..532527ebd7e 100644--- a/Libraries/LibIPC/HandleBroker.cpp+++ b/Libraries/LibIPC/HandleBroker.cpp@@ -21,6 +21,9 @@ namespace IPC {static NeverDestroyed<Mutex> s_installed_broker_mutex;static NeverDestroyed<OwnPtr<HandleBroker>> s_installed_broker;+static constexpr size_t MAX_HANDLE_BROKER_MESSAGE_SIZE = sizeof(HandleBrokerOperation) + sizeof(HandleBrokerToken) + sizeof(HandleBrokerChannel) + sizeof(u32) + MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY * sizeof(u64);+static_assert(MAX_HANDLE_BROKER_MESSAGE_SIZE <= TransportWindows::MAX_INLINE_PAYLOAD_SIZE);+HandleBroker& HandleBroker::the(){MutexLocker locker(*s_installed_broker_mutex);@@ -47,7 +50,7 @@ static ErrorOr<void> encode_handle_values(Encoder& encoder, Vector<u64> const& hstatic ErrorOr<Vector<u64>> decode_handle_values(Decoder& decoder){auto count = TRY(decoder.decode<u32>());- if (count > MAX_MESSAGE_FD_COUNT)+ if (count > MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY)return Error::from_string_literal("Handle broker message names too many handles");Vector<u64> handle_values;diff --git a/Libraries/LibIPC/Limits.h b/Libraries/LibIPC/Limits.hindex a7f356ca578..000e68839f9 100644--- a/Libraries/LibIPC/Limits.h+++ b/Libraries/LibIPC/Limits.h@@ -6,16 +6,20 @@#pragma once+#include <AK/NumericLimits.h>#include <AK/Types.h>namespace IPC {-// Maximum size of an IPC message payload (64 MiB should be more than enough)-static constexpr size_t MAX_MESSAGE_PAYLOAD_SIZE = 64 * MiB;+// Maximum size of an IPC message payload+static constexpr size_t MAX_MESSAGE_PAYLOAD_SIZE = NumericLimits<u32>::max();// Maximum number of file descriptors per message. Transports carry any number up to this, however few fit in one// system call. It stays below the 16383 port rights that XNU accepts in one Mach message, so that a message is never// split there, and far below the descriptor limit LibMain raises every process to.static constexpr size_t MAX_MESSAGE_FD_COUNT = 16000;+// A transport that sends a payload in shared memory attaches one more descriptor to its message.+static constexpr size_t MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY = MAX_MESSAGE_FD_COUNT + 1;+}diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cppindex 5b5a5993855..d7b5c95d5b2 100644--- a/Libraries/LibIPC/TransportSocket.cpp+++ b/Libraries/LibIPC/TransportSocket.cpp@@ -18,7 +18,9 @@#include <LibIPC/TransportHandle.h>#include <LibIPC/TransportSocket.h>#include <LibThreading/Thread.h>+#include <fcntl.h>#include <sys/ioctl.h>+#include <unistd.h>namespace IPC {@@ -28,7 +30,7 @@ static constexpr size_t MAX_UNPROCESSED_BUFFER_SIZE = 128 * MiB;// Maximum number of accumulated unprocessed file descriptors before we disconnect the peer. Descriptors are parsed// after every read, and one read takes the descriptors of at most one sendmsg(). So, the most a well-behaved peer can// leave unclaimed is a whole message's, plus those that arrive with the read that completes it.-static constexpr size_t MAX_UNPROCESSED_FDS = MAX_MESSAGE_FD_COUNT + Core::LocalSocket::MAX_TRANSFER_FDS;+static constexpr size_t MAX_UNPROCESSED_FDS = MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY + Core::LocalSocket::MAX_TRANSFER_FDS;// Size of the buffer for one read from the socketstatic constexpr size_t READ_BUFFER_SIZE = 4096;@@ -432,20 +434,62 @@ void TransportSocket::wait_until_readable()}}-ErrorOr<void> TransportSocket::post_message(MessageDataType bytes_to_write, Vector<Attachment>& attachments)+static ErrorOr<NonnullRefPtr<AutoCloseFileDescriptor>> copy_payload_to_shared_memory(ReadonlyBytes payload)+{+ auto shared_memory = adopt_ref(*new AutoCloseFileDescriptor(TRY(Core::System::anon_create(payload.size(), O_CLOEXEC))));+ while (!payload.is_empty())+ payload = payload.slice(TRY(Core::System::write(shared_memory->value(), payload)));+ return shared_memory;+}++// The peer can still write to the shared memory or truncate it, so we copy the payload out before parsing it. Unlike a+// read from a mapping, pread() reports a truncation as a short read instead of raising SIGBUS.+static ErrorOr<Vector<u8>> copy_payload_from_shared_memory(int fd, size_t size){- auto num_fds_to_transfer = attachments.size();+ auto stat = TRY(Core::System::fstat(fd));+ if (static_cast<u64>(stat.st_size) < size)+ return Error::from_string_literal("Shared memory is smaller than the payload size");++ Vector<u8> payload;+ TRY(payload.try_resize(size));++ size_t copied_size = 0;+ while (copied_size < size) {+ auto bytes_read = ::pread(fd, payload.data() + copied_size, size - copied_size, static_cast<off_t>(copied_size));+ if (bytes_read < 0) {+ if (errno == EINTR)+ continue;+ return Error::from_errno(errno);+ }+ if (bytes_read == 0)+ return Error::from_string_literal("Shared memory is smaller than the payload size");+ copied_size += static_cast<size_t>(bytes_read);+ }+ return payload;+}+ErrorOr<void> TransportSocket::post_message(MessageDataType bytes_to_write, Vector<Attachment>& attachments)+{SocketMessageHeader header {.type = SocketMessageHeader::Type::Payload,.payload_size = static_cast<u32>(bytes_to_write.size()),- .fd_count = static_cast<u32>(num_fds_to_transfer),+ .fd_count = static_cast<u32>(attachments.size()),};+ RefPtr<AutoCloseFileDescriptor> shared_memory;+ if (bytes_to_write.size() > MAX_INLINE_PAYLOAD_SIZE) {+ shared_memory = TRY(copy_payload_to_shared_memory(bytes_to_write));+ bytes_to_write.clear();+ header.type = SocketMessageHeader::Type::SharedMemoryPayload;+ ++header.fd_count;+ }+Vector<NonnullRefPtr<AutoCloseFileDescriptor>> fds;- fds.ensure_capacity(num_fds_to_transfer);+ fds.ensure_capacity(header.fd_count);for (auto& attachment : attachments)fds.unchecked_append(adopt_ref(*new AutoCloseFileDescriptor(attachment.to_fd())));+ if (shared_memory)+ fds.unchecked_append(shared_memory.release_nonnull());m_send_queue->enqueue_message(header, move(bytes_to_write), move(fds));wake_io_thread();@@ -508,6 +552,7 @@ void TransportSocket::parse_unprocessed_messages(Vector<NonnullOwnPtr<Message>>&while (index + sizeof(SocketMessageHeader) <= m_unprocessed_bytes.size()) {SocketMessageHeader header;memcpy(&header, m_unprocessed_bytes.data() + index, sizeof(SocketMessageHeader));+ size_t frame_payload_size = 0;if (header.type == SocketMessageHeader::Type::Attachments) {// NB: These descriptors were queued as they arrived. The Payload frame that follows claims them.if (header.payload_size != 0 || header.fd_count > Core::LocalSocket::MAX_TRANSFER_FDS) {@@ -515,28 +560,47 @@ void TransportSocket::parse_unprocessed_messages(Vector<NonnullOwnPtr<Message>>&m_peer_eof = true;break;}- } else if (header.type == SocketMessageHeader::Type::Payload) {- if (header.payload_size > MAX_MESSAGE_PAYLOAD_SIZE) {- dbgln("TransportSocket: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_MESSAGE_PAYLOAD_SIZE);+ } else if (header.type == SocketMessageHeader::Type::Payload || header.type == SocketMessageHeader::Type::SharedMemoryPayload) {+ bool payload_is_in_shared_memory = header.type == SocketMessageHeader::Type::SharedMemoryPayload;+ if (!payload_is_in_shared_memory && header.payload_size > MAX_INLINE_PAYLOAD_SIZE) {+ dbgln("TransportSocket: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_INLINE_PAYLOAD_SIZE);m_peer_eof = true;break;}- if (header.fd_count > MAX_MESSAGE_FD_COUNT) {- dbgln("TransportSocket: Rejecting message with fd_count {} exceeding limit {}", header.fd_count, MAX_MESSAGE_FD_COUNT);+ auto max_fd_count = payload_is_in_shared_memory ? MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY : MAX_MESSAGE_FD_COUNT;+ if (header.fd_count > max_fd_count) {+ dbgln("TransportSocket: Rejecting message with fd_count {} exceeding limit {}", header.fd_count, max_fd_count);m_peer_eof = true;break;}- Checked<size_t> message_size = header.payload_size;+ if (payload_is_in_shared_memory && header.fd_count == 0) {+ dbgln("TransportSocket: Rejecting shared memory message without a descriptor");+ m_peer_eof = true;+ break;+ }+ if (!payload_is_in_shared_memory)+ frame_payload_size = header.payload_size;+ Checked<size_t> message_size = frame_payload_size;message_size += sizeof(SocketMessageHeader);if (message_size.has_overflow() || message_size.value() > m_unprocessed_bytes.size() - index)break;if (header.fd_count > m_unprocessed_attachments.size())break;auto message = make<Message>();- for (size_t i = 0; i < header.fd_count; ++i)+ auto attachment_count = payload_is_in_shared_memory ? header.fd_count - 1 : header.fd_count;+ for (size_t i = 0; i < attachment_count; ++i)message->attachments.enqueue(m_unprocessed_attachments.dequeue());Vector<u8> payload_bytes;- if (payload_bytes.try_append(m_unprocessed_bytes.data() + index + sizeof(SocketMessageHeader), header.payload_size).is_error()) {+ if (payload_is_in_shared_memory) {+ auto shared_memory = m_unprocessed_attachments.dequeue();+ auto copied_bytes = copy_payload_from_shared_memory(shared_memory.fd(), header.payload_size);+ if (copied_bytes.is_error()) {+ dbgln("TransportSocket: Failed to copy payload_size {} from shared memory: {}", header.payload_size, copied_bytes.error());+ m_peer_eof = true;+ break;+ }+ payload_bytes = copied_bytes.release_value();+ } else if (payload_bytes.try_append(m_unprocessed_bytes.data() + index + sizeof(SocketMessageHeader), header.payload_size).is_error()) {dbgln("TransportSocket: Failed to allocate message buffer for payload_size {}", header.payload_size);m_peer_eof = true;break;@@ -549,7 +613,7 @@ void TransportSocket::parse_unprocessed_messages(Vector<NonnullOwnPtr<Message>>&break;}Checked<size_t> new_index = index;- new_index += header.payload_size;+ new_index += frame_payload_size;new_index += sizeof(SocketMessageHeader);if (new_index.has_overflow()) {dbgln("TransportSocket: index would overflow");diff --git a/Libraries/LibIPC/TransportSocket.h b/Libraries/LibIPC/TransportSocket.hindex 1caf17443fe..3748a929509 100644--- a/Libraries/LibIPC/TransportSocket.h+++ b/Libraries/LibIPC/TransportSocket.h@@ -33,11 +33,13 @@ namespace IPC {// NB: One sendmsg() carries a limited number of descriptors, and at least one byte with them. A message with more// descriptors sends the rest ahead of it, in Attachments frames that have no payload. A Payload frame's fd_count-// counts every descriptor of its message, including those that arrived ahead of it.+// counts every descriptor of its message, including those that arrived ahead of it. A SharedMemoryPayload frame+// has no bytes, and its shared memory is the last descriptor of its message.struct SocketMessageHeader {enum class Type : u8 {Payload = 0,Attachments = 1,+ SharedMemoryPayload = 2,};Type type { Type::Payload };u32 payload_size { 0 };@@ -82,6 +84,7 @@ public:AK_ALLOC_WITH_KMALLOC;static constexpr socklen_t SOCKET_BUFFER_SIZE = 128 * KiB;+ static constexpr size_t MAX_INLINE_PAYLOAD_SIZE = 64 * KiB;struct Paired {NonnullOwnPtr<TransportSocket> local;diff --git a/Libraries/LibIPC/TransportWindows.cpp b/Libraries/LibIPC/TransportWindows.cppindex 8b528f69e8f..292ee405ce2 100644--- a/Libraries/LibIPC/TransportWindows.cpp+++ b/Libraries/LibIPC/TransportWindows.cpp@@ -10,6 +10,7 @@#include <AK/NumericLimits.h>#include <AK/Random.h>#include <AK/ScopeGuard.h>+#include <LibCore/AnonymousBuffer.h>#include <LibCore/Notifier.h>#include <LibCore/Socket.h>#include <LibCore/System.h>@@ -22,12 +23,19 @@namespace IPC {-// A message with attachments carries the handle broker token that names them right after its header.+// A message with attachments carries the handle broker token that names them right after its header. A section+// holding the payload is the last of those attachments.struct TransportWindows::MessageHeader {+ enum class PayloadLocation : u8 {+ Inline = 0,+ SharedMemory = 1,+ };u32 payload_size { 0 };u32 attachment_count { 0 };+ PayloadLocation payload_location { PayloadLocation::Inline };size_t token_size() const { return attachment_count > 0 ? sizeof(HandleBrokerToken) : 0; }+ size_t inline_payload_size() const { return payload_location == PayloadLocation::Inline ? payload_size : 0; }};// Maximum size of accumulated unprocessed bytes before we disconnect the peer@@ -247,6 +255,21 @@ ErrorOr<void> TransportWindows::transfer(ReadonlyBytes bytes_to_write)return {};}+static ErrorOr<Attachment> copy_payload_to_shared_memory(ReadonlyBytes payload)+{+ auto section = TRY(Core::AnonymousBuffer::create_with_size(payload.size()));+ payload.copy_to({ section.data<u8>(), section.size() });+ return Attachment::from_fd(TRY(Core::System::dup(section.fd())));+}++static ErrorOr<Vector<u8>> copy_payload_from_shared_memory(Attachment section, size_t size)+{+ auto buffer = TRY(Core::AnonymousBuffer::create_from_anon_fd(section.to_fd(), size));+ Vector<u8> payload;+ TRY(payload.try_append(buffer.bytes().data(), buffer.size()));+ return payload;+}+ErrorOr<void> TransportWindows::post_message(MessageDataType bytes, Vector<Attachment>& attachments){VERIFY(bytes.size() <= MAX_MESSAGE_PAYLOAD_SIZE);@@ -258,6 +281,12 @@ ErrorOr<void> TransportWindows::post_message(MessageDataType bytes, Vector<Attac.payload_size = static_cast<u32>(bytes.size()),.attachment_count = static_cast<u32>(attachments.size()),};+ if (bytes.size() > MAX_INLINE_PAYLOAD_SIZE) {+ attachments.append(TRY(copy_payload_to_shared_memory(bytes)));+ bytes.clear();+ header.payload_location = MessageHeader::PayloadLocation::SharedMemory;+ ++header.attachment_count;+ }HandleBrokerToken attachment_token = 0;if (!attachments.is_empty()) {attachment_token = TRY(HandleBroker::the().park(m_handle_broker_channel, move(attachments)));@@ -372,24 +401,37 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_posswhile (index + sizeof(MessageHeader) <= m_unprocessed_bytes.size()) {MessageHeader header;memcpy(&header, m_unprocessed_bytes.data() + index, sizeof(MessageHeader));- if (header.payload_size > MAX_MESSAGE_PAYLOAD_SIZE) {- dbgln("TransportWindows: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_MESSAGE_PAYLOAD_SIZE);+ if (header.payload_location != MessageHeader::PayloadLocation::Inline && header.payload_location != MessageHeader::PayloadLocation::SharedMemory) {+ dbgln("TransportWindows: Rejecting message with unknown payload location {}", to_underlying(header.payload_location));should_shutdown = ShouldShutdown::Yes;break;}- if (header.attachment_count > MAX_MESSAGE_FD_COUNT) {- dbgln("TransportWindows: Rejecting message with attachment_count {} exceeding limit {}", header.attachment_count, MAX_MESSAGE_FD_COUNT);+ bool payload_is_in_shared_memory = header.payload_location == MessageHeader::PayloadLocation::SharedMemory;+ if (!payload_is_in_shared_memory && header.payload_size > MAX_INLINE_PAYLOAD_SIZE) {+ dbgln("TransportWindows: Rejecting message with payload_size {} exceeding limit {}", header.payload_size, MAX_INLINE_PAYLOAD_SIZE);+ should_shutdown = ShouldShutdown::Yes;+ break;+ }+ auto max_attachment_count = payload_is_in_shared_memory ? MAX_MESSAGE_FD_COUNT_WITH_SHARED_MEMORY : MAX_MESSAGE_FD_COUNT;+ if (header.attachment_count > max_attachment_count) {+ dbgln("TransportWindows: Rejecting message with attachment_count {} exceeding limit {}", header.attachment_count, max_attachment_count);+ should_shutdown = ShouldShutdown::Yes;+ break;+ }+ if (payload_is_in_shared_memory && header.attachment_count == 0) {+ dbgln("TransportWindows: Rejecting shared memory message without a section");should_shutdown = ShouldShutdown::Yes;break;}- Checked<size_t> message_size = header.payload_size;+ Checked<size_t> message_size = header.inline_payload_size();message_size += sizeof(MessageHeader);message_size += header.token_size();if (message_size.has_overflow() || message_size.value() > m_unprocessed_bytes.size() - index)break;Message message;+ Attachment section;if (header.attachment_count > 0) {HandleBrokerToken attachment_token = 0;memcpy(&attachment_token, m_unprocessed_bytes.data() + index + sizeof(MessageHeader), sizeof(attachment_token));@@ -399,13 +441,23 @@ TransportWindows::ShouldShutdown TransportWindows::read_as_many_messages_as_possshould_shutdown = ShouldShutdown::Yes;break;}+ if (payload_is_in_shared_memory)+ section = attachments.value().take_last();for (auto& attachment : attachments.value())message.attachments.enqueue(move(attachment));}auto const* payload = m_unprocessed_bytes.data() + index + sizeof(MessageHeader) + header.token_size();Vector<u8> payload_bytes;- if (payload_bytes.try_append(payload, header.payload_size).is_error()) {+ if (payload_is_in_shared_memory) {+ auto copied_bytes = copy_payload_from_shared_memory(move(section), header.payload_size);+ if (copied_bytes.is_error()) {+ dbgln("TransportWindows: Failed to copy payload_size {} from shared memory: {}", header.payload_size, copied_bytes.error());+ should_shutdown = ShouldShutdown::Yes;+ break;+ }+ payload_bytes = copied_bytes.release_value();+ } else if (payload_bytes.try_append(payload, header.payload_size).is_error()) {dbgln("TransportWindows: Failed to allocate message buffer for payload_size {}", header.payload_size);should_shutdown = ShouldShutdown::Yes;break;diff --git a/Libraries/LibIPC/TransportWindows.h b/Libraries/LibIPC/TransportWindows.hindex 88dfa0ca30d..e55664bddd4 100644--- a/Libraries/LibIPC/TransportWindows.h+++ b/Libraries/LibIPC/TransportWindows.h@@ -34,6 +34,8 @@ class TransportWindows {public:AK_ALLOC_WITH_KMALLOC;+ static constexpr size_t MAX_INLINE_PAYLOAD_SIZE = 1 * MiB;+struct Paired {NonnullOwnPtr<TransportWindows> local;TransportHandle remote_handle;diff --git a/Tests/LibIPC/TestConnection.cpp b/Tests/LibIPC/TestConnection.cppindex 29df5673c2f..e195e266449 100644--- a/Tests/LibIPC/TestConnection.cpp+++ b/Tests/LibIPC/TestConnection.cpp@@ -4,7 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Array.h>#include <AK/Atomic.h>+#include <AK/ByteBuffer.h>#include <AK/ByteReader.h>#include <AK/ByteString.h>#include <AK/Function.h>@@ -165,6 +167,14 @@ ErrorOr<PeerCloseOutcome> send_one_message_then_close_peer(bool peer_owns_this_preturn outcome;}+ByteBuffer patterned_bytes(size_t size, u8 seed)+{+ auto bytes = MUST(ByteBuffer::create_uninitialized(size));+ for (size_t i = 0; i < size; ++i)+ bytes[i] = static_cast<u8>(seed + i % 251);+ return bytes;+}+}TEST_CASE(taking_unprocessed_messages_includes_the_current_dispatch_batch)@@ -252,6 +262,42 @@ TEST_CASE(anonymous_buffer_size_uses_64_bits)EXPECT_EQ(decoded_buffer.size(), buffer_size);}+TEST_CASE(payloads_of_any_size_arrive_intact_with_their_attachments)+{+ auto pair = TRY_OR_FAIL(IPC::Transport::create_paired());+ auto receiver = TRY_OR_FAIL(pair.remote_handle.create_transport());++ Array<size_t, 3> payload_sizes { 1 * KiB, 2 * MiB, 65 * MiB };+ for (size_t i = 0; i < payload_sizes.size(); ++i) {+ auto attachment = TRY_OR_FAIL(Core::AnonymousBuffer::create_with_size(sizeof(size_t)));+ *attachment.data<size_t>() = i;++ IPC::MessageBuffer buffer;+ IPC::Encoder encoder { buffer };+ TRY_OR_FAIL(encoder.encode(patterned_bytes(payload_sizes[i], static_cast<u8>(i))));+ TRY_OR_FAIL(encoder.encode(attachment));+ TRY_OR_FAIL(buffer.transfer_message(*pair.local));+ }++ size_t received = 0;+ while (received < payload_sizes.size()) {+ receiver->wait_until_readable();+ auto should_shutdown = receiver->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ FixedMemoryStream stream { message.bytes.bytes() };+ IPC::Decoder decoder { stream, message.attachments };+ auto payload = MUST(decoder.decode<ByteBuffer>());+ auto attachment = MUST(decoder.decode<Core::AnonymousBuffer>());+ EXPECT(payload == patterned_bytes(payload_sizes[received], static_cast<u8>(received)));+ EXPECT_EQ(*attachment.data<size_t>(), received);+ EXPECT(message.attachments.is_empty());+ ++received;+ });+ if (should_shutdown == IPC::Transport::ShouldShutdown::Yes)+ break;+ }+ EXPECT_EQ(received, payload_sizes.size());+}+// Regression test for #9582. wait_for_specific_endpoint_message_impl is reachable from any sync IPC call, including// from inside a constructor whose members are still being initialized (e.g., PageHost's construction issues a sync// allocate_compositor_context_id IPC call before ConnectionFromClient::m_page_host has been assigned). If the peerdiff --git a/Tests/LibIPC/TestTransportSocket.cpp b/Tests/LibIPC/TestTransportSocket.cppindex 71ed17b7622..f9385975fcd 100644--- a/Tests/LibIPC/TestTransportSocket.cpp+++ b/Tests/LibIPC/TestTransportSocket.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/Array.h>#include <AK/Atomic.h>#include <AK/CharacterTypes.h>@@ -487,12 +488,60 @@ TEST_CASE(message_with_the_maximum_number_of_descriptors_arrives_whole_and_in_orEXPECT(!observed_shutdown);}-static bool reader_disconnects_after_receiving(ReadonlyBytes bytes)+TEST_CASE(message_with_the_maximum_number_of_descriptors_and_a_payload_in_shared_memory_arrives_whole)+{+ raise_descriptor_limit();+ IGNORE_USE_IN_ESCAPING_LAMBDA TransportPair pair;++ Vector<IPC::Attachment> attachments;+ attachments.append(IPC::Attachment::from_fd(pipe_holding('F')));+ for (size_t i = 2; i < IPC::MAX_MESSAGE_FD_COUNT; ++i)+ attachments.append(IPC::Attachment::from_fd(MUST(Core::System::open("/dev/null"sv, O_RDONLY))));+ attachments.append(IPC::Attachment::from_fd(pipe_holding('L')));+ static constexpr size_t payload_size = IPC::TransportSocket::MAX_INLINE_PAYLOAD_SIZE + 1;+ IPC::MessageDataType payload;+ payload.resize(payload_size);+ payload.span().fill('A');+ MUST(pair.sender->post_message(move(payload), attachments));+ (void)pair.post_with_descriptor('B');++ IGNORE_USE_IN_ESCAPING_LAMBDA Vector<u8> received_tags;+ IGNORE_USE_IN_ESCAPING_LAMBDA bool arrived_whole = true;+ IGNORE_USE_IN_ESCAPING_LAMBDA bool observed_shutdown = false;+ pair.receiver->set_up_read_hook([&] {+ auto should_shutdown = pair.receiver->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ auto bytes = message.bytes.bytes();+ received_tags.append(bytes[0]);+ Vector<int> fds;+ while (!message.attachments.is_empty())+ fds.append(message.attachments.dequeue().to_fd());+ if (bytes[0] == 'A') {+ if (bytes.size() != payload_size || any_of(bytes, [](u8 byte) { return byte != 'A'; }))+ arrived_whole = false;+ if (fds.size() != IPC::MAX_MESSAGE_FD_COUNT || byte_in_descriptor(fds.first()) != 'F' || byte_in_descriptor(fds.last()) != 'L')+ arrived_whole = false;+ } else if (fds.size() != 1 || byte_in_descriptor(fds.first()) != 'B') {+ arrived_whole = false;+ }+ for (auto fd : fds)+ MUST(Core::System::close(fd));+ });+ if (should_shutdown == IPC::TransportSocket::ShouldShutdown::Yes)+ observed_shutdown = true;+ });++ spin_until(pair.loop, [&] { return received_tags.size() == 2 || observed_shutdown; }, 10000_ms);+ EXPECT(received_tags == Vector<u8>({ 'A', 'B' }));+ EXPECT(arrived_whole);+ EXPECT(!observed_shutdown);+}++static bool reader_disconnects_after_receiving(ReadonlyBytes bytes, Vector<int, 1> descriptors = {}){Core::EventLoop loop;int fds[2] {};MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fds));- ScopeGuard close_peer = [&] { MUST(Core::System::close(fds[1])); };+ auto peer = MUST(Core::LocalSocket::adopt_fd(fds[1]));auto reader_socket = MUST(Core::LocalSocket::adopt_fd(fds[0]));MUST(reader_socket->set_blocking(false));IGNORE_USE_IN_ESCAPING_LAMBDA IPC::TransportSocket transport(move(reader_socket));@@ -502,7 +551,7 @@ static bool reader_disconnects_after_receiving(ReadonlyBytes bytes)if (transport.read_as_many_messages_as_possible_without_blocking([](auto&&) { }) == IPC::TransportSocket::ShouldShutdown::Yes)observed_shutdown = true;});- EXPECT_EQ(MUST(Core::System::write(fds[1], bytes)), bytes.size());+ EXPECT_EQ(MUST(peer->send_message(bytes, 0, move(descriptors))), bytes.size());spin_until(loop, [&] {return observed_shutdown;});@@ -529,6 +578,38 @@ TEST_CASE(attachments_frame_with_a_payload_disconnects_the_peer)EXPECT(reader_disconnects_after_receiving({ &header, sizeof(header) }));}+TEST_CASE(inline_payload_larger_than_the_inline_limit_disconnects_the_peer)+{+ IPC::SocketMessageHeader header {+ .type = IPC::SocketMessageHeader::Type::Payload,+ .payload_size = IPC::TransportSocket::MAX_INLINE_PAYLOAD_SIZE + 1,+ .fd_count = 0,+ };+ EXPECT(reader_disconnects_after_receiving({ &header, sizeof(header) }));+}++TEST_CASE(shared_memory_payload_without_a_descriptor_disconnects_the_peer)+{+ IPC::SocketMessageHeader header {+ .type = IPC::SocketMessageHeader::Type::SharedMemoryPayload,+ .payload_size = 1,+ .fd_count = 0,+ };+ EXPECT(reader_disconnects_after_receiving({ &header, sizeof(header) }));+}++TEST_CASE(shared_memory_smaller_than_its_payload_disconnects_the_peer)+{+ auto shared_memory = MUST(Core::System::anon_create(4 * KiB, O_CLOEXEC));+ ScopeGuard close_shared_memory = [&] { MUST(Core::System::close(shared_memory)); };+ IPC::SocketMessageHeader header {+ .type = IPC::SocketMessageHeader::Type::SharedMemoryPayload,+ .payload_size = 1 * MiB,+ .fd_count = 1,+ };+ EXPECT(reader_disconnects_after_receiving({ &header, sizeof(header) }, { shared_memory }));+}+// The IO thread reads a bounded amount per round. A backlog larger than that must still arrive in full and in order,// including the part that is left for the drain that runs once the peer has hung up.TEST_CASE(a_backlog_larger_than_one_read_round_is_delivered_after_peer_hangup)diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.txtnew file mode 100644index 00000000000..e4cc68d39ce--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.txt@@ -0,0 +1,4 @@+byteLength: 83886080+first byte: 1, last byte: 2+WebContent#0+ iframe#0: remote WebContent#1diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.htmlnew file mode 100644index 00000000000..fca7de0f4ad--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/isolated-iframe-posts-a-message-larger-than-64-mib-to-parent.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script>+ promiseTest(async () => {+ const httpServer = httpTestServer();++ const childUrl = new URL(+ await httpServer.createEcho("GET", "/oop-post-large-message-child", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>+ const bytes = new Uint8Array(80 * 1024 * 1024);+ bytes[0] = 1;+ bytes[bytes.length - 1] = 2;+ parent.postMessage(bytes, "*");+ <\/script>`,+ })+ );+ childUrl.hostname = uniqueLocalhostHostname("oop-post-large-message-child");++ const received = new Promise(resolve => window.addEventListener("message", resolve, { once: true }));+ const iframe = document.createElement("iframe");+ iframe.src = childUrl;+ document.body.appendChild(iframe);++ const event = await received;+ println(`byteLength: ${event.data.byteLength}`);+ println(`first byte: ${event.data[0]}, last byte: ${event.data[event.data.length - 1]}`);+ println(internals.dumpSiteIsolationProcessTree().trimEnd());+ });+</script>