1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 03:37:43 +00:00

LibWeb: Move initialization of the MainThreadVM to WebContent's main()

It is a fallible operation, so this lets us abort early if it fails.
This commit is contained in:
Timothy Flynn 2023-03-17 10:56:59 -04:00 committed by Linus Groh
parent 13dfadba79
commit 6e1b5b541a
4 changed files with 307 additions and 291 deletions

View file

@ -20,6 +20,7 @@
#include <LibCore/SystemServerTakeover.h>
#include <LibIPC/ConnectionFromClient.h>
#include <LibMain/Main.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Loader/ContentFilter.h>
#include <LibWeb/Loader/FrameLoader.h>
#include <LibWeb/Loader/ResourceLoader.h>
@ -78,6 +79,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
Web::FrameLoader::set_error_page_url(DeprecatedString::formatted("file://{}/res/html/error.html", s_serenity_resource_root));
TRY(Web::Bindings::initialize_main_thread_vm());
auto maybe_content_filter_error = load_content_filters();
if (maybe_content_filter_error.is_error())
dbgln("Failed to load content filters: {}", maybe_content_filter_error.error());

View file

@ -32,6 +32,8 @@
namespace Web::Bindings {
static RefPtr<JS::VM> s_main_thread_vm;
// https://html.spec.whatwg.org/multipage/webappapis.html#active-script
HTML::Script* active_script()
{
@ -52,23 +54,23 @@ HTML::Script* active_script()
});
}
JS::VM& main_thread_vm()
ErrorOr<void> initialize_main_thread_vm()
{
static RefPtr<JS::VM> vm;
if (!vm) {
vm = JS::VM::create(make<WebEngineCustomData>()).release_value_but_fixme_should_propagate_errors();
VERIFY(!s_main_thread_vm);
s_main_thread_vm = TRY(JS::VM::create(make<WebEngineCustomData>()));
// NOTE: We intentionally leak the main thread JavaScript VM.
// This avoids doing an exhaustive garbage collection on process exit.
vm->ref();
s_main_thread_vm->ref();
static_cast<WebEngineCustomData*>(vm->custom_data())->event_loop.set_vm(*vm);
static_cast<WebEngineCustomData*>(s_main_thread_vm->custom_data())->event_loop.set_vm(*s_main_thread_vm);
// 8.1.5.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
s_main_thread_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 Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
if (is<HTML::WindowProxy>(object) || is<HTML::Location>(object))
return vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
return s_main_thread_vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
// 2. Return NormalCompletion(unused).
return {};
@ -77,11 +79,11 @@ JS::VM& main_thread_vm()
// FIXME: Implement 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
// 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
s_main_thread_vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
// 1. Let script be the running script.
// The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
HTML::Script* script { nullptr };
vm->running_execution_context().script_or_module.visit(
s_main_thread_vm->running_execution_context().script_or_module.visit(
[&script](JS::NonnullGCPtr<JS::Script>& js_script) {
script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
},
@ -149,7 +151,7 @@ JS::VM& main_thread_vm()
};
// 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) {
s_main_thread_vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) {
auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data);
// 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]]. (NOTE: Not necessary)
@ -160,15 +162,15 @@ JS::VM& main_thread_vm()
// 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
if (callback_host_defined.active_script_context)
vm->push_execution_context(*callback_host_defined.active_script_context);
s_main_thread_vm->push_execution_context(*callback_host_defined.active_script_context);
// 5. Let result be Call(callback.[[Callback]], V, argumentsList).
auto result = JS::call(*vm, *callback.callback.cell(), this_value, move(arguments_list));
auto result = JS::call(*s_main_thread_vm, *callback.callback.cell(), this_value, move(arguments_list));
// 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
if (callback_host_defined.active_script_context) {
VERIFY(&vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
vm->pop_execution_context();
VERIFY(&s_main_thread_vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
s_main_thread_vm->pop_execution_context();
}
// 7. Clean up after running a callback with incumbent settings.
@ -179,7 +181,7 @@ JS::VM& main_thread_vm()
};
// 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {
s_main_thread_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();
@ -208,7 +210,7 @@ JS::VM& main_thread_vm()
};
// 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
vm->host_enqueue_promise_job = [](Function<JS::ThrowCompletionOr<JS::Value>()> job, JS::Realm* realm) {
s_main_thread_vm->host_enqueue_promise_job = [](Function<JS::ThrowCompletionOr<JS::Value>()> job, JS::Realm* realm) {
// 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
HTML::EnvironmentSettingsObject* job_settings { nullptr };
if (realm)
@ -217,7 +219,7 @@ JS::VM& main_thread_vm()
// 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.
// This means taking it here now and passing it through to the lambda.
auto script_or_module = vm->get_active_script_or_module();
auto script_or_module = s_main_thread_vm->get_active_script_or_module();
// 2. Queue a microtask on the surrounding agent's event loop to perform the following steps:
// This instance of "queue a microtask" uses the "implied document". The best fit for "implied document" here is "If the task is being queued by or for a script, then return the script's settings object's responsible document."
@ -249,9 +251,9 @@ JS::VM& main_thread_vm()
// FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
// This is because JS::NativeFunction::call excepts something to be on the execution context stack to be able to get the caller context to initialize the environment.
// Do note that the JS spec gives _no_ guarantee that the execution context stack has something on it if HostEnqueuePromiseJob was called with a null realm: https://tc39.es/ecma262/#job-preparedtoevaluatecode
dummy_execution_context = JS::ExecutionContext { vm->heap() };
dummy_execution_context = JS::ExecutionContext { s_main_thread_vm->heap() };
dummy_execution_context->script_or_module = script_or_module;
vm->push_execution_context(dummy_execution_context.value());
s_main_thread_vm->push_execution_context(dummy_execution_context.value());
}
// 3. Let result be job().
@ -268,7 +270,7 @@ JS::VM& main_thread_vm()
job_settings->clean_up_after_running_script();
} else {
// Pop off the dummy execution context. See the above FIXME block about why this is done.
vm->pop_execution_context();
s_main_thread_vm->pop_execution_context();
}
// 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
@ -278,7 +280,7 @@ JS::VM& main_thread_vm()
};
// 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::JobCallback {
s_main_thread_vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::JobCallback {
// 1. Let incumbent settings be the incumbent settings object.
auto& incumbent_settings = HTML::incumbent_settings_object();
@ -291,7 +293,7 @@ JS::VM& main_thread_vm()
// 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
// its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.
if (script) {
script_execution_context = adopt_own(*new JS::ExecutionContext(vm->heap()));
script_execution_context = adopt_own(*new JS::ExecutionContext(s_main_thread_vm->heap()));
script_execution_context->function = nullptr;
script_execution_context->realm = &script->settings_object().realm();
if (is<HTML::ClassicScript>(script)) {
@ -318,13 +320,13 @@ JS::VM& main_thread_vm()
// FIXME: Implement 8.1.5.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
// 8.1.5.5.4 HostGetSupportedImportAssertions(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
vm->host_get_supported_import_assertions = []() -> Vector<DeprecatedString> {
s_main_thread_vm->host_get_supported_import_assertions = []() -> Vector<DeprecatedString> {
// 1. Return « "type" ».
return { "type"sv };
};
// 8.1.6.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
vm->host_resolve_imported_module = [](JS::ScriptOrModule const& referencing_string_or_module, JS::ModuleRequest const& module_request) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>> {
s_main_thread_vm->host_resolve_imported_module = [](JS::ScriptOrModule const& referencing_string_or_module, JS::ModuleRequest const& module_request) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>> {
// 1. Let moduleMap and referencingScript be null.
Optional<HTML::ModuleMap&> module_map;
Optional<HTML::Script&> referencing_script;
@ -368,8 +370,14 @@ JS::VM& main_thread_vm()
// 10. Return resolvedModuleScript's record.
return JS::NonnullGCPtr(*resolved_module_script.module_script->record());
};
}
return *vm;
return {};
}
JS::VM& main_thread_vm()
{
VERIFY(s_main_thread_vm);
return *s_main_thread_vm;
}
// https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask

View file

@ -50,7 +50,10 @@ struct WebEngineCustomJobCallbackData final : public JS::JobCallback::CustomData
};
HTML::Script* active_script();
ErrorOr<void> initialize_main_thread_vm();
JS::VM& main_thread_vm();
void queue_mutation_observer_microtask(DOM::Document const&);
NonnullOwnPtr<JS::ExecutionContext> create_a_new_javascript_realm(JS::VM&, Function<JS::Object*(JS::Realm&)> create_global_object, Function<JS::Object*(JS::Realm&)> create_global_this_value);

View file

@ -12,6 +12,7 @@
#include <LibCore/System.h>
#include <LibIPC/SingleServer.h>
#include <LibMain/Main.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/EventLoopPluginSerenity.h>
@ -45,6 +46,7 @@ ErrorOr<int> serenity_main(Main::Arguments)
Web::WebSockets::WebSocketClientManager::initialize(TRY(WebView::WebSocketClientManagerAdapter::try_create()));
Web::ResourceLoader::initialize(TRY(WebView::RequestServerAdapter::try_create()));
TRY(Web::Bindings::initialize_main_thread_vm());
auto client = TRY(IPC::take_over_accepted_client_from_system_server<WebContent::ConnectionFromClient>());
return event_loop.exec();