Truly independent web browser
LibIPC: Release the Mach ports of a child that exits before taking them
Andreas Kling3f779a50a941
diff --git a/Libraries/LibIPC/TransportBootstrapMach.cpp b/Libraries/LibIPC/TransportBootstrapMach.cppindex dac93c90a28..d966ca54c03 100644--- a/Libraries/LibIPC/TransportBootstrapMach.cpp+++ b/Libraries/LibIPC/TransportBootstrapMach.cpp@@ -13,8 +13,12 @@#include <LibIPC/MachBootstrapMessages.h>#include <LibIPC/TransportBootstrapMach.h>#include <LibIPC/TransportMachPort.h>+#include <LibThreading/Thread.h>+#include <errno.h>#include <mach/mach.h>+#include <sys/event.h>+#include <unistd.h>namespace IPC {@@ -125,16 +129,107 @@ ErrorOr<TransportBootstrapMachPorts> TransportBootstrapMachServer::create_on_dem};}+// What wakes the child exit watcher when the server goes away.+static constexpr uintptr_t stop_watching_event_identifier = 1;++TransportBootstrapMachServer::TransportBootstrapMachServer()+ : m_child_exit_queue(kqueue())+{+ if (m_child_exit_queue < 0) {+ dbgln("Unable to create the queue that reports children that exit before they take their transport: {}", Error::from_errno(errno));+ return;+ }++ struct kevent change {};+ EV_SET(&change, stop_watching_event_identifier, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, nullptr);+ VERIFY(kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) == 0);+}++TransportBootstrapMachServer::~TransportBootstrapMachServer()+{+ if (m_child_exit_watcher) {+ struct kevent change {};+ EV_SET(&change, stop_watching_event_identifier, EVFILT_USER, 0, NOTE_TRIGGER, 0, nullptr);+ VERIFY(kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) == 0);+ (void)m_child_exit_watcher->join();+ }+ if (m_child_exit_queue >= 0)+ (void)::close(m_child_exit_queue);+}+void TransportBootstrapMachServer::register_child_transport(pid_t pid, TransportBootstrapMachPorts ports){- VERIFY(!m_child_transports.contains(pid));- m_child_transports.set(pid, move(ports));+ // NB: Ports that are still registered for this PID are those of an earlier child that exited before it took them,+ // and whose exit has not been handled yet. They are replaced.+ auto serial = m_next_child_transport_serial++;++ if (m_child_exit_queue >= 0) {+ if (!m_child_exit_watcher) {+ m_child_exit_watcher = Threading::Thread::construct("ChildExitWatch"sv, [this]() -> intptr_t {+ child_exit_watcher_loop();+ return 0;+ });+ m_child_exit_watcher->start();+ }++ // NB: The serial tells the watcher which registration an exit belongs to, as a later child can get the PID of+ // an earlier one.+ struct kevent change {};+ EV_SET(&change, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, reinterpret_cast<void*>(static_cast<uintptr_t>(serial)));+ if (kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr) < 0) {+ // The child is gone already, so it never takes these ports. Letting go of them tells the other end.+ if (errno == ESRCH)+ return;+ dbgln("Unable to watch for the exit of child {}: {}", pid, Error::from_errno(errno));+ }+ }++ m_child_transports.set(pid, ChildTransport { move(ports), serial });+}++void TransportBootstrapMachServer::stop_watching_for_child_exit(pid_t pid)+{+ if (m_child_exit_queue < 0)+ return;+ // NB: This fails for a child whose exit was reported already, which is fine.+ struct kevent change {};+ EV_SET(&change, pid, EVFILT_PROC, EV_DELETE, 0, 0, nullptr);+ (void)kevent(m_child_exit_queue, &change, 1, nullptr, 0, nullptr);}void TransportBootstrapMachServer::unregister_child_transport(pid_t pid){MutexLocker locker(m_child_registration_mutex);- m_child_transports.remove(pid);+ if (m_child_transports.remove(pid))+ stop_watching_for_child_exit(pid);+}++void TransportBootstrapMachServer::child_exit_watcher_loop()+{+ for (;;) {+ struct kevent event {};+ auto count = kevent(m_child_exit_queue, nullptr, 0, &event, 1, nullptr);+ if (count < 0) {+ if (errno == EINTR)+ continue;+ dbgln("Unable to wait for children to exit: {}", Error::from_errno(errno));+ return;+ }+ if (count == 0)+ continue;+ if (event.filter == EVFILT_USER)+ return;+ if (event.filter != EVFILT_PROC)+ continue;++ auto pid = static_cast<pid_t>(event.ident);+ auto serial = static_cast<u64>(reinterpret_cast<uintptr_t>(event.udata));++ MutexLocker locker(m_child_registration_mutex);+ auto child_transport = m_child_transports.get(pid);+ if (child_transport.has_value() && child_transport->serial == serial)+ m_child_transports.remove(pid);+ }}ErrorOr<TransportBootstrapMachServer::BootstrapRequestResult> TransportBootstrapMachServer::handle_bootstrap_request(pid_t pid, Core::MachPort reply_port)@@ -142,7 +237,10 @@ ErrorOr<TransportBootstrapMachServer::BootstrapRequestResult> TransportBootstrapOptional<TransportBootstrapMachPorts> child_transport;{MutexLocker locker(m_child_registration_mutex);- child_transport = m_child_transports.take(pid);+ if (auto registered = m_child_transports.take(pid); registered.has_value()) {+ stop_watching_for_child_exit(pid);+ child_transport = move(registered->ports);+ }}if (child_transport.has_value()) {diff --git a/Libraries/LibIPC/TransportBootstrapMach.h b/Libraries/LibIPC/TransportBootstrapMach.hindex aee421494bf..c65f2f5a317 100644--- a/Libraries/LibIPC/TransportBootstrapMach.h+++ b/Libraries/LibIPC/TransportBootstrapMach.h@@ -16,7 +16,9 @@#endif#include <AK/Mutex.h>+#include <AK/RefPtr.h>#include <LibCore/MachPort.h>+#include <LibThreading/Forward.h>namespace IPC {@@ -32,7 +34,8 @@ class TransportBootstrapMachServer {AK_MAKE_NONCOPYABLE(TransportBootstrapMachServer);public:- TransportBootstrapMachServer() = default;+ TransportBootstrapMachServer();+ ~TransportBootstrapMachServer();struct ChildTransportHandled {};@@ -46,6 +49,9 @@ public:Mutex& child_registration_lock() { return m_child_registration_mutex; }// Must be called while holding child_registration_lock().+ // NB: Until the child asks for its ports, we hold them ourselves, so nothing would tell the other end of the+ // transport that the child is gone. A child that exits before it asks is unregistered from a thread of our+ // own, so that this also happens while the thread that spawned the child waits for the child to answer.void register_child_transport(pid_t, TransportBootstrapMachPorts);// For a child that was ended before it asked for its transport.void unregister_child_transport(pid_t);@@ -55,8 +61,20 @@ private:static ErrorOr<void> send_transport_ports_to_child(Core::MachPort reply_port, TransportBootstrapMachPorts ports);static ErrorOr<TransportBootstrapMachPorts> create_on_demand_local_transport(Core::MachPort reply_port);+ struct ChildTransport {+ TransportBootstrapMachPorts ports;+ u64 serial { 0 };+ };++ void stop_watching_for_child_exit(pid_t);+ void child_exit_watcher_loop();+Mutex m_child_registration_mutex;- HashMap<pid_t, TransportBootstrapMachPorts> m_child_transports;+ HashMap<pid_t, ChildTransport> m_child_transports;+ u64 m_next_child_transport_serial { 1 };++ int m_child_exit_queue { -1 };+ RefPtr<Threading::Thread> m_child_exit_watcher;};}diff --git a/Tests/LibIPC/TestMachBootstrap.cpp b/Tests/LibIPC/TestMachBootstrap.cppindex 6f98f5a5acd..4ef4b572347 100644--- a/Tests/LibIPC/TestMachBootstrap.cpp+++ b/Tests/LibIPC/TestMachBootstrap.cpp@@ -7,6 +7,7 @@#include <AK/ByteString.h>#include <AK/Mutex.h>#include <AK/Random.h>+#include <AK/Time.h>#include <LibCore/MachPort.h>#include <LibIPC/MachBootstrapListener.h>#include <LibIPC/MachBootstrapMessages.h>@@ -14,6 +15,8 @@#include <LibTest/TestCase.h>#include <mach/mach.h>#include <mach/mach_vm.h>+#include <spawn.h>+#include <sys/wait.h>#include <unistd.h>static ByteString server_name()@@ -203,3 +206,78 @@ TEST_CASE(bootstrap_reports_a_missing_reply_port)EXPECT_EQ(mach_port_type(mach_task_self(), send_port, &type), KERN_SUCCESS);EXPECT_EQ(type, static_cast<mach_port_type_t>(MACH_PORT_TYPE_RECEIVE));}++enum class RegisterChild {+ WhileItRuns,+ AfterItExited,+};++// Blocks until the server lets go of the ports of a child that exits before it asks for them.+static void expect_ports_of_exited_child_to_be_released(RegisterChild register_child)+{+ auto local_receive_right = TRY_OR_FAIL(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ auto child_send_right = TRY_OR_FAIL(local_receive_right.insert_right(Core::MachPort::MessageRight::MakeSend));+ auto child_receive_right = TRY_OR_FAIL(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ auto child_receive_port = child_receive_right.port();++ // NB: This is how a transport learns that its peer is gone.+ auto notification_receive_right = TRY_OR_FAIL(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ mach_port_t previous = MACH_PORT_NULL;+ VERIFY(mach_port_request_notification(mach_task_self(), local_receive_right.port(), MACH_NOTIFY_NO_SENDERS, 1, notification_receive_right.port(), MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous) == KERN_SUCCESS);++ IPC::TransportBootstrapMachServer server;+ pid_t pid = -1;+ {+ MutexLocker locker(server.child_registration_lock());+ // NB: The child runs until its input ends, which is when we close our end of the pipe.+ int input[2] = {};+ VERIFY(pipe(input) == 0);+ posix_spawn_file_actions_t file_actions;+ VERIFY(posix_spawn_file_actions_init(&file_actions) == 0);+ VERIFY(posix_spawn_file_actions_adddup2(&file_actions, input[0], STDIN_FILENO) == 0);+ VERIFY(posix_spawn_file_actions_addclose(&file_actions, input[1]) == 0);+ char const* arguments[] = { "/bin/cat", nullptr };+ VERIFY(posix_spawn(&pid, arguments[0], &file_actions, nullptr, const_cast<char**>(arguments), nullptr) == 0);+ VERIFY(posix_spawn_file_actions_destroy(&file_actions) == 0);+ VERIFY(close(input[0]) == 0);+ if (register_child == RegisterChild::AfterItExited) {+ VERIFY(close(input[1]) == 0);+ siginfo_t info {};+ while (waitid(P_PID, pid, &info, WEXITED | WNOWAIT) < 0)+ VERIFY(errno == EINTR);+ }+ server.register_child_transport(pid, { move(child_receive_right), move(child_send_right) });+ if (register_child == RegisterChild::WhileItRuns)+ VERIFY(close(input[1]) == 0);+ }++ struct {+ mach_msg_header_t header;+ u8 body[64];+ } notification {};+ // NB: The limit only keeps a server that holds on to the ports from stopping the test run.+ static constexpr mach_msg_timeout_t limit_in_milliseconds = 60'000;+ EXPECT_EQ(mach_msg(¬ification.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(notification), notification_receive_right.port(), limit_in_milliseconds, MACH_PORT_NULL), KERN_SUCCESS);+ EXPECT_EQ(notification.header.msgh_id, MACH_NOTIFY_NO_SENDERS);++ // The server lets go of the send right first, so the receive right may still be there for a moment.+ mach_port_type_t type = 0;+ auto deadline = MonotonicTime::now() + AK::Duration::from_milliseconds(limit_in_milliseconds);+ while (mach_port_type(mach_task_self(), child_receive_port, &type) != KERN_INVALID_NAME && MonotonicTime::now() < deadline)+ usleep(1'000);+ EXPECT_EQ(mach_port_type(mach_task_self(), child_receive_port, &type), KERN_INVALID_NAME);++ int status = 0;+ while (waitpid(pid, &status, 0) < 0)+ VERIFY(errno == EINTR);+}++TEST_CASE(ports_of_a_child_that_exits_before_taking_them_are_released)+{+ expect_ports_of_exited_child_to_be_released(RegisterChild::WhileItRuns);+}++TEST_CASE(ports_of_a_child_that_exited_before_registration_are_released)+{+ expect_ports_of_exited_child_to_be_released(RegisterChild::AfterItExited);+}diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex ba0b21fc7f4..c73d2adb1b3 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -41,11 +41,9 @@# include <LibIPC/MachBootstrapListener.h># include <LibIPC/TransportBootstrapMach.h># include <LibIPC/TransportMachPort.h>-# include <LibThreading/Thread.h># include <LibWebView/MediaSessionPlatformBackendMacOS.h># include <LibWebView/NotificationBackendMacOS.h># include <mach/mach.h>-# include <sys/wait.h>#elif defined(AK_OS_LINUX) || defined(AK_OS_FREEBSD)# include <LibWebView/NotificationBackendFreedesktop.h>#endif@@ -746,7 +744,7 @@ ErrorOr<NonnullOwnPtr<Application>> Application::create(Main::Arguments const& a#ifdef LADYBIRD_HUB_IN_OWN_PROCESS# if defined(AK_OS_MACOS)-// What the Hub gets its end of the connection from. The thread that watches for the Hub to end can outlive connecting.+// What the Hub gets its end of the connection from. The thread that answers the Hub can outlive connecting.struct HubBootstrap : public AtomicRefCounted<HubBootstrap> {IPC::TransportBootstrapMachServer server;};@@ -863,18 +861,6 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)}auto process = spawned_process.release_value();- // NB: Until the Hub takes its ports, we hold them ourselves, so nothing would tell us of a Hub that ended before- // that. Letting go of them then closes the connection, as a socket does when its peer ends.- auto hub_exit_watcher = Threading::Thread::construct("HubExitWatcher"sv, [hub_bootstrap, pid = process.pid()]() -> intptr_t {- siginfo_t info {};- while (waitid(P_PID, pid, &info, WEXITED | WNOWAIT) < 0 && errno == EINTR)- ;- hub_bootstrap->server.unregister_child_transport(pid);- return 0;- });- hub_exit_watcher->start();- hub_exit_watcher->detach();-auto transport = make<IPC::Transport>(move(port_a_recv), move(port_b_send));# elseint socket_fds[2] {};