MainThreadVM.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2021, 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/Environment.h>
  9. #include <LibJS/Runtime/FinalizationRegistry.h>
  10. #include <LibJS/Runtime/NativeFunction.h>
  11. #include <LibJS/Runtime/VM.h>
  12. #include <LibWeb/Bindings/MainThreadVM.h>
  13. #include <LibWeb/DOM/Document.h>
  14. #include <LibWeb/DOM/Window.h>
  15. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  16. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  17. #include <LibWeb/HTML/Scripting/Environments.h>
  18. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  19. namespace Web::Bindings {
  20. // https://html.spec.whatwg.org/multipage/webappapis.html#active-script
  21. HTML::ClassicScript* active_script()
  22. {
  23. // 1. Let record be GetActiveScriptOrModule().
  24. auto record = main_thread_vm().get_active_script_or_module();
  25. // 2. If record is null, return null.
  26. if (record.has<Empty>())
  27. return nullptr;
  28. // 3. Return record.[[HostDefined]].
  29. if (record.has<WeakPtr<JS::Module>>()) {
  30. // FIXME: We don't currently have a module script.
  31. TODO();
  32. }
  33. auto js_script = record.get<WeakPtr<JS::Script>>();
  34. VERIFY(js_script);
  35. VERIFY(js_script->host_defined());
  36. return verify_cast<HTML::ClassicScript>(js_script->host_defined());
  37. }
  38. JS::VM& main_thread_vm()
  39. {
  40. static RefPtr<JS::VM> vm;
  41. if (!vm) {
  42. vm = JS::VM::create(make<WebEngineCustomData>());
  43. static_cast<WebEngineCustomData*>(vm->custom_data())->event_loop.set_vm(*vm);
  44. // FIXME: Implement 8.1.5.1 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
  45. // 8.1.5.2 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
  46. vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
  47. // 1. Let script be the running script.
  48. // The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
  49. // FIXME: This currently assumes there's only a ClassicScript.
  50. HTML::ClassicScript* script { nullptr };
  51. vm->running_execution_context().script_or_module.visit(
  52. [&script](WeakPtr<JS::Script>& js_script) {
  53. script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
  54. },
  55. [](WeakPtr<JS::Module>&) {
  56. TODO();
  57. },
  58. [](Empty) {
  59. });
  60. // If there's no script, we're out of luck. Return.
  61. // FIXME: This can happen from JS::NativeFunction, which makes its callee contexts [[ScriptOrModule]] null.
  62. if (!script) {
  63. dbgln("FIXME: Unable to process unhandled promise rejection in host_promise_rejection_tracker as the running script is null.");
  64. return;
  65. }
  66. // 2. If script's muted errors is true, terminate these steps.
  67. if (script->muted_errors() == HTML::ClassicScript::MutedErrors::Yes)
  68. return;
  69. // 3. Let settings object be script's settings object.
  70. auto& settings_object = script->settings_object();
  71. switch (operation) {
  72. case JS::Promise::RejectionOperation::Reject:
  73. // 4. If operation is "reject",
  74. // 1. Add promise to settings object's about-to-be-notified rejected promises list.
  75. settings_object.push_onto_about_to_be_notified_rejected_promises_list(JS::make_handle(&promise));
  76. break;
  77. case JS::Promise::RejectionOperation::Handle: {
  78. // 5. If operation is "handle",
  79. // 1. If settings object's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
  80. bool removed_about_to_be_notified_rejected_promise = settings_object.remove_from_about_to_be_notified_rejected_promises_list(&promise);
  81. if (removed_about_to_be_notified_rejected_promise)
  82. return;
  83. // 3. Remove promise from settings object's outstanding rejected promises weak set.
  84. bool removed_outstanding_rejected_promise = settings_object.remove_from_outstanding_rejected_promises_weak_set(&promise);
  85. // 2. If settings object's outstanding rejected promises weak set does not contain promise, then return.
  86. // 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.
  87. if (!removed_outstanding_rejected_promise)
  88. return;
  89. // 4. Let global be settings object's global object.
  90. auto& global = settings_object.global_object();
  91. // 5. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
  92. // with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
  93. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, [global = JS::make_handle(&global), promise = JS::make_handle(&promise)]() mutable {
  94. // FIXME: This currently assumes that global is a WindowObject.
  95. auto& window = verify_cast<Bindings::WindowObject>(*global.cell());
  96. HTML::PromiseRejectionEventInit event_init {
  97. {}, // Initialize the inherited DOM::EventInit
  98. /* .promise = */ promise,
  99. /* .reason = */ promise.cell()->result(),
  100. };
  101. auto promise_rejection_event = HTML::PromiseRejectionEvent::create(HTML::EventNames::rejectionhandled, event_init);
  102. window.impl().dispatch_event(move(promise_rejection_event));
  103. });
  104. break;
  105. }
  106. default:
  107. VERIFY_NOT_REACHED();
  108. }
  109. };
  110. // 8.1.5.3.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
  111. vm->host_call_job_callback = [](JS::GlobalObject& global_object, JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) {
  112. auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data);
  113. // 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]]. (NOTE: Not necessary)
  114. // 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]]. (NOTE: Not necessary)
  115. // 3. Prepare to run a callback with incumbent settings.
  116. callback_host_defined.incumbent_settings.prepare_to_run_callback();
  117. // 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
  118. if (callback_host_defined.active_script_context)
  119. MUST(vm->push_execution_context(*callback_host_defined.active_script_context, callback.callback.cell()->global_object()));
  120. // 5. Let result be Call(callback.[[Callback]], V, argumentsList).
  121. auto result = JS::call(global_object, *callback.callback.cell(), this_value, move(arguments_list));
  122. // 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
  123. if (callback_host_defined.active_script_context) {
  124. VERIFY(&vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
  125. vm->pop_execution_context();
  126. }
  127. // 7. Clean up after running a callback with incumbent settings.
  128. callback_host_defined.incumbent_settings.clean_up_after_running_callback();
  129. // 8. Return result.
  130. return result;
  131. };
  132. // 8.1.5.3.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
  133. vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) mutable {
  134. // 1. Let global be finalizationRegistry.[[Realm]]'s global object.
  135. auto& global = finalization_registry.realm().global_object();
  136. // 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:
  137. HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, [finalization_registry = JS::make_handle(&finalization_registry)]() mutable {
  138. // 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object.
  139. auto& entry = verify_cast<HTML::EnvironmentSettingsObject>(*finalization_registry.cell()->cleanup_callback().callback.cell()->realm()->host_defined());
  140. // 2. Check if we can run script with entry. If this returns "do not run", then return.
  141. if (entry.can_run_script() == HTML::RunScriptDecision::DoNotRun)
  142. return;
  143. // 3. Prepare to run script with entry.
  144. entry.prepare_to_run_script();
  145. // 4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).
  146. auto result = finalization_registry.cell()->cleanup();
  147. // 5. Clean up after running script with entry.
  148. entry.clean_up_after_running_script();
  149. // 6. If result is an abrupt completion, then report the exception given by result.[[Value]].
  150. if (result.is_error())
  151. HTML::report_exception(result);
  152. });
  153. };
  154. // 8.1.5.3.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
  155. vm->host_enqueue_promise_job = [](Function<JS::ThrowCompletionOr<JS::Value>()> job, JS::Realm* realm) {
  156. // 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
  157. HTML::EnvironmentSettingsObject* job_settings { nullptr };
  158. if (realm)
  159. job_settings = verify_cast<HTML::EnvironmentSettingsObject>(realm->host_defined());
  160. // 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
  161. // also be the active script or module of the job at the time of its invocation.
  162. // This means taking it here now and passing it through to the lambda.
  163. auto script_or_module = vm->get_active_script_or_module();
  164. // 2. Queue a microtask on the surrounding agent's event loop to perform the following steps:
  165. // 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."
  166. // 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
  167. auto* script = active_script();
  168. // NOTE: This keeps job_settings alive by keeping realm alive, which is holding onto job_settings.
  169. 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 {
  170. // The dummy execution context has to be kept up here to keep it alive for the duration of the function.
  171. Optional<JS::ExecutionContext> dummy_execution_context;
  172. if (job_settings) {
  173. // 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.
  174. if (job_settings->can_run_script() == HTML::RunScriptDecision::DoNotRun)
  175. return;
  176. // 2. If job settings is not null, then prepare to run script with job settings.
  177. job_settings->prepare_to_run_script();
  178. // IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
  179. // Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
  180. job_settings->realm_execution_context().script_or_module = script_or_module;
  181. } else {
  182. // FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
  183. // 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.
  184. // 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.
  185. // 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.
  186. // 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
  187. VERIFY(script_or_module.has<WeakPtr<JS::Script>>());
  188. auto script_record = script_or_module.get<WeakPtr<JS::Script>>();
  189. dummy_execution_context = JS::ExecutionContext { vm->heap() };
  190. dummy_execution_context->script_or_module = script_or_module;
  191. vm->push_execution_context(dummy_execution_context.value(), script_record->realm().global_object());
  192. }
  193. // 3. Let result be job().
  194. [[maybe_unused]] auto result = job();
  195. // 4. If job settings is not null, then clean up after running script with job settings.
  196. if (job_settings) {
  197. // IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
  198. job_settings->realm_execution_context().script_or_module = Empty {};
  199. job_settings->clean_up_after_running_script();
  200. } else {
  201. // Pop off the dummy execution context. See the above FIXME block about why this is done.
  202. vm->pop_execution_context();
  203. }
  204. // 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
  205. if (result.is_error())
  206. HTML::report_exception(result);
  207. });
  208. };
  209. // 8.1.5.3.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
  210. vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::JobCallback {
  211. // 1. Let incumbent settings be the incumbent settings object.
  212. auto& incumbent_settings = HTML::incumbent_settings_object();
  213. // 2. Let active script be the active script.
  214. auto* script = active_script();
  215. // 3. Let script execution context be null.
  216. OwnPtr<JS::ExecutionContext> script_execution_context;
  217. // 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
  218. // its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.
  219. if (script) {
  220. script_execution_context = adopt_own(*new JS::ExecutionContext(vm->heap()));
  221. script_execution_context->function = nullptr;
  222. script_execution_context->realm = &script->settings_object().realm();
  223. VERIFY(script->script_record());
  224. script_execution_context->script_or_module = script->script_record()->make_weak_ptr();
  225. }
  226. // 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.
  227. auto host_defined = adopt_own(*new WebEngineCustomJobCallbackData(incumbent_settings, move(script_execution_context)));
  228. return { JS::make_handle(&callable), move(host_defined) };
  229. };
  230. // FIXME: Implement 8.1.5.4.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
  231. // FIXME: Implement 8.1.5.4.2 HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability), https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-modulerequest,-promisecapability)
  232. // FIXME: Implement 8.1.5.4.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
  233. // FIXME: Implement 8.1.5.4.4 HostGetSupportedImportAssertions(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
  234. vm->host_resolve_imported_module = [&](JS::ScriptOrModule, JS::ModuleRequest const&) -> JS::ThrowCompletionOr<NonnullRefPtr<JS::Module>> {
  235. return vm->throw_completion<JS::InternalError>(vm->current_realm()->global_object(), JS::ErrorType::NotImplemented, "Modules in the browser");
  236. };
  237. }
  238. return *vm;
  239. }
  240. }