Skip to content

Truly independent web browser

LibWebView: End WebContent processes that use too much memory

Andreas Klinge7a04c1ead33
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index d084961ee3e..75a48ba0f0a 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -352,6 +352,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)
auto site_isolation_mode = default_site_isolation_mode();
bool disable_same_origin_tab_sharing = false;
Optional<size_t> maximum_site_request_servers;
+ Optional<u64> web_content_memory_limit_in_mebibytes;
bool disable_http_memory_cache = false;
bool disable_http_disk_cache = false;
bool disable_content_blocker = false;
@@ -485,6 +486,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)
args_parser.add_option(disable_http_memory_cache, "Disable HTTP memory cache", "disable-http-memory-cache");
args_parser.add_option(disable_http_disk_cache, "Disable HTTP disk cache", "disable-http-disk-cache");
args_parser.add_option(maximum_site_request_servers, "How many RequestServers a session may have for the sites it visits, 0 to share one", "max-site-request-servers", 0, "count");
+ args_parser.add_option(web_content_memory_limit_in_mebibytes, "How much memory a WebContent process may use before it is ended, 0 for no limit", "web-content-memory-limit", 0, "MiB");
args_parser.add_option(disable_content_blocker, "Disable content blocker", "disable-content-blocker");
args_parser.add_option(disable_sandbox, "Disable helper process sandboxing", "disable-sandbox");
args_parser.add_option(force_video_decoder_server, "Also decode video that has no hardware decoder in the VideoDecoderServer", "force-video-decoder-server");
@@ -618,6 +620,11 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)
.force_video_decoder_server = force_video_decoder_server ? ForceVideoDecoderServer::Yes : ForceVideoDecoderServer::No,
};
+ if (web_content_memory_limit_in_mebibytes.has_value()) {
+ if (*web_content_memory_limit_in_mebibytes > NumericLimits<u64>::max() / MiB)
+ return Error::from_string_literal("The WebContent memory limit is too large");
+ m_browser_options.web_content_memory_limit_in_bytes = *web_content_memory_limit_in_mebibytes * MiB;
+ }
if (screenshot_delay.has_value())
m_browser_options.screenshot_delay = *screenshot_delay;
if (screenshot_path.has_value())
@@ -1876,6 +1883,7 @@ ErrorOr<void> Application::launch_services()
m_process_manager->on_process_exited = [this](Process&& process, Optional<int> exit_status) {
process_did_exit(move(process), exit_status);
};
+ m_process_manager->set_web_content_memory_limit(m_browser_options.web_content_memory_limit_in_bytes.value_or(ProcessManager::default_web_content_memory_limit()));
if (m_browser_options.disable_sql_database == DisableSQLDatabase::No) {
auto database_path = profile().paths().data;
diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.h
index f2e3116e5f2..3d0c3eb9d23 100644
--- a/Libraries/LibWebView/Options.h
+++ b/Libraries/LibWebView/Options.h
@@ -114,6 +114,9 @@ struct BrowserOptions {
DisableSandbox disable_sandbox { DisableSandbox::No };
ForceVideoDecoderServer force_video_decoder_server { ForceVideoDecoderServer::No };
Vector<ByteString> content_blocker_list_paths {};
+ // How much memory a WebContent process may use before it is ended. Zero means that there is no limit, and no value
+ // means the default limit for this machine.
+ Optional<u64> web_content_memory_limit_in_bytes {};
};
enum class HTTPDiskCacheMode {
diff --git a/Libraries/LibWebView/ProcessManager.cpp b/Libraries/LibWebView/ProcessManager.cpp
index 1ad21f2b0db..9af8c753712 100644
--- a/Libraries/LibWebView/ProcessManager.cpp
+++ b/Libraries/LibWebView/ProcessManager.cpp
@@ -4,10 +4,12 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/NumberFormat.h>
#include <AK/NumericLimits.h>
#include <AK/String.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Process.h>
+#include <LibCore/System.h>
#include <LibIPC/Connection.h>
#include <LibWebView/ProcessManager.h>
@@ -74,6 +76,7 @@ StringView process_name_from_type(ProcessType type)
ProcessManager::ProcessManager()
: on_process_added([](Process&) { })
, on_process_exited([](Process&&, Optional<int>) { })
+ , on_process_exceeded_memory_limit([](Process&, u64) { })
, m_process_monitor(ProcessMonitor([this](pid_t pid, Optional<int> exit_status) {
auto child_id = m_child_ids_by_pid.get(pid);
if (!child_id.has_value())
@@ -177,6 +180,7 @@ Optional<Process> ProcessManager::remove_process(u64 child_id)
{
verify_event_loop();
cancel_forced_exit(child_id);
+ m_children_ended_for_memory_use.remove(child_id);
auto process = m_processes.take(child_id);
if (!process.has_value())
return {};
@@ -250,6 +254,82 @@ void ProcessManager::update_all_process_statistics()
(void)update_process_statistics(m_statistics);
}
+u64 ProcessManager::default_web_content_memory_limit()
+{
+#if defined(HAS_ADDRESS_SANITIZER)
+ // NB: A sanitizer multiplies the memory a helper uses, so the limit would end helpers that behave correctly.
+ return 0;
+#else
+ // A page that needs this much memory is almost always a runaway one. A machine with more memory can let a page
+ // go further before the rest of the system suffers, and a machine with little memory suffers long before one
+ // helper uses all of it.
+ auto physical_memory = Core::System::physical_memory_bytes();
+ auto limit = physical_memory > 16 * GiB ? 16 * GiB : 8 * GiB;
+ return min(limit, physical_memory / 2);
+#endif
+}
+
+void ProcessManager::set_web_content_memory_limit(u64 limit_in_bytes)
+{
+ verify_event_loop();
+ m_web_content_memory_limit = limit_in_bytes;
+ if (limit_in_bytes == 0) {
+ if (m_web_content_memory_limit_timer)
+ m_web_content_memory_limit_timer->stop();
+ return;
+ }
+
+ // NB: A runaway helper can grow by gigabytes per second, so a long interval would let it pass the limit by far.
+ static constexpr auto check_interval = AK::Duration::from_seconds(2);
+ if (!m_web_content_memory_limit_timer) {
+ m_web_content_memory_limit_timer = Core::Timer::create_repeating(check_interval, [this] {
+ end_helpers_over_memory_limit();
+ });
+ }
+ m_web_content_memory_limit_timer->start();
+}
+
+void ProcessManager::end_helpers_over_memory_limit()
+{
+ verify_event_loop();
+
+ struct HelperOverLimit {
+ u64 child_id { 0 };
+ u64 memory_usage_in_bytes { 0 };
+ };
+ Vector<HelperOverLimit> helpers_over_limit;
+ for (auto const& info : m_statistics.processes) {
+ // NB: Child ID zero is the browser itself.
+ auto child_id = m_child_ids_by_pid.get(info->pid);
+ if (!child_id.has_value() || *child_id == 0 || m_children_ended_for_memory_use.contains(*child_id))
+ continue;
+ // NB: Only WebContent has a limit for now. The other helpers serve every tab, so ending one of them would
+ // disturb all tabs, and none of them can tell the user why it was ended.
+ if (auto process = find_child(*child_id); !process.has_value() || process->type() != ProcessType::WebContent)
+ continue;
+ auto usage = Core::Platform::process_resource_usage(*info);
+ if (usage.has_value() && usage->attributed_memory_bytes > m_web_content_memory_limit)
+ helpers_over_limit.append({ *child_id, usage->attributed_memory_bytes });
+ }
+
+ // The callback may change the process table, so each helper is looked up again.
+ for (auto const& helper : helpers_over_limit) {
+ auto process = find_child(helper.child_id);
+ if (!process.has_value())
+ continue;
+ warnln("Ending {} process {}: it uses {} of memory, and the limit is {}", process_name_from_type(process->type()), process->pid(), human_readable_size(helper.memory_usage_in_bytes), human_readable_size(m_web_content_memory_limit));
+ // NB: The exit is handled in a later task, so the process is still in the table for the callback. A helper
+ // that could not be ended is not reported, or a later crash of it would be blamed on its memory use. It
+ // is not remembered either, so the next check tries again.
+ if (auto result = terminate_child(helper.child_id, Core::Process::TerminationMode::Forceful); result.is_error()) {
+ warnln("Failed to end process over its memory limit: {}", result.error());
+ continue;
+ }
+ m_children_ended_for_memory_use.set(helper.child_id);
+ on_process_exceeded_memory_limit(*process, helper.memory_usage_in_bytes);
+ }
+}
+
void ProcessManager::verify_event_loop() const
{
if (Core::EventLoop::is_running())
diff --git a/Libraries/LibWebView/ProcessManager.h b/Libraries/LibWebView/ProcessManager.h
index 45130e8e8f9..2333d0d0f67 100644
--- a/Libraries/LibWebView/ProcessManager.h
+++ b/Libraries/LibWebView/ProcessManager.h
@@ -8,6 +8,7 @@
#include <AK/Function.h>
#include <AK/HashMap.h>
+#include <AK/HashTable.h>
#include <AK/RefPtr.h>
#include <AK/Types.h>
#include <LibCore/EventLoop.h>
@@ -52,19 +53,32 @@ public:
#endif
void update_all_process_statistics();
+
+ // The memory a WebContent process may use on this machine before it is ended. Zero means that there is no limit.
+ static u64 default_web_content_memory_limit();
+ // Ends each helper that uses more memory than the limit, so that one runaway process cannot take the machine
+ // down. A limit of zero turns the check off.
+ void set_web_content_memory_limit(u64 limit_in_bytes);
Optional<Core::Platform::ProcessResourceUsage> resource_usage(pid_t) const;
Function<void(Process&)> on_process_added; // test-web
Function<void(Process&&, Optional<int> exit_status)> on_process_exited;
+ // Called when a helper was ended for using more memory than the limit, before its exit is handled.
+ Function<void(Process&, u64 memory_usage_in_bytes)> on_process_exceeded_memory_limit;
private:
void verify_event_loop() const;
+ void end_helpers_over_memory_limit();
Core::Platform::ProcessStatistics m_statistics;
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_web_content_memory_limit { 0 };
+ RefPtr<Core::Timer> m_web_content_memory_limit_timer;
+ // NB: A helper ended for its memory use stays in the table until its exit is handled.
+ HashTable<u64> m_children_ended_for_memory_use;
u64 m_next_child_id { 1 };
ProcessMonitor m_process_monitor;
Core::EventLoop* m_creation_event_loop { &Core::EventLoop::current() };