Truly independent web browser
LibWeb: Set up an agent on any thread
Andreas Kling140f5063c63b
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex e47033e9721..99995b50237 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -8,8 +8,10 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Atomic.h>#include <AK/NeverDestroyed.h>#include <LibCore/AnonymousBuffer.h>+#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/ThreadEventQueue.h>#include <LibGC/CellAllocator.h>#include <LibGC/DeferGC.h>@@ -46,6 +48,8 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/Fetch/Fetching/BodyStreamPullSource.h>+#include <LibWeb/Fetch/Fetching/Fetching.h>+#include <LibWeb/FileAPI/BlobURLStore.h>#include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>#include <LibWeb/HTML/EventNames.h>#include <LibWeb/HTML/HTMLFormElement.h>@@ -72,7 +76,10 @@#include <LibWeb/PerformanceTimeline/PerformanceObserver.h>#include <LibWeb/PermissionsAPI/PermissionStore.h>#include <LibWeb/Platform/EventLoopPlugin.h>+#include <LibWeb/Platform/ImageCodecPlugin.h>#include <LibWeb/Platform/ThreadPoolWork.h>+#include <LibWeb/ServiceWorker/Job.h>+#include <LibWeb/ServiceWorker/Registration.h>#include <LibWeb/ServiceWorker/ServiceWorkerContainer.h>#include <LibWeb/TrustedTypes/TrustedScript.h>#include <LibWeb/WebAssembly/WebAssembly.h>@@ -92,12 +99,15 @@ void WebEngineCustomJobCallbackData::visit_edges(Cell::Visitor& visitor)active_script_context->visit_edges(visitor);}+// The VM of the window agent. A process that hosts only workers has none.static auto& main_thread_vm_ptr(){static NeverDestroyed<RefPtr<JS::VM>> vm;return *vm;}+static Atomic<bool, AK::MemoryOrder::memory_order_relaxed> s_collect_garbage_on_every_allocation { false };+static HTML::SimilarOriginWindowAgent*& main_thread_similar_origin_window_agent_ptr(){static HTML::SimilarOriginWindowAgent* agent;@@ -108,7 +118,7 @@ static HTML::SimilarOriginWindowAgent*& main_thread_similar_origin_window_agent_HTML::Script* active_script(){// 1. Let record be GetActiveScriptOrModule().- auto record = main_thread_vm().get_active_script_or_module();+ auto record = JS::VM::the().get_active_script_or_module();// 2. If record is null, return null.// 3. Return record.[[HostDefined]].@@ -145,43 +155,62 @@ static NonnullOwnPtr<HTML::Agent> create_agent(GC::Heap& heap, HTML::AgentType tHTML::SimilarOriginWindowAgent& main_thread_similar_origin_window_agent(){- VERIFY(main_thread_similar_origin_window_agent_ptr());- return *main_thread_similar_origin_window_agent_ptr();+ auto* agent = main_thread_similar_origin_window_agent_ptr();+ VERIFY(agent);+ VERIFY(JS::VM::the().agent() == agent);+ return *agent;+}++void set_collect_garbage_on_every_allocation_in_new_agents(bool enabled)+{+ s_collect_garbage_on_every_allocation = enabled;}-void initialize_main_thread_vm(HTML::AgentType type)+void initialize_agent(HTML::AgentType type){- VERIFY(!main_thread_vm_ptr());+ auto new_vm = JS::VM::create();+ auto& vm = *new_vm;+ if (type == HTML::AgentType::SimilarOriginWindow) {+ VERIFY(!main_thread_vm_ptr());+ main_thread_vm_ptr() = new_vm;+ }+ vm.set_agent(create_agent(vm.heap(), type));++ vm.heap().set_should_collect_on_every_allocation(s_collect_garbage_on_every_allocation);- main_thread_vm_ptr() = JS::VM::create();- main_thread_vm_ptr()->set_agent(create_agent(main_thread_vm_ptr()->heap(), type));+ // A window agent has the main thread, whose priority its process sets. Workers run below it, at what a worker+ // process would give its own main thread.+ if (type != HTML::AgentType::SimilarOriginWindow) {+ if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInitiated); result.is_error())+ warnln("Could not set the QoS of an agent's thread: {}", result.error());+ }- main_thread_vm_ptr()->on_unimplemented_property_access = [](auto const& object, auto const& property_key) {+ vm.on_unimplemented_property_access = [](auto const& object, auto const& property_key) {dbgln("FIXME: Unimplemented IDL interface: '{}.{}'", object.class_name(), property_key.to_utf16_string());};- // NOTE: We intentionally leak the main thread JavaScript VM.+ // NOTE: We intentionally leak the JavaScript VM, unless the agent is shut down.// This avoids doing an exhaustive garbage collection on process exit.- main_thread_vm_ptr()->ref();+ vm.ref();// 8.1.6.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation- main_thread_vm_ptr()->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {+ vm.host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {// 1. If O is a WindowProxy object, or implements Location, then return ThrowCompletion(a new TypeError).if (HTML::WindowProxy::from_object(object) || impl_from<HTML::Location>(&object))- return main_thread_vm_ptr()->throw_completion<JS::TypeError>(u"Cannot add private elements to window or location object"sv);+ return JS::VM::the().throw_completion<JS::TypeError>(u"Cannot add private elements to window or location object"sv);// 2. Return NormalCompletion(unused).return {};};// 8.1.6.2 HostEnsureCanCompileStrings(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(realm,-parameterstrings,-bodystring,-codestring,-compilationtype,-parameterargs,-bodyarg)- main_thread_vm_ptr()->host_ensure_can_compile_strings = [](JS::Realm& realm, ReadonlySpan<Utf16String> parameter_strings, Utf16View body_string, Utf16View code_string, JS::CompilationType compilation_type, ReadonlySpan<JS::Value> parameter_args, JS::Value body_arg) -> JS::ThrowCompletionOr<void> {+ vm.host_ensure_can_compile_strings = [](JS::Realm& realm, ReadonlySpan<Utf16String> parameter_strings, Utf16View body_string, Utf16View code_string, JS::CompilationType compilation_type, ReadonlySpan<JS::Value> parameter_args, JS::Value body_arg) -> JS::ThrowCompletionOr<void> {// 1. Perform ? EnsureCSPDoesNotBlockStringCompilation(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg). [CSP]return ContentSecurityPolicy::ensure_csp_does_not_block_string_compilation(realm, parameter_strings, body_string, code_string, compilation_type, parameter_args, body_arg);};// 8.1.6.3 HostGetCodeForEval(argument), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetcodeforeval(argument)- main_thread_vm_ptr()->host_get_code_for_eval = [](JS::Object const& argument) -> GC::Ptr<JS::PrimitiveString> {+ vm.host_get_code_for_eval = [](JS::Object const& argument) -> GC::Ptr<JS::PrimitiveString> {// 1. If argument is a TrustedScript object, then return argument's data.if (auto const* trusted_script = impl_from<TrustedTypes::TrustedScript>(&argument))return JS::PrimitiveString::create(argument.vm(), trusted_script->to_string());@@ -191,8 +220,8 @@ void initialize_main_thread_vm(HTML::AgentType type)};// 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation- main_thread_vm_ptr()->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {- auto& vm = *main_thread_vm_ptr();+ vm.host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {+ auto& vm = JS::VM::the();// NB: Nothing reports what an aborted script left behind.if (vm.interrupt_requested())@@ -232,7 +261,7 @@ void initialize_main_thread_vm(HTML::AgentType type)case JS::Promise::RejectionOperation::Reject:// 1. Append promise to global's about-to-be-notified rejected promises list.global_mixin.push_onto_about_to_be_notified_rejected_promises_list(promise);- HTML::main_thread_event_loop().did_reject_promise_without_handler();+ HTML::current_event_loop().did_reject_promise_without_handler();break;// 7. If operation is "handle",case JS::Promise::RejectionOperation::Handle: {@@ -276,7 +305,7 @@ void initialize_main_thread_vm(HTML::AgentType type)};// 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback- main_thread_vm_ptr()->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, ReadonlySpan<JS::Value> arguments_list) {+ vm.host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, ReadonlySpan<JS::Value> arguments_list) {auto& callback_host_defined = as<WebEngineCustomJobCallbackData>(*callback.custom_data());// 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]].@@ -289,16 +318,17 @@ void initialize_main_thread_vm(HTML::AgentType type)HTML::prepare_to_run_callback(incumbent_settings);// 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.+ auto& vm = JS::VM::the();if (script_execution_context)- main_thread_vm_ptr()->push_execution_context(*script_execution_context);+ vm.push_execution_context(*script_execution_context);// 5. Let result be Call(callback.[[Callback]], V, argumentsList).- auto result = JS::call(*main_thread_vm_ptr(), callback.callback(), this_value, arguments_list);+ auto result = JS::call(vm, callback.callback(), this_value, arguments_list);// 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.if (script_execution_context) {- VERIFY(&main_thread_vm_ptr()->running_execution_context() == script_execution_context);- main_thread_vm_ptr()->pop_execution_context();+ VERIFY(&vm.running_execution_context() == script_execution_context);+ vm.pop_execution_context();}// 7. Clean up after running a callback with incumbent settings.@@ -309,7 +339,7 @@ void initialize_main_thread_vm(HTML::AgentType type)};// 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob- main_thread_vm_ptr()->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {+ vm.host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {// 1. Let global be finalizationRegistry.[[Realm]]'s global object.auto& global = finalization_registry.realm().global_object();@@ -342,8 +372,8 @@ void initialize_main_thread_vm(HTML::AgentType type)};// 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob- main_thread_vm_ptr()->host_enqueue_promise_job = [](JS::PromiseJob job, GC::Ptr<JS::Realm> realm) {- auto& vm = *main_thread_vm_ptr();+ vm.host_enqueue_promise_job = [](JS::PromiseJob job, GC::Ptr<JS::Realm> realm) {+ auto& vm = JS::VM::the();// IMPLEMENTATION DEFINED: The JS spec says we must take implementation defined steps to make the currently active script or module at the time of HostEnqueuePromiseJob being invoked// also be the active script or module of the job at the time of its invocation.@@ -408,12 +438,12 @@ void initialize_main_thread_vm(HTML::AgentType type)}));};- main_thread_vm_ptr()->host_promise_job_queue_is_empty = []() -> bool {- return HTML::main_thread_event_loop().microtask_queue_empty();+ vm.host_promise_job_queue_is_empty = []() -> bool {+ return HTML::current_event_loop().microtask_queue_empty();};// 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback- main_thread_vm_ptr()->host_make_job_callback = [](JS::FunctionObject& callable) -> GC::Ref<JS::JobCallback> {+ vm.host_make_job_callback = [](JS::FunctionObject& callable) -> GC::Ref<JS::JobCallback> {// 1. Let incumbent settings be the incumbent settings object.auto& incumbent_settings = HTML::incumbent_settings_object();@@ -441,12 +471,13 @@ void initialize_main_thread_vm(HTML::AgentType type)}// 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.- auto host_defined = main_thread_vm_ptr()->heap().allocate<WebEngineCustomJobCallbackData>(incumbent_settings, move(script_execution_context));- return JS::JobCallback::create(*main_thread_vm_ptr(), callable, host_defined);+ auto& vm = JS::VM::the();+ auto host_defined = vm.heap().allocate<WebEngineCustomJobCallbackData>(incumbent_settings, move(script_execution_context));+ return JS::JobCallback::create(vm, callable, host_defined);};// 8.1.6.7.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties- main_thread_vm_ptr()->host_get_import_meta_properties = [](JS::SourceTextModule& module_record) {+ vm.host_get_import_meta_properties = [](JS::SourceTextModule& module_record) {auto& realm = module_record.realm();auto& vm = realm.vm();@@ -487,14 +518,14 @@ void initialize_main_thread_vm(HTML::AgentType type)};// 8.1.6.7.2 HostGetSupportedImportAttributes(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions- main_thread_vm_ptr()->host_get_supported_import_attributes = []() -> Vector<Utf16String> {+ vm.host_get_supported_import_attributes = []() -> Vector<Utf16String> {// 1. Return « "type" ».return { "type"_utf16 };};// 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload), https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule- main_thread_vm_ptr()->host_load_imported_module = [](JS::ImportedModuleReferrer referrer, JS::ModuleRequest const& module_request, GC::Ptr<GC::Cell> load_state, JS::ImportedModulePayload payload) -> void {- auto& vm = *main_thread_vm_ptr();+ vm.host_load_imported_module = [](JS::ImportedModuleReferrer referrer, JS::ModuleRequest const& module_request, GC::Ptr<GC::Cell> load_state, JS::ImportedModulePayload payload) -> void {+ auto& vm = JS::VM::the();// 1. Let settingsObject be the current settings object.GC::Ref<HTML::EnvironmentSettingsObject> settings_object = HTML::current_settings_object();@@ -574,7 +605,7 @@ void initialize_main_thread_vm(HTML::AgentType type)}// 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, ThrowCompletion(resolutionError)).- auto completion = WebIDL::exception_to_throw_completion(main_thread_vm(), settings_object->realm(), maybe_exception.exception());+ auto completion = WebIDL::exception_to_throw_completion(JS::VM::the(), settings_object->realm(), maybe_exception.exception());JS::finish_loading_imported_module(referrer, module_request, payload, completion);// 3. Return.@@ -624,7 +655,7 @@ void initialize_main_thread_vm(HTML::AgentType type)}// 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, ThrowCompletion(resolutionError)).- auto completion = WebIDL::exception_to_throw_completion(main_thread_vm(), settings_object->realm(), url.exception());+ auto completion = WebIDL::exception_to_throw_completion(JS::VM::the(), settings_object->realm(), url.exception());HTML::TemporaryExecutionContext context { *settings_object };JS::finish_loading_imported_module(referrer, module_request, payload, completion);@@ -718,7 +749,7 @@ void initialize_main_thread_vm(HTML::AgentType type)HTML::fetch_single_imported_module_script(settings_object->realm(), url.release_value(), fetch_client, destination, fetch_options, settings_object, fetch_referrer, module_request, perform_fetch, on_single_fetch_complete);};- main_thread_vm_ptr()->host_unrecognized_date_string = [](Utf16View date) {+ vm.host_unrecognized_date_string = [](Utf16View date) {// NB: Sites routinely construct dates from empty strings on purpose, so those would only drown out strings our// date parser fails to understand.if (date.is_empty())@@ -726,16 +757,16 @@ void initialize_main_thread_vm(HTML::AgentType type)dbgln("Unable to parse date string: \"{}\"", date);};- main_thread_vm_ptr()->host_resize_array_buffer = [default_host_resize_array_buffer = move(main_thread_vm_ptr()->host_resize_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {- auto wasm_handled = TRY(WebAssembly::host_resize_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));+ vm.host_resize_array_buffer = [default_host_resize_array_buffer = move(vm.host_resize_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {+ auto wasm_handled = TRY(WebAssembly::host_resize_array_buffer(JS::VM::the(), buffer, new_byte_length));if (wasm_handled == JS::HandledByHost::Handled)return JS::HandledByHost::Handled;return default_host_resize_array_buffer(buffer, new_byte_length);};- main_thread_vm_ptr()->host_grow_shared_array_buffer = [default_host_grow_shared_array_buffer = move(main_thread_vm_ptr()->host_grow_shared_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {- auto wasm_handled = TRY(WebAssembly::host_grow_shared_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));+ vm.host_grow_shared_array_buffer = [default_host_grow_shared_array_buffer = move(vm.host_grow_shared_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {+ auto wasm_handled = TRY(WebAssembly::host_grow_shared_array_buffer(JS::VM::the(), buffer, new_byte_length));if (wasm_handled == JS::HandledByHost::Handled)return JS::HandledByHost::Handled;@@ -747,7 +778,10 @@ extern "C" void web_rust_shut_down_agent(JSVM*);void shut_down_agent(){- auto& vm = main_thread_vm();+ auto& vm = JS::VM::the();++ // NB: A window agent lives as long as its process does.+ VERIFY(&vm != main_thread_vm_ptr().ptr());static_cast<HTML::Agent*>(vm.agent())->detach_script_abort_handle();@@ -758,7 +792,11 @@ void shut_down_agent()PerformanceTimeline::clear_supported_entry_types_caches();Crypto::clear_crypto_key_caches();ServiceWorker::clear_service_worker_container_ready_promise_caches();- PermissionsAPI::PermissionStore::the().forget_statuses();+ PermissionsAPI::PermissionStore::forget_statuses_of_this_agent();+ FileAPI::forget_blob_url_store_of_this_agent();+ Fetch::Fetching::clear_http_memory_cache();+ ServiceWorker::forget_job_queues_of_this_agent();+ ServiceWorker::Registration::forget_registrations_of_this_agent();// An event that is still queued can hold roots as well, and a stopped request only lets go of its roots in one. As// the task queues discard everything by now, no script runs from these. What a deferred invocation of LibWeb is for@@ -776,17 +814,18 @@ void shut_down_agent()web_rust_shut_down_agent(JS::HostABI::vm_to_abi(vm));ResourceLoader::shut_down();+ Platform::ImageCodecPlugin::shut_down();// NB: The VM stays reachable while it is destroyed, as the finalizers of the cells in its heap use it.vm.unref();- vm.unref();- (void)main_thread_vm_ptr().leak_ref();}JS::VM& main_thread_vm(){- VERIFY(main_thread_vm_ptr());- return *main_thread_vm_ptr();+ auto* vm = main_thread_vm_ptr().ptr();+ VERIFY(vm);+ VERIFY(&JS::VM::the() == vm);+ return *vm;}// https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm@@ -828,7 +867,7 @@ static void ensure_main_thread_vm_initialized()return;Platform::EventLoopPlugin::install(*new Platform::EventLoopPlugin);- initialize_main_thread_vm(HTML::AgentType::SimilarOriginWindow);+ initialize_agent(HTML::AgentType::SimilarOriginWindow);}GC::Ref<JS::Realm> create_a_simple_javascript_realm()diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.h b/Libraries/LibWeb/Bindings/MainThreadVM.hindex 46adc29ef69..0fc3b3ad374 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.h+++ b/Libraries/LibWeb/Bindings/MainThreadVM.h@@ -42,12 +42,19 @@ private:HTML::Script* active_script();-WEB_API void initialize_main_thread_vm(HTML::AgentType);+// Sets up the agent of the current thread, with its VM, heap and event loop. Any thread that has none can host one,+// but a process has one window agent at most. What belongs to the process, such as the plugins, is not set up by this.+WEB_API void initialize_agent(HTML::AgentType);++// Agents that start after this inherit it.+WEB_API void set_collect_garbage_on_every_allocation_in_new_agents(bool);++// The VM of the window agent, from that agent's thread only. Code that a worker can reach has to use JS::VM::the().WEB_API JS::VM& main_thread_vm();// Ends the agent of the current thread: releases what it keeps outside its heap, runs the events queued on the thread,// and destroys its VM and heap. The caller has run its closing steps and given up its roots. None of this ends the-// thread or the process, and the agent's thread has to be the one that calls it.+// thread or the process, and the agent's thread has to be the one that calls it. Other agents carry on.WEB_API void shut_down_agent();WEB_API NonnullOwnPtr<JS::ExecutionContext> create_a_new_javascript_realm(JS::VM&, HTML::CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode, Function<GC::Ref<JS::Object>(JS::Realm&)> create_global_object, Function<GC::Ref<JS::Object>(JS::Realm&)> create_global_this_value);diff --git a/Meta/Fuzzers/FuzzCSSParser.cpp b/Meta/Fuzzers/FuzzCSSParser.cppindex 520733eff64..1f4e1444837 100644--- a/Meta/Fuzzers/FuzzCSSParser.cpp+++ b/Meta/Fuzzers/FuzzCSSParser.cpp@@ -18,7 +18,7 @@ struct Globals {Globals::Globals(){Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);- Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);}}diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 3e49a5dc06b..4749e0a1ab3 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -278,13 +278,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Web::HTML::Window::set_internals_object_exposed(expose_internals_object);Web::HTML::WindowOrWorkerGlobalScopeMixin::set_experimental_interfaces_exposed(expose_experimental_interfaces);- Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ Web::Bindings::set_collect_garbage_on_every_allocation_in_new_agents(collect_garbage_on_every_allocation);+ Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);if (stats_log)Web::Bindings::main_thread_vm().heap().enable_stats();- if (collect_garbage_on_every_allocation)- Web::Bindings::main_thread_vm().heap().set_should_collect_on_every_allocation(true);-if (log_all_js_exceptions) {JS::set_log_all_js_exceptions(true);}diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cppindex e695e1836d4..db56557de56 100644--- a/Services/WebWorker/ConnectionFromClient.cpp+++ b/Services/WebWorker/ConnectionFromClient.cpp@@ -119,7 +119,7 @@ void ConnectionFromClient::set_user_agent(String user_agent)void ConnectionFromClient::set_navigator_compatibility_mode(Web::NavigatorCompatibilityMode mode){- Web::ResourceLoader::the().set_navigator_compatibility_mode(mode);+ Web::ResourceLoader::set_navigator_compatibility_mode(mode);}void ConnectionFromClient::set_preferred_languages(Vector<String> preferred_languages)@@ -138,8 +138,8 @@ void ConnectionFromClient::begin_closing()m_worker_host->terminate();return;}- Web::Bindings::main_thread_vm().request_interrupt();- Web::HTML::main_thread_event_loop().destroy_once_script_has_finished();+ JS::VM::the().request_interrupt();+ Web::HTML::current_event_loop().destroy_once_script_has_finished();}void ConnectionFromClient::die()@@ -210,13 +210,13 @@ ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transpo// down right away, rather than handle startup messages and make sync requests on a closed connection.set_peer_owns_this_process(true);- Web::HTML::main_thread_event_loop().set_on_destroyed([] {+ Web::HTML::current_event_loop().set_on_destroyed([] {Core::EventLoop::current().quit(0);});// NB: The thread that handles close_worker() may be stuck in script, so that message and the loss of the client have// to abort the script from the IO thread, for this thread to get to them at all.- auto& agent = *static_cast<Web::HTML::Agent*>(Web::Bindings::main_thread_vm().agent());+ auto& agent = Web::HTML::surrounding_agent();this->transport().set_incoming_message_observer([script_abort_handle = agent.script_abort_handle()](ReadonlyBytes message) {struct [[gnu::packed]] Header {u32 endpoint_magic;@@ -258,7 +258,7 @@ void ConnectionFromClient::start_worker(URL::URL url, Web::HTML::WorkerType typebool const is_shared = agent_type == Web::HTML::AgentType::SharedWorker;VERIFY(is_shared || agent_type == Web::HTML::AgentType::DedicatedWorker);- // FIXME: Add an assertion that the agent_type passed here is the same that was passed at process creation to initialize_main_thread_vm()+ // FIXME: Add an assertion that the agent_type passed here is the same that was passed to initialize_agent()m_worker_host->set_on_script_ready([this] {auto pending = move(m_pending_transform_inits);diff --git a/Services/WebWorker/WorkerHost.cpp b/Services/WebWorker/WorkerHost.cppindex 39993e3d890..f056c284273 100644--- a/Services/WebWorker/WorkerHost.cpp+++ b/Services/WebWorker/WorkerHost.cpp@@ -113,7 +113,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes// cross-origin isolation mode is "none" until the worker's response sets it.auto agent_cluster_cross_origin_isolation_mode = is_shared ? Web::HTML::CrossOriginIsolationMode::None : outside_settings_snapshot.agent_cluster_cross_origin_isolation_mode;auto realm_execution_context = Web::Bindings::create_a_new_javascript_realm(- Web::Bindings::main_thread_vm(),+ JS::VM::the(),agent_cluster_cross_origin_isolation_mode,[page, is_shared](JS::Realm& realm) -> GC::Ref<JS::Object> {// For the global object, if is shared is true, create a new SharedWorkerGlobalScope object.diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cppindex 4b41f99b212..ac4f538dd97 100644--- a/Services/WebWorker/main.cpp+++ b/Services/WebWorker/main.cpp@@ -108,8 +108,6 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (auto result = Core::Platform::adopt_foreground_application_task_role(); result.is_error())warnln("Could not adopt the foreground application task role: {}", result.error());- if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInitiated); result.is_error())- warnln("Could not set main thread QoS: {}", result.error());if (file_origins_are_tuple_origins)URL::set_file_scheme_urls_have_tuple_origins();@@ -129,16 +127,16 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);- Web::Bindings::initialize_main_thread_vm(worker_type);+ Web::Bindings::initialize_agent(worker_type);if (stats_log)- Web::Bindings::main_thread_vm().heap().enable_stats();+ JS::VM::the().heap().enable_stats();if (!disable_sandbox)TRY(RendererSandbox::apply_sandbox(mach_server_name));auto client = TRY(IPC::take_over_accepted_client_from_system_server<WebWorker::ConnectionFromClient>(mach_server_name, enable_test_mode));- auto& heap = Web::Bindings::main_thread_vm().heap();+ auto& heap = JS::VM::the().heap();client->on_request_server_connection = [&heap](auto const& handle, auto client_id, auto const& top_level_site) {if (auto result = connect_to_resource_loader(heap, handle, client_id, top_level_site); result.is_error())dbgln("Failed to connect to resource loader: {}", result.error());diff --git a/Tests/LibWeb/BenchmarkDisplayListRecording.cpp b/Tests/LibWeb/BenchmarkDisplayListRecording.cppindex 5cd3a7232e1..a7b7d11f0ff 100644--- a/Tests/LibWeb/BenchmarkDisplayListRecording.cpp+++ b/Tests/LibWeb/BenchmarkDisplayListRecording.cpp@@ -214,7 +214,7 @@ void initialize_web_platform()// the bundled fonts from.Web::Platform::FontPlugin::install(*new Web::Platform::FontPlugin(false));- Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);}Web::HTML::PaintConfig benchmark_paint_config()diff --git a/UI/Android/src/main/cpp/WebContentService.cpp b/UI/Android/src/main/cpp/WebContentService.cppindex 732dcdc67d6..3eda68e0604 100644--- a/UI/Android/src/main/cpp/WebContentService.cpp+++ b/UI/Android/src/main/cpp/WebContentService.cpp@@ -46,7 +46,7 @@ ErrorOr<int> service_main(int ipc_socket)Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(bind_image_decoder_service));- Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);auto request_server_client = TRY(bind_request_server_service());Web::ResourceLoader::initialize(Web::Bindings::main_thread_vm().heap());diff --git a/Utilities/dump-html-tree.cpp b/Utilities/dump-html-tree.cppindex 2afdabe05df..292cc047ae2 100644--- a/Utilities/dump-html-tree.cpp+++ b/Utilities/dump-html-tree.cpp@@ -331,7 +331,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)[[maybe_unused]] auto& event_loop = Core::EventLoop::initialize_for_current_thread();Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);Web::Platform::FontPlugin::install(*new Web::Platform::FontPlugin(false));- Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);auto& vm = Web::Bindings::main_thread_vm();auto page_client = DumpHTMLTreePageClient::create(vm);