Skip to content

Truly independent web browser

LibWebView+UI/Qt: Track helper processes by child ID

Andreas Klingc43221df387c
diff --git a/Libraries/LibCore/Process.cpp b/Libraries/LibCore/Process.cpp
index cdfd62095f9..32e515c820f 100644
--- a/Libraries/LibCore/Process.cpp
+++ b/Libraries/LibCore/Process.cpp
@@ -104,12 +104,6 @@ Process::~Process()
{
}
-Process Process::current()
-{
- auto p = Process { getpid() };
- return p;
-}
-
#if defined(AK_OS_LINUX)
static Optional<int> run_file_actions_in_child(Vector<ProcessSpawnOptions::FileActionType> const& file_actions)
{
diff --git a/Libraries/LibCore/Process.h b/Libraries/LibCore/Process.h
index dea77d7ac5e..2c1c230b5f2 100644
--- a/Libraries/LibCore/Process.h
+++ b/Libraries/LibCore/Process.h
@@ -63,7 +63,6 @@ public:
~Process();
static ErrorOr<Process> spawn(ProcessSpawnOptions const& options);
- static Process current();
static ErrorOr<Process> spawn(StringView path, ReadonlySpan<ByteString> arguments);
static ErrorOr<Process> spawn(StringView path, ReadonlySpan<StringView> arguments);
diff --git a/Libraries/LibCore/ProcessWindows.cpp b/Libraries/LibCore/ProcessWindows.cpp
index dd217242525..95c9aac128f 100644
--- a/Libraries/LibCore/ProcessWindows.cpp
+++ b/Libraries/LibCore/ProcessWindows.cpp
@@ -38,11 +38,6 @@ Process::~Process()
CloseHandle(m_handle);
}
-Process Process::current()
-{
- return GetCurrentProcess();
-}
-
static ErrorOr<HANDLE> duplicate_inheritable_handle(HANDLE handle)
{
HANDLE duplicate = nullptr;
diff --git a/Libraries/LibIPC/TransportBootstrapMach.cpp b/Libraries/LibIPC/TransportBootstrapMach.cpp
index c49dd410876..dac93c90a28 100644
--- a/Libraries/LibIPC/TransportBootstrapMach.cpp
+++ b/Libraries/LibIPC/TransportBootstrapMach.cpp
@@ -131,6 +131,12 @@ void TransportBootstrapMachServer::register_child_transport(pid_t pid, Transport
m_child_transports.set(pid, move(ports));
}
+void TransportBootstrapMachServer::unregister_child_transport(pid_t pid)
+{
+ MutexLocker locker(m_child_registration_mutex);
+ m_child_transports.remove(pid);
+}
+
ErrorOr<TransportBootstrapMachServer::BootstrapRequestResult> TransportBootstrapMachServer::handle_bootstrap_request(pid_t pid, Core::MachPort reply_port)
{
Optional<TransportBootstrapMachPorts> child_transport;
diff --git a/Libraries/LibIPC/TransportBootstrapMach.h b/Libraries/LibIPC/TransportBootstrapMach.h
index c3158871cae..aee421494bf 100644
--- a/Libraries/LibIPC/TransportBootstrapMach.h
+++ b/Libraries/LibIPC/TransportBootstrapMach.h
@@ -47,6 +47,8 @@ public:
// Must be called while holding child_registration_lock().
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);
ErrorOr<BootstrapRequestResult> handle_bootstrap_request(pid_t, Core::MachPort reply_port);
private:
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 42b5a272429..e5b5cf16b5b 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -69,7 +69,6 @@ set(SOURCES
WebView/DOMNodeProperties.cpp
WebView/Geolocation.cpp
WebView/Mutation.cpp
- WebView/ProcessHandle.cpp
WebView/SiteIsolation.cpp
WebView/Utilities.cpp
)
diff --git a/Libraries/LibWebCommon/Forward.h b/Libraries/LibWebCommon/Forward.h
index 54fe66a70d4..d4ccab3475b 100644
--- a/Libraries/LibWebCommon/Forward.h
+++ b/Libraries/LibWebCommon/Forward.h
@@ -135,7 +135,6 @@ struct DebuggerValue;
struct DictionaryLookup;
struct DictionaryLookupTextStyle;
struct Mutation;
-struct ProcessHandle;
}
diff --git a/Libraries/LibWebCommon/WebView/ProcessHandle.cpp b/Libraries/LibWebCommon/WebView/ProcessHandle.cpp
deleted file mode 100644
index 60a802871e2..00000000000
--- a/Libraries/LibWebCommon/WebView/ProcessHandle.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibIPC/Decoder.h>
-#include <LibIPC/Encoder.h>
-#include <LibWebCommon/WebView/ProcessHandle.h>
-
-template<>
-ErrorOr<void> IPC::encode(IPC::Encoder& encoder, WebView::ProcessHandle const& handle)
-{
- TRY(encoder.encode(handle.pid));
- return {};
-}
-
-template<>
-ErrorOr<WebView::ProcessHandle> IPC::decode(IPC::Decoder& decoder)
-{
- auto pid = TRY(decoder.decode<pid_t>());
- return WebView::ProcessHandle { pid };
-}
diff --git a/Libraries/LibWebCommon/WebView/ProcessHandle.h b/Libraries/LibWebCommon/WebView/ProcessHandle.h
deleted file mode 100644
index fcc521ef6e4..00000000000
--- a/Libraries/LibWebCommon/WebView/ProcessHandle.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Types.h>
-#include <LibIPC/Forward.h>
-#include <LibWebCommon/Export.h>
-
-namespace WebView {
-
-constexpr bool should_terminate_pid(pid_t pid)
-{
- return pid > 0;
-}
-
-struct ProcessHandle {
- // FIXME: Use mach_port_t on macOS/Hurd and HANDLE on Windows.
- pid_t pid { -1 };
-};
-
-}
-
-template<>
-WEBCOMMON_API ErrorOr<void> IPC::encode(IPC::Encoder&, WebView::ProcessHandle const&);
-
-template<>
-WEBCOMMON_API ErrorOr<WebView::ProcessHandle> IPC::decode(IPC::Decoder&);
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index d04d0862c63..a57449e9eeb 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -1583,7 +1583,7 @@ void Application::launch_spare_web_content_process()
}
m_spare_web_content_process = web_content_client.release_value();
- if (auto process = find_process(m_spare_web_content_process->pid()); process.has_value())
+ if (auto process = m_process_manager->find_child(m_spare_web_content_process->child_id()); process.has_value())
process->set_title("(spare)"_utf16);
});
}
@@ -1964,9 +1964,9 @@ void Application::configure_request_server_control_client(Requests::RequestContr
TabPerformanceMonitor::configure(control_client);
}
-void Application::set_image_decoder_exit_handler(pid_t pid, Function<void()> handler)
+void Application::set_image_decoder_exit_handler(u64 child_id, Function<void()> handler)
{
- m_image_decoder_exit_handlers.set(pid, move(handler));
+ m_image_decoder_exit_handlers.set(child_id, move(handler));
}
#if defined(HAVE_WASM_COMPILER_SERVICE)
@@ -2135,9 +2135,9 @@ Core::EventLoop& Application::create_platform_event_loop()
return Core::EventLoop::initialize_for_current_thread();
}
-void Application::add_child_process(WebView::Process&& process)
+ChildIdentity Application::add_child_process(WebView::Process&& process)
{
- m_process_manager->add_process(move(process));
+ return m_process_manager->add_process(move(process));
}
#if defined(AK_OS_MACH)
@@ -2177,7 +2177,7 @@ void Application::process_did_exit(Process&& process, Optional<int>)
}
break;
case ProcessType::ImageDecoder:
- if (auto handler = m_image_decoder_exit_handlers.take(process.pid()); handler.has_value())
+ if (auto handler = m_image_decoder_exit_handlers.take(process.child_id()); handler.has_value())
(*handler)();
break;
case ProcessType::MediaServer:
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 116f57d1b3f..99d4c01fcc7 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -215,8 +215,8 @@ public:
static IPC::HandleBrokerServer& handle_broker_server() { return *the().m_handle_broker_server; }
#endif
- // Runs the handler when the ImageDecoder with the given pid exits.
- void set_image_decoder_exit_handler(pid_t, Function<void()>);
+ // Runs the handler when the ImageDecoder with the given child ID exits.
+ void set_image_decoder_exit_handler(u64 child_id, Function<void()>);
#if defined(AK_OS_MACOS)
static IPC::TransportBootstrapMachServer& transport_bootstrap_server() { return the().m_transport_bootstrap_server; }
void set_browser_process_transport_handler(Function<void(NonnullOwnPtr<IPC::Transport>)> handler);
@@ -288,7 +288,7 @@ public:
Main::Arguments const& command_line_arguments() const { return m_arguments; }
- void add_child_process(Process&&);
+ ChildIdentity add_child_process(Process&&);
// FIXME: Should these methods be part of Application, instead of deferring to ProcessManager?
#if defined(AK_OS_MACH)
@@ -625,7 +625,7 @@ private:
WebDriverSessionConfig m_webdriver_session_config;
OwnPtr<RequestServerManager> m_request_server_manager;
- HashMap<pid_t, Function<void()>> m_image_decoder_exit_handlers;
+ HashMap<u64, Function<void()>> m_image_decoder_exit_handlers;
#if defined(HAVE_WASM_COMPILER_SERVICE)
RefPtr<WasmCompilerClient::Client> m_wasm_compiler_client;
#endif
diff --git a/Libraries/LibWebView/ChildIdentity.h b/Libraries/LibWebView/ChildIdentity.h
new file mode 100644
index 00000000000..bd42cbf498b
--- /dev/null
+++ b/Libraries/LibWebView/ChildIdentity.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Types.h>
+
+namespace WebView {
+
+// NB: A child ID names one helper process for as long as the browser runs. Unlike a PID, it is never reused for a
+// later process. Child ID zero denotes the browser itself.
+struct ChildIdentity {
+ u64 child_id { 0 };
+ pid_t pid { -1 };
+};
+
+}
diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cpp
index 1e2c00a9ae0..824b847fc49 100644
--- a/Libraries/LibWebView/HelperProcess.cpp
+++ b/Libraries/LibWebView/HelperProcess.cpp
@@ -166,9 +166,10 @@ static ErrorOr<CPUProfiler> launch_cpu_profiler(StringView server_name, pid_t pi
#endif
}
-// Spawns the helper with the given function, which returns the Process to keep track of, and returns the helper's pid.
+// Spawns the helper with the given function, which returns the Process to keep track of, and returns the helper's
+// identity.
template<typename SpawnFunction>
-static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteString> arguments, SpawnFunction&& spawn)
+static ErrorOr<ChildIdentity> launch_helper_process(StringView server_name, Vector<ByteString> arguments, SpawnFunction&& spawn)
{
auto process_type = WebView::process_type_from_name(server_name);
auto const& browser_options = WebView::Application::browser_options();
@@ -248,7 +249,6 @@ static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteS
if (!result.is_error()) {
auto process = result.release_value();
- auto pid = process.pid();
if (crash_report)
process.set_crash_report(crash_report.release_nonnull());
#if defined(AK_OS_LINUX)
@@ -261,7 +261,7 @@ static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteS
WebView::Application::the().set_cpu_profiler_process(move(profiler.process), move(profiler.control_socket));
}
- WebView::Application::the().add_child_process(move(process));
+ auto identity = WebView::Application::the().add_child_process(move(process));
if (browser_options.profile_helper_process == process_type && browser_options.profile_tool == ProfileTool::Callgrind) {
dbgln();
@@ -270,7 +270,7 @@ static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteS
dbgln();
}
- return pid;
+ return identity;
}
if (i == candidate_server_paths.size() - 1) {
@@ -289,15 +289,14 @@ static ErrorOr<NonnullRefPtr<ClientType>> launch_server_process(
ClientArguments&&... client_arguments)
{
RefPtr<ClientType> client;
- TRY(launch_helper_process(server_name, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {
+ auto identity = TRY(launch_helper_process(server_name, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {
auto [process, new_client] = TRY(WebView::Process::spawn<ClientType>(WebView::process_type_from_name(server_name), options, capture_output, forward<ClientArguments>(client_arguments)...));
-
- if constexpr (requires { new_client->set_pid(pid_t {}); })
- new_client->set_pid(process.pid());
-
client = move(new_client);
return move(process);
}));
+
+ if constexpr (requires { client->set_child_identity(ChildIdentity {}); })
+ client->set_child_identity(identity);
return client.release_nonnull();
}
@@ -389,26 +388,26 @@ ErrorOr<ImageDecoderConnection> launch_image_decoder_process()
// The decoder parses untrusted images for one client, so it must not see the images of any other. The Browser
// does not talk to it, and hands its end of the transport to the client.
OwnPtr<IPC::Transport> transport;
- auto pid = TRY(launch_helper_process("ImageDecoder"sv, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {
+ auto identity = TRY(launch_helper_process("ImageDecoder"sv, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {
auto [process, new_transport] = TRY(WebView::Process::spawn_with_transport(ProcessType::ImageDecoder, options, capture_output));
transport = move(new_transport);
return move(process);
}));
- return ImageDecoderConnection { TRY(transport->release_for_transfer()), pid };
+ return ImageDecoderConnection { TRY(transport->release_for_transfer()), identity.child_id };
}
template<typename ClientType>
static void connect_client_to_image_decoder(ClientType& client, ImageDecoderConnection decoder)
{
- auto process = Application::process_manager().find_process(decoder.pid);
+ auto process = Application::process_manager().find_child(decoder.child_id);
VERIFY(process.has_value());
- process->set_owner_pid(client.pid());
+ process->set_owner_child_id(client.child_id());
client.async_connect_to_image_decoder(decoder.handle);
// A decoder exits by itself once its client is gone. One that dies before then is replaced, so a crash costs the
// client the images it was decoding at the time rather than every image after it.
- Application::the().set_image_decoder_exit_handler(decoder.pid, [weak_client = client.template make_weak_ptr<ClientType>()] {
+ Application::the().set_image_decoder_exit_handler(decoder.child_id, [weak_client = client.template make_weak_ptr<ClientType>()] {
auto client = weak_client.strong_ref();
if (!client || !client->is_open())
return;
diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.h
index 92933390cb7..499a823a84f 100644
--- a/Libraries/LibWebView/HelperProcess.h
+++ b/Libraries/LibWebView/HelperProcess.h
@@ -43,7 +43,7 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WasmCompilerClient::Client>> launch_wasm_compi
struct ImageDecoderConnection {
IPC::TransportHandle handle;
- pid_t pid { -1 };
+ u64 child_id { 0 };
};
// Launches an ImageDecoder that serves a single renderer or worker, which talks to it over the returned handle.
diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cpp
index 3d634d70b17..c7296e173ce 100644
--- a/Libraries/LibWebView/Process.cpp
+++ b/Libraries/LibWebView/Process.cpp
@@ -6,6 +6,7 @@
#include <AK/AnyOf.h>
#include <AK/Array.h>
+#include <AK/ScopeGuard.h>
#include <LibCore/Environment.h>
#include <LibCore/File.h>
#include <LibCore/Process.h>
@@ -27,7 +28,6 @@
#endif
#if defined(AK_OS_WINDOWS)
-# include <AK/ScopeGuard.h>
# include <AK/Windows.h>
# include <LibIPC/HandleBrokerServer.h>
# include <LibWebView/Application.h>
@@ -36,12 +36,29 @@
namespace WebView {
Process::Process(ProcessType type, RefPtr<IPC::ConnectionBase> connection, Core::Process process)
- : m_process(move(process))
+ : m_pid(process.pid())
+ , m_process(move(process))
, m_type(type)
, m_connection(move(connection))
{
}
+Process::Process(ProcessType type, pid_t pid)
+ : m_pid(pid)
+ , m_type(type)
+{
+}
+
+Process Process::for_browser()
+{
+ return Process { ProcessType::Browser, Core::System::getpid() };
+}
+
+void Process::did_register(Badge<ProcessManager>, u64 child_id)
+{
+ m_child_id = child_id;
+}
+
void Process::save_crash_report(Optional<int> exit_status)
{
if (m_crash_report && exit_status.has_value()) {
@@ -55,6 +72,14 @@ void Process::save_crash_report(Optional<int> exit_status)
Process::~Process()
{
+ // NB: A helper that never made it into the ProcessManager would run on untracked, so it is ended instead.
+ if (m_process.has_value() && m_child_id == 0) {
+ (void)Core::Process::terminate_process(m_pid, Core::Process::TerminationMode::Forceful);
+#if defined(AK_OS_MACOS)
+ Application::transport_bootstrap_server().unregister_child_transport(m_pid);
+#endif
+ }
+
// shutdown() can release the connection's last owner while dispatching die().
if (auto connection = m_connection.strong_ref())
connection->shutdown();
@@ -208,6 +233,17 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = stderr_pipe[1], .fd = STDERR_FILENO });
}
+ // NB: A helper that we fail to connect to is ended rather than left running untracked.
+ Optional<Core::Process> process;
+ ArmedScopeGuard terminate_process_on_failure { [&] {
+ if (!process.has_value())
+ return;
+ (void)Core::Process::terminate_process(process->pid(), Core::Process::TerminationMode::Forceful);
+#if defined(AK_OS_MACOS)
+ Application::transport_bootstrap_server().unregister_child_transport(process->pid());
+#endif
+ } };
+
#if defined(AK_OS_MACOS)
auto port_a_recv = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));
auto port_a_send = TRY(port_a_recv.insert_right(Core::MachPort::MessageRight::MakeSend));
@@ -218,10 +254,10 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
IPC::TransportMachPort::raise_receive_queue_limit(port_b_recv);
MutexLocker child_registration_locker(Application::transport_bootstrap_server().child_registration_lock());
- auto process = TRY(Core::Process::spawn(spawn_options));
- watch_with_process_reaper(process.pid());
+ process = TRY(Core::Process::spawn(spawn_options));
+ watch_with_process_reaper(process->pid());
- Application::transport_bootstrap_server().register_child_transport(process.pid(), IPC::TransportBootstrapMachPorts { move(port_b_recv), move(port_a_send) });
+ Application::transport_bootstrap_server().register_child_transport(process->pid(), IPC::TransportBootstrapMachPorts { move(port_b_recv), move(port_a_send) });
auto transport = make<IPC::Transport>(move(port_a_recv), move(port_b_send));
#elif defined(AK_OS_WINDOWS)
@@ -238,13 +274,13 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = broker_channel[1], .fd = broker_channel[1] });
TRY(Core::Environment::set("SOCKET_TAKEOVER"sv, ByteString::formatted("ipc:{};handle-broker:{}", channel[1], broker_channel[1]), Core::Environment::Overwrite::Yes));
- auto process = TRY(Core::Process::spawn(spawn_options));
+ process = TRY(Core::Process::spawn(spawn_options));
auto transport = TRY(IPC::Transport::adopt_fd(channel[0]));
guard_channel_0.disarm();
guard_broker_channel_0.disarm();
- Application::handle_broker_server().add_child(process.pid(), broker_channel[0]);
+ Application::handle_broker_server().add_child(process->pid(), broker_channel[0]);
#else
int socket_fds[2] {};
TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, socket_fds));
@@ -262,7 +298,7 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
else
TRY(Core::Environment::set("SOCKET_TAKEOVER"sv, takeover_string, Core::Environment::Overwrite::Yes));
- auto process = TRY(Core::Process::spawn(spawn_options));
+ process = TRY(Core::Process::spawn(spawn_options));
auto ipc_socket = TRY(Core::LocalSocket::adopt_fd(socket_fds[0]));
guard_fd_0.disarm();
@@ -281,7 +317,8 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([
output_capture.stderr_file = TRY(Core::File::adopt_fd(stderr_pipe[0], Core::File::OpenMode::Read));
}
- return ProcessAndIPCTransport { move(process), move(transport), move(output_capture) };
+ terminate_process_on_failure.disarm();
+ return ProcessAndIPCTransport { process.release_value(), move(transport), move(output_capture) };
}
ErrorOr<Optional<pid_t>> Process::get_process_pid(StringView process_name, StringView pid_path)
diff --git a/Libraries/LibWebView/Process.h b/Libraries/LibWebView/Process.h
index be5f8577a9c..917ff547a17 100644
--- a/Libraries/LibWebView/Process.h
+++ b/Libraries/LibWebView/Process.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Badge.h>
#include <AK/RefPtr.h>
#include <AK/Utf16String.h>
#include <AK/WeakPtr.h>
@@ -31,6 +32,7 @@ class WEBVIEW_API Process {
public:
Process(ProcessType type, RefPtr<IPC::ConnectionBase> connection, Core::Process process);
+ static Process for_browser();
~Process();
template<typename ClientType>
@@ -49,8 +51,8 @@ public:
Optional<Utf16String> const& title() const { return m_title; }
void set_title(Optional<Utf16String> title) { m_title = move(title); }
- Optional<pid_t> owner_pid() const { return m_owner_pid; }
- void set_owner_pid(pid_t pid) { m_owner_pid = pid; }
+ Optional<u64> owner_child_id() const { return m_owner_child_id; }
+ void set_owner_child_id(u64 child_id) { m_owner_child_id = child_id; }
template<typename ConnectionFromClient>
RefPtr<ConnectionFromClient> client()
@@ -69,7 +71,9 @@ public:
void save_crash_report(Optional<int> exit_status);
ByteString const& saved_crash_report_name() const { return m_saved_crash_report_name; }
- pid_t pid() const { return m_process.pid(); }
+ pid_t pid() const { return m_pid; }
+ u64 child_id() const { return m_child_id; }
+ void did_register(Badge<ProcessManager>, u64 child_id);
ProcessOutputCapture& output_capture() { return m_output_capture; }
ProcessOutputCapture const& output_capture() const { return m_output_capture; }
@@ -101,10 +105,16 @@ private:
OwnPtr<Sandbox::ConnectBroker> m_connect_broker;
#endif
- Core::Process m_process;
+ Process(ProcessType, pid_t);
+
+ pid_t m_pid { -1 };
+ // NB: The browser's own record has no process of its own to hold. On Windows, holding the process keeps its handle,
+ // and with it its PID, until this record is gone.
+ Optional<Core::Process> m_process;
+ u64 m_child_id { 0 };
ProcessType m_type;
Optional<Utf16String> m_title;
- Optional<pid_t> m_owner_pid;
+ Optional<u64> m_owner_child_id;
WeakPtr<IPC::ConnectionBase> m_connection;
ProcessOutputCapture m_output_capture;
};
@@ -124,10 +134,12 @@ template<typename ClientType, typename... ClientArguments>
ErrorOr<Process::ProcessAndClient<ClientType>> Process::spawn(ProcessType type, Core::ProcessSpawnOptions const& options, bool capture_output, ClientArguments&&... client_arguments)
{
auto [core_process, transport, output_capture] = TRY(spawn_and_connect_to_process(type, options, capture_output));
- auto client = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ClientType { move(transport), forward<ClientArguments>(client_arguments)... }));
- Process process { type, client, move(core_process) };
+ // NB: Create the record first, so that a failure below ends the helper rather than leaving it running untracked.
+ Process process { type, nullptr, move(core_process) };
process.m_output_capture = move(output_capture);
+ auto client = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ClientType { move(transport), forward<ClientArguments>(client_arguments)... }));
+ process.m_connection = *client;
return ProcessAndClient<ClientType> { move(process), client };
}
diff --git a/Libraries/LibWebView/ProcessManager.cpp b/Libraries/LibWebView/ProcessManager.cpp
index d862bd6407c..f40ca7bb22a 100644
--- a/Libraries/LibWebView/ProcessManager.cpp
+++ b/Libraries/LibWebView/ProcessManager.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/NumericLimits.h>
#include <AK/String.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Process.h>
@@ -70,13 +71,16 @@ ProcessManager::ProcessManager()
: on_process_added([](Process&) { })
, on_process_exited([](Process&&, Optional<int>) { })
, m_process_monitor(ProcessMonitor([this](pid_t pid, Optional<int> exit_status) {
- if (auto process = remove_process(pid); process.has_value()) {
+ auto child_id = m_child_ids_by_pid.get(pid);
+ if (!child_id.has_value())
+ return;
+ if (auto process = remove_process(*child_id); process.has_value()) {
process->save_crash_report(exit_status);
on_process_exited(process.release_value(), exit_status);
}
}))
{
- add_process(Process(WebView::ProcessType::Browser, nullptr, Core::Process::current()));
+ add_process(Process::for_browser());
#ifdef AK_OS_MACH
mach_port_t task_name_port = MACH_PORT_NULL;
@@ -89,18 +93,46 @@ ProcessManager::ProcessManager()
Optional<Process&> ProcessManager::find_process(pid_t pid)
{
verify_event_loop();
- return m_processes.get(pid);
+ auto child_id = m_child_ids_by_pid.get(pid);
+ if (!child_id.has_value())
+ return {};
+ return m_processes.get(*child_id);
+}
+
+Optional<Process&> ProcessManager::find_child(u64 child_id)
+{
+ verify_event_loop();
+ return m_processes.get(child_id);
}
-void ProcessManager::add_process(WebView::Process&& process)
+ChildIdentity ProcessManager::add_process(WebView::Process&& process)
{
verify_event_loop();
auto pid = process.pid();
+ u64 child_id = 0;
+ if (process.type() != ProcessType::Browser) {
+ VERIFY(m_next_child_id < NumericLimits<u64>::max());
+ child_id = m_next_child_id++;
+ }
+ process.did_register({}, child_id);
on_process_added(process);
- auto result = m_processes.set(pid, move(process));
- VERIFY(result == AK::HashSetResult::InsertedNewEntry);
+ VERIFY(m_processes.set(child_id, move(process)) == AK::HashSetResult::InsertedNewEntry);
+ VERIFY(m_child_ids_by_pid.set(pid, child_id) == AK::HashSetResult::InsertedNewEntry);
m_statistics.processes.append(make<Core::Platform::ProcessInfo>(pid));
m_process_monitor.add_process(pid);
+ return { child_id, pid };
+}
+
+ErrorOr<void> ProcessManager::terminate_child(u64 child_id, Core::Process::TerminationMode mode)
+{
+ verify_event_loop();
+ // NB: Child ID zero is the browser itself.
+ auto process = child_id != 0 ? find_child(child_id) : OptionalNone {};
+ if (!process.has_value())
+ return Error::from_errno(ESRCH);
+ // NB: The process is still in the table, so its exit has not been handled yet. On POSIX it has not been reaped,
+ // and on Windows its Process keeps the handle open, so its PID cannot belong to another process yet.
+ return Core::Process::terminate_process(process->pid(), mode);
}
void ProcessManager::for_each_process(Function<void(Process&)> callback)
@@ -114,7 +146,7 @@ void ProcessManager::for_each_process_statistics(Function<void(Process&, Core::P
{
verify_event_loop();
m_statistics.for_each_process([&](auto const& process) {
- auto process_handle = m_processes.get(process.pid);
+ auto process_handle = find_process(process.pid);
if (!process_handle.has_value())
return;
@@ -135,14 +167,19 @@ void ProcessManager::set_process_task_name_port(pid_t pid, Core::MachPort&& port
}
#endif
-Optional<Process> ProcessManager::remove_process(pid_t pid)
+Optional<Process> ProcessManager::remove_process(u64 child_id)
{
verify_event_loop();
- cancel_forced_exit(pid);
+ cancel_forced_exit(child_id);
+ auto process = m_processes.take(child_id);
+ if (!process.has_value())
+ return {};
+ auto pid = process->pid();
+ m_child_ids_by_pid.remove(pid);
m_statistics.processes.remove_first_matching([&](auto const& info) {
return (info->pid == pid);
});
- return m_processes.take(pid);
+ return process;
}
void ProcessManager::remove_all_processes()
@@ -151,12 +188,12 @@ void ProcessManager::remove_all_processes()
// NB: Shutting down a connection runs its die() handler, which looks up its process, for example to end a worker
// that did not notice the connection closing. Shut the connections down while the table is intact.
- Vector<pid_t> pids;
- pids.ensure_capacity(m_processes.size());
+ Vector<u64> child_ids;
+ child_ids.ensure_capacity(m_processes.size());
for (auto const& entry : m_processes)
- pids.unchecked_append(entry.key);
- for (auto pid : pids) {
- auto process = m_processes.get(pid);
+ child_ids.unchecked_append(entry.key);
+ for (auto child_id : child_ids) {
+ auto process = m_processes.get(child_id);
if (!process.has_value())
continue;
if (auto connection = process->client<IPC::ConnectionBase>())
@@ -165,38 +202,40 @@ void ProcessManager::remove_all_processes()
// Destroying a process may run a die() handler too, so take the processes out first. Lookups then see an empty
// table rather than one being destroyed.
+ m_child_ids_by_pid.clear();
auto processes = move(m_processes);
processes.clear();
}
-void ProcessManager::cancel_forced_exit(pid_t pid)
+void ProcessManager::cancel_forced_exit(u64 child_id)
{
verify_event_loop();
- if (auto timer = m_forced_exit_timers.take(pid); timer.has_value())
+ if (auto timer = m_forced_exit_timers.take(child_id); timer.has_value())
(*timer)->stop();
}
-void ProcessManager::force_exit_after_timeout(pid_t pid, int timeout_ms)
+void ProcessManager::force_exit_after_timeout(u64 child_id, int timeout_ms)
{
verify_event_loop();
- if (!m_processes.contains(pid))
+ if (!m_processes.contains(child_id))
return;
- if (m_forced_exit_timers.contains(pid))
+ if (m_forced_exit_timers.contains(child_id))
return;
- auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(timeout_ms), [this, pid] {
- m_forced_exit_timers.remove(pid);
- auto process = m_processes.get(pid);
+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(timeout_ms), [this, child_id] {
+ m_forced_exit_timers.remove(child_id);
+ auto process = m_processes.get(child_id);
if (!process.has_value())
return;
+ auto pid = process->pid();
dbgln("Force-killing unresponsive {} process {}", process_name_from_type(process->type()), pid);
- auto result = Core::Process::terminate_process(pid, Core::Process::TerminationMode::Forceful);
+ auto result = terminate_child(child_id, Core::Process::TerminationMode::Forceful);
if (result.is_error())
dbgln("Failed to force-kill process {}: {}", pid, result.error());
});
timer->start();
- m_forced_exit_timers.set(pid, move(timer));
+ m_forced_exit_timers.set(child_id, move(timer));
}
void ProcessManager::update_all_process_statistics()
diff --git a/Libraries/LibWebView/ProcessManager.h b/Libraries/LibWebView/ProcessManager.h
index 72b9baa915f..8e990d96b92 100644
--- a/Libraries/LibWebView/ProcessManager.h
+++ b/Libraries/LibWebView/ProcessManager.h
@@ -13,7 +13,9 @@
#include <LibCore/EventLoop.h>
#include <LibCore/Platform/ProcessResourceUsage.h>
#include <LibCore/Platform/ProcessStatistics.h>
+#include <LibCore/Process.h>
#include <LibCore/Timer.h>
+#include <LibWebView/ChildIdentity.h>
#include <LibWebView/Forward.h>
#include <LibWebView/Process.h>
#include <LibWebView/ProcessMonitor.h>
@@ -32,14 +34,17 @@ public:
ProcessManager();
- void add_process(Process&&);
+ // Gives the process its child ID and starts watching for its exit.
+ ChildIdentity add_process(Process&&);
void for_each_process(Function<void(Process&)>);
void for_each_process_statistics(Function<void(Process&, Core::Platform::ProcessInfo const&)>);
- Optional<Process> remove_process(pid_t);
+ Optional<Process> remove_process(u64 child_id);
void remove_all_processes();
Optional<Process&> find_process(pid_t);
- void cancel_forced_exit(pid_t);
- void force_exit_after_timeout(pid_t, int timeout_ms);
+ Optional<Process&> find_child(u64 child_id);
+ ErrorOr<void> terminate_child(u64 child_id, Core::Process::TerminationMode);
+ void cancel_forced_exit(u64 child_id);
+ void force_exit_after_timeout(u64 child_id, int timeout_ms);
#if defined(AK_OS_MACH)
void set_process_task_name_port(pid_t, Core::MachPort&&);
@@ -55,8 +60,11 @@ private:
void verify_event_loop() const;
Core::Platform::ProcessStatistics m_statistics;
- HashMap<pid_t, Process> m_processes;
- HashMap<pid_t, RefPtr<Core::Timer>> m_forced_exit_timers;
+ HashMap<u64, Process> m_processes;
+ // NB: Exit notifications and statistics name processes by PID.
+ HashMap<pid_t, u64> m_child_ids_by_pid;
+ HashMap<u64, RefPtr<Core::Timer>> m_forced_exit_timers;
+ u64 m_next_child_id { 1 };
ProcessMonitor m_process_monitor;
Core::EventLoop* m_creation_event_loop { &Core::EventLoop::current() };
};
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 5964a9c1129..0afcf644598 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -21,7 +21,6 @@
#include <LibWebCommon/HTML/BrowsingContext.h>
#include <LibWebCommon/Page/InputEvent.h>
#include <LibWebCommon/WebDriver/Error.h>
-#include <LibWebCommon/WebView/ProcessHandle.h>
#include <LibWebCommon/WebView/SiteIsolation.h>
#include <LibWebView/Application.h>
#include <LibWebView/AudioServerControlClient.h>
@@ -168,8 +167,7 @@ void WebContentClient::did_misbehave(StringView message_name, StringView reason)
{
m_rejected_ipc = true;
dbgln("WebContentClient: terminating helper process {}: {} rejected: {}", pid(), message_name, reason);
- if (should_terminate_pid(pid()))
- (void)Core::Process::terminate_process(pid(), Core::Process::TerminationMode::Forceful);
+ (void)Application::process_manager().terminate_child(child_id(), Core::Process::TerminationMode::Forceful);
shutdown();
}
@@ -258,7 +256,7 @@ WebContentPage& WebContentClient::open_page_for_new_top_level_traversable(Web::P
{
if (m_detached_page_close_timer)
m_detached_page_close_timer->stop();
- Application::process_manager().cancel_forced_exit(pid());
+ Application::process_manager().cancel_forced_exit(child_id());
auto& page = open_page(page_id, traversable);
traversable.active_document().set_host(page);
@@ -304,7 +302,7 @@ void WebContentClient::register_embedded_page(Web::PageId page_id, CanonicalTrav
auto& page = open_page(page_id, traversable);
if (m_unassigned_initial_page_id == page_id)
m_unassigned_initial_page_id.clear();
- Application::process_manager().cancel_forced_exit(pid());
+ Application::process_manager().cancel_forced_exit(child_id());
page.view().send_preferences_to_page(page);
if (Application::browser_options().webdriver_browser_endpoint.has_value())
@@ -418,11 +416,11 @@ void WebContentClient::close_server_if_unused()
m_detached_page_close_timer->stop();
m_requested_close = true;
async_close_server();
- Application::process_manager().force_exit_after_timeout(pid(), close_server_exit_timeout_ms);
+ Application::process_manager().force_exit_after_timeout(child_id(), close_server_exit_timeout_ms);
return;
}
- Application::process_manager().force_exit_after_timeout(pid(), detached_page_forced_exit_timeout_ms);
+ Application::process_manager().force_exit_after_timeout(child_id(), detached_page_forced_exit_timeout_ms);
if (!m_detached_page_close_timer) {
m_detached_page_close_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(detached_page_close_timeout_ms), [this] {
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 2e413e5e794..c7e227a4268 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -56,6 +56,7 @@
#include <LibWebCommon/WebView/Debugger.h>
#include <LibWebView/BlobURLStore.h>
#include <LibWebView/BrowsingSession.h>
+#include <LibWebView/ChildIdentity.h>
#include <LibWebView/Forward.h>
#include <LibWebView/RequestServerSiteBindings.h>
#include <LibWebView/WebContentPage.h>
@@ -162,8 +163,9 @@ public:
Optional<Web::PageId> page_id_for_compositor_context_id(Web::CompositorContextId) const;
bool has_requested_close() const { return m_requested_close; }
- pid_t pid() const { return m_process_handle.pid; }
- void set_pid(pid_t pid) { m_process_handle.pid = pid; }
+ pid_t pid() const { return m_child_identity.pid; }
+ u64 child_id() const { return m_child_identity.child_id; }
+ void set_child_identity(ChildIdentity identity) { m_child_identity = identity; }
private:
void close_server_if_unused();
@@ -227,7 +229,7 @@ private:
Optional<Web::HTML::SessionHistoryEntryDescriptor> m_initial_top_level_history_entry;
Web::HTML::CrossProcessId m_initial_top_level_document_id;
- ProcessHandle m_process_handle;
+ ChildIdentity m_child_identity;
ErrorOr<IPC::TransportHandle> connect_audio_server_client();
ErrorOr<void> ensure_audio_server_controller();
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 5dddf54ee1f..717f59f264f 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -437,7 +437,7 @@ void WebContentPage::maybe_record_history_visit_for_current_load(URL::URL const&
void WebContentPage::begin_top_level_load(URL::URL const& url)
{
- if (auto process = WebView::Application::the().find_process(client().pid()); process.has_value())
+ if (auto process = WebView::Application::process_manager().find_child(client().child_id()); process.has_value())
process->set_title(OptionalNone {});
m_history_recorded_url_for_current_load.clear();
@@ -2322,7 +2322,7 @@ void WebContentPage::did_finish_loading(Web::HTML::CrossProcessId navigable_id,
void WebContentPage::did_change_title(Utf16String title)
{
- if (auto process = WebView::Application::the().find_process(client().pid()); process.has_value())
+ if (auto process = WebView::Application::process_manager().find_child(client().child_id()); process.has_value())
process->set_title(title);
if (displays_tab()) {
diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cpp
index e126286ff07..d5ae74c2f58 100644
--- a/Libraries/LibWebView/WebWorkerClient.cpp
+++ b/Libraries/LibWebView/WebWorkerClient.cpp
@@ -5,7 +5,6 @@
*/
#include <LibCore/Process.h>
-#include <LibWebCommon/WebView/ProcessHandle.h>
#include <LibWebView/Application.h>
#include <LibWebView/AudioServerControlClient.h>
#include <LibWebView/BlobURLStore.h>
@@ -42,8 +41,7 @@ void WebWorkerClient::did_misbehave(StringView message_name, StringView reason)
void WebWorkerClient::terminate_process()
{
- if (should_terminate_pid(pid()))
- (void)Core::Process::terminate_process(pid(), Core::Process::TerminationMode::Forceful);
+ (void)Application::process_manager().terminate_child(child_id(), Core::Process::TerminationMode::Forceful);
}
void WebWorkerClient::die()
@@ -52,9 +50,7 @@ void WebWorkerClient::die()
WorkerProcessManager::the().worker_did_die(m_agent_id);
// NB: A worker whose connection is gone does no more work, so a process that outlives its connection is ended.
- // Until it is reaped, its process ID is still its own.
- if (Application::process_manager().find_process(pid()).has_value())
- terminate_process();
+ terminate_process();
WorkerProcessManager::the().worker_process_did_exit(*this);
// Otherwise nested workers we own would outlive us, in violation of the HTML spec.
diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.h
index e2de19558bf..98c961ffccc 100644
--- a/Libraries/LibWebView/WebWorkerClient.h
+++ b/Libraries/LibWebView/WebWorkerClient.h
@@ -19,6 +19,7 @@
#include <LibWebCommon/HTML/WorkerAgentTypes.h>
#include <LibWebView/BlobURLStore.h>
#include <LibWebView/BrowsingSession.h>
+#include <LibWebView/ChildIdentity.h>
#include <LibWebView/Export.h>
#include <LibWebView/RequestServerSiteBindings.h>
#include <WebWorker/WebWorkerClientEndpoint.h>
@@ -40,11 +41,12 @@ public:
RequestServerSiteBindings& request_server_site_bindings() { return m_request_server_site_bindings; }
void remove_blob_url_entries();
- pid_t pid() const { return m_pid; }
+ pid_t pid() const { return m_child_identity.pid; }
+ u64 child_id() const { return m_child_identity.child_id; }
void terminate_process();
Optional<CanonicalEnvironmentSettingsObject const&> hosted_environment(Web::HTML::EnvironmentId const& environment_id) const;
- void set_pid(pid_t pid) { m_pid = pid; }
+ void set_child_identity(ChildIdentity identity) { m_child_identity = identity; }
virtual void did_close_worker() override;
virtual void did_finish_loading_worker_script(bool worker_is_secure_context) override;
@@ -70,7 +72,7 @@ private:
WeakPtr<BrowsingSession> m_session;
RequestServerSiteBindings m_request_server_site_bindings;
- pid_t m_pid { -1 };
+ ChildIdentity m_child_identity;
Web::HTML::WorkerAgentId m_agent_id { 0 };
// The controller connections to the MediaServer and AudioServer spawned for this process, from its first media use
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 0bf22a42b89..f84f45e3b9b 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -71,7 +71,6 @@
#include <LibWebCommon/WebView/DictionaryLookup.h>
#include <LibWebCommon/WebView/Mutation.h>
#include <LibWebCommon/WebView/PageInfo.h>
-#include <LibWebCommon/WebView/ProcessHandle.h>
#include <LibWebCommon/WebView/StorageSetResult.h>
endpoint WebContentClient routed by Web::PageId page_id
diff --git a/Tests/LibWebView/TestCrashReport.cpp b/Tests/LibWebView/TestCrashReport.cpp
index d941cea553e..312ae13f599 100644
--- a/Tests/LibWebView/TestCrashReport.cpp
+++ b/Tests/LibWebView/TestCrashReport.cpp
@@ -13,7 +13,6 @@
#include <LibCore/System.h>
#include <LibFileSystem/FileSystem.h>
#include <LibTest/TestCase.h>
-#include <LibWebCommon/WebView/ProcessHandle.h>
#include <LibWebView/CrashReport.h>
#include <LibWebView/ProcessManager.h>
#include <fcntl.h>
@@ -93,13 +92,6 @@ static void cleanup()
MUST(FileSystem::remove(test_directory(), FileSystem::RecursionMode::Allowed));
}
-TEST_CASE(helper_termination_requires_a_specific_process_id)
-{
- EXPECT(!WebView::should_terminate_pid(-1));
- EXPECT(!WebView::should_terminate_pid(0));
- EXPECT(WebView::should_terminate_pid(1));
-}
-
enum class CrashThread {
Main,
Worker,
diff --git a/Tests/UI/Qt/TestProcessManagerWindow.cpp b/Tests/UI/Qt/TestProcessManagerWindow.cpp
index 5b7a98dd81d..a1659494368 100644
--- a/Tests/UI/Qt/TestProcessManagerWindow.cpp
+++ b/Tests/UI/Qt/TestProcessManagerWindow.cpp
@@ -151,7 +151,7 @@ TEST_CASE(end_process_terminates_a_child_and_handles_disappearing_selection)
(void)Core::System::close(pipe[0]);
(void)Core::System::close(pipe[1]);
};
- manager.add_process(WebView::Process(WebView::ProcessType::WebContent, nullptr, move(child)));
+ auto identity = manager.add_process(WebView::Process(WebView::ProcessType::WebContent, nullptr, move(child)));
Ladybird::ProcessManagerWindow window(manager);
window.show();
auto* processes = window.findChild<QTreeWidget*>();
@@ -162,6 +162,7 @@ TEST_CASE(end_process_terminates_a_child_and_handles_disappearing_selection)
EXPECT_EQ(browser->childCount(), 1);
auto* child_item = browser->child(0);
EXPECT_EQ(child_item->data(1, Qt::UserRole).toLongLong(), pid);
+ EXPECT_EQ(child_item->data(1, Qt::UserRole + 1).toULongLong(), identity.child_id);
auto blank_icon = child_item->icon(0).pixmap(16, 16).toImage();
manager.find_process(pid)->set_title("(spare)"_utf16);
EXPECT(QMetaObject::invokeMethod(timer, "timeout", Qt::DirectConnection));
@@ -195,7 +196,7 @@ TEST_CASE(end_process_terminates_a_child_and_handles_disappearing_selection)
processes->setCurrentItem(browser->child(0));
EXPECT(button->isEnabled());
- (void)manager.remove_process(pid);
+ (void)manager.remove_process(identity.child_id);
button->click();
EXPECT(!button->isEnabled());
EXPECT(QMetaObject::invokeMethod(timer, "timeout", Qt::DirectConnection));
diff --git a/UI/Qt/ProcessManagerWindow.cpp b/UI/Qt/ProcessManagerWindow.cpp
index 0766cd99014..cd89b28429a 100644
--- a/UI/Qt/ProcessManagerWindow.cpp
+++ b/UI/Qt/ProcessManagerWindow.cpp
@@ -67,6 +67,9 @@ enum Column {
Memory,
};
+// Rows are identified by the process's child ID, which, unlike its PID, never comes to name another process.
+constexpr int ChildIDRole = Qt::UserRole + 1;
+
class ProcessHeader final : public QHeaderView {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -358,25 +361,25 @@ void ProcessManagerWindow::refresh()
manager.update_all_process_statistics();
auto scroll_position = m_processes->verticalScrollBar()->value();
- auto selected_pid = m_processes->currentItem() && m_processes->currentItem()->isSelected() ? m_processes->currentItem()->data(PID, Qt::UserRole) : QVariant {};
+ auto selected_child_id = m_processes->currentItem() && m_processes->currentItem()->isSelected() ? m_processes->currentItem()->data(PID, ChildIDRole) : QVariant {};
QSignalBlocker selection_blocker(m_processes);
- HashMap<pid_t, QTreeWidgetItem*> items;
- HashMap<pid_t, bool> expanded;
+ HashMap<u64, QTreeWidgetItem*> items;
+ HashMap<u64, bool> expanded;
m_processes->setUpdatesEnabled(false);
m_processes->setSortingEnabled(false);
auto detach_items = [&](auto& self, QTreeWidgetItem* parent) -> void {
while (parent->childCount()) {
auto* item = parent->child(0);
- auto pid = static_cast<pid_t>(item->data(PID, Qt::UserRole).toLongLong());
- expanded.set(pid, item->isExpanded());
+ auto child_id = item->data(PID, ChildIDRole).toULongLong();
+ expanded.set(child_id, item->isExpanded());
self(self, item);
parent->takeChild(0);
- items.set(pid, item);
+ items.set(child_id, item);
}
};
detach_items(detach_items, m_processes->invisibleRootItem());
- HashMap<pid_t, QTreeWidgetItem*> live_items;
+ HashMap<u64, QTreeWidgetItem*> live_items;
QTreeWidgetItem* browser_item = nullptr;
double total_cpu = 0;
u64 total_memory = 0;
@@ -427,12 +430,12 @@ void ProcessManagerWindow::refresh()
return IterationDecision::Continue;
});
manager.for_each_process_statistics([&](auto& process, auto const& statistics) {
- auto* item = static_cast<ProcessItem*>(items.take(statistics.pid).value_or_lazy_evaluated([] { return new ProcessItem; }));
+ auto* item = static_cast<ProcessItem*>(items.take(process.child_id()).value_or_lazy_evaluated([] { return new ProcessItem; }));
auto name = qstring_from_ak_string(WebView::process_name_from_type(process.type()));
if (process.type() == WebView::ProcessType::WebContent || process.type() == WebView::ProcessType::ImageDecoder) {
auto* label_process = &process;
- if (process.type() == WebView::ProcessType::ImageDecoder && process.owner_pid().has_value()) {
- if (auto owner = manager.find_process(*process.owner_pid()); owner.has_value())
+ if (process.type() == WebView::ProcessType::ImageDecoder && process.owner_child_id().has_value()) {
+ if (auto owner = manager.find_child(*process.owner_child_id()); owner.has_value())
label_process = &*owner;
}
auto page = process_pages.get(label_process->pid());
@@ -465,11 +468,12 @@ void ProcessManagerWindow::refresh()
item->setText(CPU, locale.toString(statistics.cpu_percent, 'f', 2) + '%');
item->setText(Memory, locale.formattedDataSize(statistics.memory_usage_bytes, 2));
item->setData(PID, Qt::UserRole, static_cast<qlonglong>(statistics.pid));
+ item->setData(PID, ChildIDRole, static_cast<qulonglong>(process.child_id()));
item->setData(CPU, Qt::UserRole, statistics.cpu_percent);
item->setData(Memory, Qt::UserRole, static_cast<qulonglong>(statistics.memory_usage_bytes));
for (auto column : { PID, CPU, Memory })
item->setTextAlignment(column, Qt::AlignRight | Qt::AlignVCenter);
- live_items.set(statistics.pid, item);
+ live_items.set(process.child_id(), item);
total_cpu += statistics.cpu_percent;
total_memory += statistics.memory_usage_bytes;
});
@@ -482,7 +486,7 @@ void ProcessManagerWindow::refresh()
m_processes->setCurrentItem(nullptr);
for (auto& entry : live_items) {
entry.value->setExpanded(expanded.get(entry.key).value_or(true));
- if (entry.value->data(PID, Qt::UserRole) == selected_pid)
+ if (entry.value->data(PID, ChildIDRole) == selected_child_id)
m_processes->setCurrentItem(entry.value);
}
m_processes->setSortingEnabled(true);
@@ -531,8 +535,7 @@ void ProcessManagerWindow::update_actions()
m_end_process_action->setEnabled(false);
return;
}
- auto pid = static_cast<pid_t>(item->data(PID, Qt::UserRole).toLongLong());
- auto process = m_process_manager.find_process(pid);
+ auto process = m_process_manager.find_child(item->data(PID, ChildIDRole).toULongLong());
m_copy_pid_action->setEnabled(process.has_value());
m_end_process_action->setEnabled(process.has_value() && process->type() != WebView::ProcessType::Browser);
}
@@ -543,7 +546,8 @@ void ProcessManagerWindow::end_selected_process()
if (!m_end_process_action->isEnabled())
return;
auto pid = static_cast<pid_t>(m_processes->currentItem()->data(PID, Qt::UserRole).toLongLong());
- if (auto result = Core::Process::terminate_process(pid, Core::Process::TerminationMode::Forceful); result.is_error()) {
+ auto child_id = m_processes->currentItem()->data(PID, ChildIDRole).toULongLong();
+ if (auto result = m_process_manager.terminate_child(child_id, Core::Process::TerminationMode::Forceful); result.is_error()) {
if (!result.error().is_errno() || result.error().code() != ESRCH)
QMessageBox::warning(this, tr("Unable to end process"), qformatted("Could not end process {}: {}", pid, result.error()));
}