MainThreadVM.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Module.h>
  8. #include <LibJS/Runtime/Array.h>
  9. #include <LibJS/Runtime/Environment.h>
  10. #include <LibJS/Runtime/FinalizationRegistry.h>
  11. #include <LibJS/Runtime/NativeFunction.h>
  12. #include <LibJS/Runtime/VM.h>
  13. #include <LibWeb/Bindings/IDLAbstractOperations.h>
  14. #include <LibWeb/Bindings/LocationObject.h>
  15. #include <LibWeb/Bindings/MainThreadVM.h>
  16. #include <LibWeb/Bindings/WindowProxy.h>
  17. #include <LibWeb/DOM/Document.h>
  18. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  19. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  20. #include <LibWeb/HTML/Scripting/Environments.h>
  21. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  22. #include <LibWeb/HTML/Window.h>
  23. #include <LibWeb/Platform/EventLoopPlugin.h>
  24. namespace Web::Bindings {
  25. // https://html.spec.whatwg.org/multipage/webappapis.html#active-script
  26. HTML::ClassicScript* active_script()
  27. {
  28. // 1. Let record be GetActiveScriptOrModule().
  29. auto record = main_thread_vm().get_active_script_or_module();
  30. // 2. If record is null, return null.
  31. if (record.has<Empty>())
  32. return nullptr;
  33. // 3. Return record.[[HostDefined]].
  34. if (record.has<JS::NonnullGCPtr<JS::Module>>()) {
  35. // FIXME: We don't currently have a module script.
  36. TODO();
  37. }
  38. auto js_script = record.get<JS::NonnullGCPtr<JS::Script>>();
  39. VERIFY(js_script);
  40. VERIFY(js_script->host_defined());
  41. return verify_cast<HTML::ClassicScript>(js_script->host_defined());
  42. }
  43. JS::VM& main_thread_vm()
  44. {
  45. static RefPtr<JS::VM> vm;
  46. if (!vm) {
  47. vm = JS::VM::create(make<WebEngineCustomData>());
  48. // NOTE: We intentionally leak the main thread JavaScript VM.
  49. // This avoids doing an exhaustive garbage collection on process exit.
  50. vm->ref();
  51. static_cast<WebEngineCustomData*>(vm->custom_data())->event_loop.set_vm(*vm);
  52. // 8.1.5.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
  53. vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
  54. // 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
  55. if (is<WindowProxy>(object) || is<LocationObject>(object))
  56. return vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object");
  57. // 2. Return NormalCompletion(unused).
  58. return {};
  59. };
  60. // FIXME: Implement 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
  61. // 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
  62. vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
  63. // 1. Let script be the running script.
  64. // The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
  65. HTML::Script* script { nullptr };
  66. vm->running_execution_context().script_or_module.visit(
  67. [&script](JS::NonnullGCPtr<JS::Script>& js_script) {
  68. script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
  69. },
  70. [](JS::NonnullGCPtr<JS::Module>&) {
  71. TODO();
  72. },
  73. [](Empty) {
  74. });
  75. // 2. If script is a classic script and script's muted errors is true, then return.
  76. // NOTE: is<T>() returns false if nullptr is passed.
  77. if (is<HTML::ClassicScript>(script)) {
  78. auto const& classic_script = static_cast<HTML::ClassicScript const&>(*script);
  79. if (classic_script.muted_errors() == HTML::ClassicScript::MutedErrors::Yes)
  80. return;
  81. }
  82. // 3. Let settings object be the current settings object.
  83. // 4. If script is not null, then set settings object to script's settings object.
  84. auto& settings_object = script ? script->settings_object() : HTML::current_settings_object();
  85. switch (operation) {
  86. case JS::Promise::RejectionOperation::Reject:
  87. // 4. If operation is "reject",
  88. // 1. Add promise to settings object's about-to-be-notified rejected promises list.
  89. settings_object.push_onto_about_to_be_notified_rejected_promises_list(JS::make_handle(&promise));
  90. break;
  91. case JS::Promise::RejectionOperation::Handle: {
  92. // 5. If operation is "handle",
  93. // 1. If settings object's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
  94. bool removed_about_to_be_notified_rejected_promise = settings_object.remove_from_about_to_be_notified_rejected_promises_list(&promise);
  95. if (removed_about_to_be_notified_rejected_promise)
  96. return;
  97. // 3. Remove promise from settings object's outstanding rejected promises weak set.
  98. bool removed_outstanding_rejected_promise = settings_object.remove_from_outstanding_rejected_promises_weak_set(&promise);
  99. // 2. If settings object's outstanding rejected promises weak set does not contain promise, then return.
  100. // NOTE: This is done out of order because removed_outstanding_rejected_promise will be false if the promise wasn't in the set or true if it was and got removed.
  101. if (!removed_outstanding_rejected_promise)
  102. return;
  103. // 4. Let global be settings object's global object.
  104. auto& global = settings_object.global_object();
  105. // 5. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
  106. // with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
  107. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, [&global, &promise]() mutable {
  108. // FIXME: This currently assumes that global is a WindowObject.
  109. auto& window = verify_cast<HTML::Window>(global);
  110. HTML::PromiseRejectionEventInit event_init {
  111. {}, // Initialize the inherited DOM::EventInit
  112. /* .promise = */ promise,
  113. /* .reason = */ promise.result(),
  114. };
  115. auto promise_rejection_event = HTML::PromiseRejectionEvent::create(window, HTML::EventNames::rejectionhandled, event_init);
  116. window.dispatch_event(*promise_rejection_event);
  117. });
  118. break;
  119. }
  120. default:
  121. VERIFY_NOT_REACHED();
  122. }
  123. };
  124. // 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
  125. vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) {
  126. auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data);
  127. // 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]]. (NOTE: Not necessary)
  128. // 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]]. (NOTE: Not necessary)
  129. // 3. Prepare to run a callback with incumbent settings.
  130. callback_host_defined.incumbent_settings.prepare_to_run_callback();
  131. // 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
  132. if (callback_host_defined.active_script_context)
  133. vm->push_execution_context(*callback_host_defined.active_script_context);
  134. // 5. Let result be Call(callback.[[Callback]], V, argumentsList).
  135. auto result = JS::call(*vm, *callback.callback.cell(), this_value, move(arguments_list));
  136. // 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
  137. if (callback_host_defined.active_script_context) {
  138. VERIFY(&vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
  139. vm->pop_execution_context();
  140. }
  141. // 7. Clean up after running a callback with incumbent settings.
  142. callback_host_defined.incumbent_settings.clean_up_after_running_callback();
  143. // 8. Return result.
  144. return result;
  145. };
  146. // 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
  147. vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) mutable {
  148. // 1. Let global be finalizationRegistry.[[Realm]]'s global object.
  149. auto& global = finalization_registry.realm().global_object();
  150. // 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:
  151. HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, [&finalization_registry]() mutable {
  152. // 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object.
  153. auto& entry = verify_cast<HTML::EnvironmentSettingsObject>(*finalization_registry.cleanup_callback().callback.cell()->realm()->host_defined());
  154. // 2. Check if we can run script with entry. If this returns "do not run", then return.
  155. if (entry.can_run_script() == HTML::RunScriptDecision::DoNotRun)
  156. return;
  157. // 3. Prepare to run script with entry.
  158. entry.prepare_to_run_script();
  159. // 4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).
  160. auto result = finalization_registry.cleanup();
  161. // 5. Clean up after running script with entry.
  162. entry.clean_up_after_running_script();
  163. // 6. If result is an abrupt completion, then report the exception given by result.[[Value]].
  164. if (result.is_error())
  165. HTML::report_exception(result);
  166. });
  167. };
  168. // 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
  169. vm->host_enqueue_promise_job = [](Function<JS::ThrowCompletionOr<JS::Value>()> job, JS::Realm* realm) {
  170. // 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
  171. HTML::EnvironmentSettingsObject* job_settings { nullptr };
  172. if (realm)
  173. job_settings = verify_cast<HTML::EnvironmentSettingsObject>(realm->host_defined());
  174. // 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
  175. // also be the active script or module of the job at the time of its invocation.
  176. // This means taking it here now and passing it through to the lambda.
  177. auto script_or_module = vm->get_active_script_or_module();
  178. // 2. Queue a microtask on the surrounding agent's event loop to perform the following steps:
  179. // 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."
  180. // Do note that "implied document" from the spec is handwavy and the spec authors are trying to get rid of it: https://github.com/whatwg/html/issues/4980
  181. auto* script = active_script();
  182. // NOTE: This keeps job_settings alive by keeping realm alive, which is holding onto job_settings.
  183. HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, [job_settings, job = move(job), realm = realm ? JS::make_handle(realm) : JS::Handle<JS::Realm> {}, script_or_module = move(script_or_module)]() mutable {
  184. // The dummy execution context has to be kept up here to keep it alive for the duration of the function.
  185. Optional<JS::ExecutionContext> dummy_execution_context;
  186. if (job_settings) {
  187. // 1. If job settings is not null, then check if we can run script with job settings. If this returns "do not run" then return.
  188. if (job_settings->can_run_script() == HTML::RunScriptDecision::DoNotRun)
  189. return;
  190. // 2. If job settings is not null, then prepare to run script with job settings.
  191. job_settings->prepare_to_run_script();
  192. // IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
  193. // Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
  194. job_settings->realm_execution_context().script_or_module = script_or_module;
  195. } else {
  196. // FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
  197. // 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.
  198. // Since this requires pushing an execution context onto the stack, it also requires a global object. The only thing we can get a global object from in this case is the script or module.
  199. // To do this, we must assume script or module is not Empty. We must also assume that it is a Script Record for now as we don't currently run modules.
  200. // 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
  201. VERIFY(script_or_module.has<JS::NonnullGCPtr<JS::Script>>());
  202. dummy_execution_context = JS::ExecutionContext { vm->heap() };
  203. dummy_execution_context->script_or_module = script_or_module;
  204. vm->push_execution_context(dummy_execution_context.value());
  205. }
  206. // 3. Let result be job().
  207. [[maybe_unused]] auto result = job();
  208. // 4. If job settings is not null, then clean up after running script with job settings.
  209. if (job_settings) {
  210. // IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
  211. job_settings->realm_execution_context().script_or_module = Empty {};
  212. job_settings->clean_up_after_running_script();
  213. } else {
  214. // Pop off the dummy execution context. See the above FIXME block about why this is done.
  215. vm->pop_execution_context();
  216. }
  217. // 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
  218. if (result.is_error())
  219. HTML::report_exception(result);
  220. });
  221. };
  222. // 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
  223. vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::JobCallback {
  224. // 1. Let incumbent settings be the incumbent settings object.
  225. auto& incumbent_settings = HTML::incumbent_settings_object();
  226. // 2. Let active script be the active script.
  227. auto* script = active_script();
  228. // 3. Let script execution context be null.
  229. OwnPtr<JS::ExecutionContext> script_execution_context;
  230. // 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
  231. // its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.
  232. if (script) {
  233. script_execution_context = adopt_own(*new JS::ExecutionContext(vm->heap()));
  234. script_execution_context->function = nullptr;
  235. script_execution_context->realm = &script->settings_object().realm();
  236. VERIFY(script->script_record());
  237. script_execution_context->script_or_module = JS::NonnullGCPtr<JS::Script>(*script->script_record());
  238. }
  239. // 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.
  240. auto host_defined = adopt_own(*new WebEngineCustomJobCallbackData(incumbent_settings, move(script_execution_context)));
  241. return { JS::make_handle(&callable), move(host_defined) };
  242. };
  243. // FIXME: Implement 8.1.5.5.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
  244. // FIXME: Implement 8.1.5.5.2 HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability), https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-modulerequest,-promisecapability)
  245. // FIXME: Implement 8.1.5.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
  246. // FIXME: Implement 8.1.5.5.4 HostGetSupportedImportAssertions(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
  247. vm->host_resolve_imported_module = [](JS::ScriptOrModule, JS::ModuleRequest const&) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>> {
  248. return vm->throw_completion<JS::InternalError>(JS::ErrorType::NotImplemented, "Modules in the browser");
  249. };
  250. // NOTE: We push a dummy execution context onto the JS execution context stack,
  251. // just to make sure that it's never empty.
  252. auto& custom_data = *verify_cast<WebEngineCustomData>(vm->custom_data());
  253. custom_data.root_execution_context = MUST(JS::Realm::initialize_host_defined_realm(
  254. *vm, [&](JS::Realm& realm) -> JS::Object* {
  255. custom_data.internal_window_object = JS::make_handle(*HTML::Window::create(realm));
  256. return custom_data.internal_window_object.cell();
  257. },
  258. nullptr));
  259. vm->push_execution_context(*custom_data.root_execution_context);
  260. }
  261. return *vm;
  262. }
  263. HTML::Window& main_thread_internal_window_object()
  264. {
  265. auto& vm = main_thread_vm();
  266. auto& custom_data = verify_cast<WebEngineCustomData>(*vm.custom_data());
  267. return *custom_data.internal_window_object;
  268. }
  269. // https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
  270. void queue_mutation_observer_microtask(DOM::Document& document)
  271. {
  272. auto& vm = main_thread_vm();
  273. auto& custom_data = verify_cast<WebEngineCustomData>(*vm.custom_data());
  274. // 1. If the surrounding agent’s mutation observer microtask queued is true, then return.
  275. if (custom_data.mutation_observer_microtask_queued)
  276. return;
  277. // 2. Set the surrounding agent’s mutation observer microtask queued to true.
  278. custom_data.mutation_observer_microtask_queued = true;
  279. // 3. Queue a microtask to notify mutation observers.
  280. // NOTE: This uses the implied document concept. In the case of mutation observers, it is always done in a node context, so document should be that node's document.
  281. // FIXME: Is it safe to pass custom_data through?
  282. HTML::queue_a_microtask(&document, [&custom_data]() {
  283. // 1. Set the surrounding agent’s mutation observer microtask queued to false.
  284. custom_data.mutation_observer_microtask_queued = false;
  285. // 2. Let notifySet be a clone of the surrounding agent’s mutation observers.
  286. auto notify_set = custom_data.mutation_observers;
  287. // FIXME: 3. Let signalSet be a clone of the surrounding agent’s signal slots.
  288. // FIXME: 4. Empty the surrounding agent’s signal slots.
  289. // 5. For each mo of notifySet:
  290. for (auto& mutation_observer : notify_set) {
  291. // 1. Let records be a clone of mo’s record queue.
  292. // 2. Empty mo’s record queue.
  293. auto records = mutation_observer->take_records();
  294. // 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.
  295. for (auto& node : mutation_observer->node_list()) {
  296. // FIXME: Is this correct?
  297. if (node.is_null())
  298. continue;
  299. node->registered_observers_list().remove_all_matching([&mutation_observer](DOM::RegisteredObserver& registered_observer) {
  300. return is<DOM::TransientRegisteredObserver>(registered_observer) && static_cast<DOM::TransientRegisteredObserver&>(registered_observer).observer().ptr() == mutation_observer.ptr();
  301. });
  302. }
  303. // 4. If records is not empty, then invoke mo’s callback with « records, mo », and mo. If this throws an exception, catch it, and report the exception.
  304. if (!records.is_empty()) {
  305. auto& callback = mutation_observer->callback();
  306. auto& realm = callback.callback_context.realm();
  307. auto* wrapped_records = MUST(JS::Array::create(realm, 0));
  308. for (size_t i = 0; i < records.size(); ++i) {
  309. auto& record = records.at(i);
  310. auto property_index = JS::PropertyKey { i };
  311. MUST(wrapped_records->create_data_property(property_index, record.ptr()));
  312. }
  313. auto result = IDL::invoke_callback(callback, mutation_observer.ptr(), wrapped_records, mutation_observer.ptr());
  314. if (result.is_abrupt())
  315. HTML::report_exception(result);
  316. }
  317. }
  318. // FIXME: 6. For each slot of signalSet, fire an event named slotchange, with its bubbles attribute set to true, at slot.
  319. });
  320. }
  321. // https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
  322. NonnullOwnPtr<JS::ExecutionContext> create_a_new_javascript_realm(JS::VM& vm, Function<JS::Object*(JS::Realm&)> create_global_object, Function<JS::Object*(JS::Realm&)> create_global_this_value)
  323. {
  324. // 1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.
  325. // 2. Let realm execution context be the running JavaScript execution context.
  326. auto realm_execution_context = MUST(JS::Realm::initialize_host_defined_realm(vm, move(create_global_object), move(create_global_this_value)));
  327. // 3. Remove realm execution context from the JavaScript execution context stack.
  328. vm.execution_context_stack().remove_first_matching([&realm_execution_context](auto* execution_context) {
  329. return execution_context == realm_execution_context.ptr();
  330. });
  331. // NO-OP: 4. Let realm be realm execution context's Realm component.
  332. // NO-OP: 5. Set realm's agent to agent.
  333. // FIXME: 6. If agent's agent cluster's cross-origin isolation mode is "none", then:
  334. // 1. Let global be realm's global object.
  335. // 2. Let status be ! global.[[Delete]]("SharedArrayBuffer").
  336. // 3. Assert: status is true.
  337. // 7. Return realm execution context.
  338. return realm_execution_context;
  339. }
  340. void WebEngineCustomData::spin_event_loop_until(Function<bool()> goal_condition)
  341. {
  342. Platform::EventLoopPlugin::the().spin_until(move(goal_condition));
  343. }
  344. }