VM.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Array.h>
  9. #include <AK/Debug.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/String.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/Time.h>
  15. #include <LibFileSystem/FileSystem.h>
  16. #include <LibJS/AST.h>
  17. #include <LibJS/Bytecode/Interpreter.h>
  18. #include <LibJS/Runtime/AbstractOperations.h>
  19. #include <LibJS/Runtime/Array.h>
  20. #include <LibJS/Runtime/ArrayBuffer.h>
  21. #include <LibJS/Runtime/BoundFunction.h>
  22. #include <LibJS/Runtime/Completion.h>
  23. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  24. #include <LibJS/Runtime/Error.h>
  25. #include <LibJS/Runtime/FinalizationRegistry.h>
  26. #include <LibJS/Runtime/FunctionEnvironment.h>
  27. #include <LibJS/Runtime/Iterator.h>
  28. #include <LibJS/Runtime/NativeFunction.h>
  29. #include <LibJS/Runtime/PromiseCapability.h>
  30. #include <LibJS/Runtime/Reference.h>
  31. #include <LibJS/Runtime/Symbol.h>
  32. #include <LibJS/Runtime/Temporal/Instant.h>
  33. #include <LibJS/Runtime/VM.h>
  34. #include <LibJS/SourceTextModule.h>
  35. #include <LibJS/SyntheticModule.h>
  36. namespace JS {
  37. ErrorOr<NonnullRefPtr<VM>> VM::create(OwnPtr<CustomData> custom_data)
  38. {
  39. ErrorMessages error_messages {};
  40. error_messages[to_underlying(ErrorMessage::OutOfMemory)] = TRY(String::from_utf8(ErrorType::OutOfMemory.message()));
  41. auto vm = adopt_ref(*new VM(move(custom_data), move(error_messages)));
  42. WellKnownSymbols well_known_symbols {
  43. #define __JS_ENUMERATE(SymbolName, snake_name) \
  44. Symbol::create(*vm, "Symbol." #SymbolName##_string, false),
  45. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  46. #undef __JS_ENUMERATE
  47. };
  48. vm->set_well_known_symbols(move(well_known_symbols));
  49. return vm;
  50. }
  51. template<size_t... code_points>
  52. static constexpr auto make_single_ascii_character_strings(IndexSequence<code_points...>)
  53. {
  54. return AK::Array { (String::from_code_point(static_cast<u32>(code_points)))... };
  55. }
  56. static constexpr auto single_ascii_character_strings = make_single_ascii_character_strings(MakeIndexSequence<128>());
  57. VM::VM(OwnPtr<CustomData> custom_data, ErrorMessages error_messages)
  58. : m_heap(this, [this](HashMap<GC::Cell*, GC::HeapRoot>& roots) {
  59. gather_roots(roots);
  60. })
  61. , m_error_messages(move(error_messages))
  62. , m_custom_data(move(custom_data))
  63. {
  64. m_bytecode_interpreter = make<Bytecode::Interpreter>(*this);
  65. m_empty_string = m_heap.allocate<PrimitiveString>(String {});
  66. typeof_strings = {
  67. .number = m_heap.allocate<PrimitiveString>("number"),
  68. .undefined = m_heap.allocate<PrimitiveString>("undefined"),
  69. .object = m_heap.allocate<PrimitiveString>("object"),
  70. .string = m_heap.allocate<PrimitiveString>("string"),
  71. .symbol = m_heap.allocate<PrimitiveString>("symbol"),
  72. .boolean = m_heap.allocate<PrimitiveString>("boolean"),
  73. .bigint = m_heap.allocate<PrimitiveString>("bigint"),
  74. .function = m_heap.allocate<PrimitiveString>("function"),
  75. };
  76. for (size_t i = 0; i < single_ascii_character_strings.size(); ++i)
  77. m_single_ascii_character_strings[i] = m_heap.allocate<PrimitiveString>(single_ascii_character_strings[i]);
  78. // Default hook implementations. These can be overridden by the host, for example, LibWeb overrides the default hooks to place promise jobs on the microtask queue.
  79. host_promise_rejection_tracker = [this](Promise& promise, Promise::RejectionOperation operation) {
  80. promise_rejection_tracker(promise, operation);
  81. };
  82. host_call_job_callback = [this](JobCallback& job_callback, Value this_value, ReadonlySpan<Value> arguments) {
  83. return call_job_callback(*this, job_callback, this_value, arguments);
  84. };
  85. host_enqueue_finalization_registry_cleanup_job = [this](FinalizationRegistry& finalization_registry) {
  86. enqueue_finalization_registry_cleanup_job(finalization_registry);
  87. };
  88. host_enqueue_promise_job = [this](GC::Ref<GC::Function<ThrowCompletionOr<Value>()>> job, Realm* realm) {
  89. enqueue_promise_job(job, realm);
  90. };
  91. host_make_job_callback = [](FunctionObject& function_object) {
  92. return make_job_callback(function_object);
  93. };
  94. host_load_imported_module = [this](ImportedModuleReferrer referrer, ModuleRequest const& module_request, GC::Ptr<GraphLoadingState::HostDefined> load_state, ImportedModulePayload payload) -> void {
  95. return load_imported_module(referrer, module_request, load_state, move(payload));
  96. };
  97. host_get_import_meta_properties = [&](SourceTextModule const&) -> HashMap<PropertyKey, Value> {
  98. return {};
  99. };
  100. host_finalize_import_meta = [&](Object*, SourceTextModule const&) {
  101. };
  102. host_get_supported_import_attributes = [&] {
  103. return Vector<ByteString> { "type" };
  104. };
  105. // 19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, parameterStrings, bodyString, direct ), https://tc39.es/ecma262/#sec-hostensurecancompilestrings
  106. host_ensure_can_compile_strings = [](Realm&, ReadonlySpan<String>, StringView, EvalMode) -> ThrowCompletionOr<void> {
  107. // The host-defined abstract operation HostEnsureCanCompileStrings takes arguments calleeRealm (a Realm Record),
  108. // parameterStrings (a List of Strings), bodyString (a String), and direct (a Boolean) and returns either a normal
  109. // completion containing unused or a throw completion.
  110. //
  111. // It allows host environments to block certain ECMAScript functions which allow developers to compile strings into ECMAScript code.
  112. // An implementation of HostEnsureCanCompileStrings must conform to the following requirements:
  113. // - If the returned Completion Record is a normal completion, it must be a normal completion containing unused.
  114. // The default implementation of HostEnsureCanCompileStrings is to return NormalCompletion(unused).
  115. return {};
  116. };
  117. host_ensure_can_add_private_element = [](Object&) -> ThrowCompletionOr<void> {
  118. // The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument O (an Object)
  119. // and returns either a normal completion containing unused or a throw completion.
  120. // It allows host environments to prevent the addition of private elements to particular host-defined exotic objects.
  121. // An implementation of HostEnsureCanAddPrivateElement must conform to the following requirements:
  122. // - If O is not a host-defined exotic object, this abstract operation must return NormalCompletion(unused) and perform no other steps.
  123. // - Any two calls of this abstract operation with the same argument must return the same kind of Completion Record.
  124. // The default implementation of HostEnsureCanAddPrivateElement is to return NormalCompletion(unused).
  125. return {};
  126. // This abstract operation is only invoked by ECMAScript hosts that are web browsers.
  127. // NOTE: Since LibJS has no way of knowing whether the current environment is a browser we always
  128. // call HostEnsureCanAddPrivateElement when needed.
  129. };
  130. // 25.1.3.8 HostResizeArrayBuffer ( buffer, newByteLength ), https://tc39.es/ecma262/#sec-hostresizearraybuffer
  131. host_resize_array_buffer = [this](ArrayBuffer& buffer, size_t new_byte_length) -> ThrowCompletionOr<HandledByHost> {
  132. // The host-defined abstract operation HostResizeArrayBuffer takes arguments buffer (an ArrayBuffer) and
  133. // newByteLength (a non-negative integer) and returns either a normal completion containing either handled or
  134. // unhandled, or a throw completion. It gives the host an opportunity to perform implementation-defined resizing
  135. // of buffer. If the host chooses not to handle resizing of buffer, it may return unhandled for the default behaviour.
  136. // The implementation of HostResizeArrayBuffer must conform to the following requirements:
  137. // - The abstract operation does not detach buffer.
  138. // - If the abstract operation completes normally with handled, buffer.[[ArrayBufferByteLength]] is newByteLength.
  139. // The default implementation of HostResizeArrayBuffer is to return NormalCompletion(unhandled).
  140. if (auto result = buffer.buffer().try_resize(new_byte_length, ByteBuffer::ZeroFillNewElements::Yes); result.is_error())
  141. return throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, new_byte_length);
  142. return HandledByHost::Handled;
  143. };
  144. // 3.6.1 HostInitializeShadowRealm ( realm, context, O ), https://tc39.es/proposal-shadowrealm/#sec-hostinitializeshadowrealm
  145. host_initialize_shadow_realm = [](Realm&, NonnullOwnPtr<ExecutionContext>, ShadowRealm&) -> ThrowCompletionOr<void> {
  146. // The host-defined abstract operation HostInitializeShadowRealm takes arguments realm (a Realm Record),
  147. // context (an execution context), and O (a ShadowRealm object) and returns either a normal completion
  148. // containing unused or a throw completion. It is used to inform the host of any newly created realms
  149. // from the ShadowRealm constructor. The idea of this hook is to initialize host data structures related
  150. // to the ShadowRealm, e.g., for module loading.
  151. //
  152. // The host may use this hook to add properties to the ShadowRealm's global object. Those properties must be configurable.
  153. return {};
  154. };
  155. // 2.3.1 HostSystemUTCEpochNanoseconds ( global ), https://tc39.es/proposal-temporal/#sec-hostsystemutcepochnanoseconds
  156. host_system_utc_epoch_nanoseconds = [](Object const&) {
  157. // 1. Let ns be the approximate current UTC date and time, in nanoseconds since the epoch.
  158. Crypto::SignedBigInteger nanoseconds { AK::UnixDateTime::now().nanoseconds_since_epoch() };
  159. // 2. Return the result of clamping ns between nsMinInstant and nsMaxInstant.
  160. if (nanoseconds < Temporal::NANOSECONDS_MIN_INSTANT)
  161. nanoseconds = Temporal::NANOSECONDS_MIN_INSTANT;
  162. if (nanoseconds > Temporal::NANOSECONDS_MAX_INSTANT)
  163. nanoseconds = Temporal::NANOSECONDS_MAX_INSTANT;
  164. return nanoseconds;
  165. };
  166. // AD-HOC: Inform the host that we received a date string we were unable to parse.
  167. host_unrecognized_date_string = [](StringView) {
  168. };
  169. }
  170. VM::~VM() = default;
  171. String const& VM::error_message(ErrorMessage type) const
  172. {
  173. VERIFY(type < ErrorMessage::__Count);
  174. auto const& message = m_error_messages[to_underlying(type)];
  175. VERIFY(!message.is_empty());
  176. return message;
  177. }
  178. Bytecode::Interpreter& VM::bytecode_interpreter()
  179. {
  180. return *m_bytecode_interpreter;
  181. }
  182. struct ExecutionContextRootsCollector : public Cell::Visitor {
  183. virtual void visit_impl(GC::Cell& cell) override
  184. {
  185. roots.set(&cell);
  186. }
  187. virtual void visit_possible_values(ReadonlyBytes) override
  188. {
  189. VERIFY_NOT_REACHED();
  190. }
  191. HashTable<GC::Ptr<GC::Cell>> roots;
  192. };
  193. void VM::gather_roots(HashMap<GC::Cell*, GC::HeapRoot>& roots)
  194. {
  195. roots.set(m_empty_string, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  196. for (auto string : m_single_ascii_character_strings)
  197. roots.set(string, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  198. roots.set(typeof_strings.number, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  199. roots.set(typeof_strings.undefined, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  200. roots.set(typeof_strings.object, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  201. roots.set(typeof_strings.string, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  202. roots.set(typeof_strings.symbol, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  203. roots.set(typeof_strings.boolean, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  204. roots.set(typeof_strings.bigint, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  205. roots.set(typeof_strings.function, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  206. #define __JS_ENUMERATE(SymbolName, snake_name) \
  207. roots.set(m_well_known_symbols.snake_name, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  208. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  209. #undef __JS_ENUMERATE
  210. for (auto& symbol : m_global_symbol_registry)
  211. roots.set(symbol.value, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  212. for (auto finalization_registry : m_finalization_registry_cleanup_jobs)
  213. roots.set(finalization_registry, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  214. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  215. for (auto const& execution_context : stack) {
  216. ExecutionContextRootsCollector visitor;
  217. execution_context->visit_edges(visitor);
  218. for (auto cell : visitor.roots)
  219. roots.set(cell, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  220. }
  221. };
  222. gather_roots_from_execution_context_stack(m_execution_context_stack);
  223. for (auto& saved_stack : m_saved_execution_context_stacks)
  224. gather_roots_from_execution_context_stack(saved_stack);
  225. for (auto& job : m_promise_jobs)
  226. roots.set(job, GC::HeapRoot { .type = GC::HeapRoot::Type::VM });
  227. }
  228. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  229. ThrowCompletionOr<Reference> VM::get_identifier_reference(Environment* environment, DeprecatedFlyString name, bool strict, size_t hops)
  230. {
  231. // 1. If env is the value null, then
  232. if (!environment) {
  233. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  234. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  235. }
  236. // 2. Let exists be ? env.HasBinding(name).
  237. Optional<size_t> index;
  238. auto exists = TRY(environment->has_binding(name, &index));
  239. // Note: This is an optimization for looking up the same reference.
  240. Optional<EnvironmentCoordinate> environment_coordinate;
  241. if (index.has_value()) {
  242. VERIFY(hops <= NumericLimits<u32>::max());
  243. VERIFY(index.value() <= NumericLimits<u32>::max());
  244. environment_coordinate = EnvironmentCoordinate { .hops = static_cast<u32>(hops), .index = static_cast<u32>(index.value()) };
  245. }
  246. // 3. If exists is true, then
  247. if (exists) {
  248. // a. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  249. return Reference { *environment, move(name), strict, environment_coordinate };
  250. }
  251. // 4. Else,
  252. else {
  253. // a. Let outer be env.[[OuterEnv]].
  254. // b. Return ? GetIdentifierReference(outer, name, strict).
  255. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  256. }
  257. }
  258. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  259. ThrowCompletionOr<Reference> VM::resolve_binding(DeprecatedFlyString const& name, Environment* environment)
  260. {
  261. // 1. If env is not present or if env is undefined, then
  262. if (!environment) {
  263. // a. Set env to the running execution context's LexicalEnvironment.
  264. environment = running_execution_context().lexical_environment;
  265. }
  266. // 2. Assert: env is an Environment Record.
  267. VERIFY(environment);
  268. // 3. If the source text matched by the syntactic production that is being evaluated is contained in strict mode code, let strict be true; else let strict be false.
  269. bool strict = in_strict_mode();
  270. // 4. Return ? GetIdentifierReference(env, name, strict).
  271. return get_identifier_reference(environment, name, strict);
  272. // NOTE: The spec says:
  273. // Note: The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
  274. // But this is not actually correct as GetIdentifierReference (or really the methods it calls) can throw.
  275. }
  276. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  277. ThrowCompletionOr<Value> VM::resolve_this_binding()
  278. {
  279. auto& vm = *this;
  280. // 1. Let envRec be GetThisEnvironment().
  281. auto environment = get_this_environment(vm);
  282. // 2. Return ? envRec.GetThisBinding().
  283. return TRY(environment->get_this_binding(vm));
  284. }
  285. // 9.4.5 GetNewTarget ( ), https://tc39.es/ecma262/#sec-getnewtarget
  286. Value VM::get_new_target()
  287. {
  288. // 1. Let envRec be GetThisEnvironment().
  289. auto env = get_this_environment(*this);
  290. // 2. Assert: envRec has a [[NewTarget]] field.
  291. // 3. Return envRec.[[NewTarget]].
  292. return verify_cast<FunctionEnvironment>(*env).new_target();
  293. }
  294. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  295. // ImportMeta branch only
  296. Object* VM::get_import_meta()
  297. {
  298. // 1. Let module be GetActiveScriptOrModule().
  299. auto script_or_module = get_active_script_or_module();
  300. // 2. Assert: module is a Source Text Module Record.
  301. auto& module = verify_cast<SourceTextModule>(*script_or_module.get<GC::Ref<Module>>());
  302. // 3. Let importMeta be module.[[ImportMeta]].
  303. auto* import_meta = module.import_meta();
  304. // 4. If importMeta is empty, then
  305. if (import_meta == nullptr) {
  306. // a. Set importMeta to OrdinaryObjectCreate(null).
  307. import_meta = Object::create(*current_realm(), nullptr);
  308. // b. Let importMetaValues be HostGetImportMetaProperties(module).
  309. auto import_meta_values = host_get_import_meta_properties(module);
  310. // c. For each Record { [[Key]], [[Value]] } p of importMetaValues, do
  311. for (auto& entry : import_meta_values) {
  312. // i. Perform ! CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]).
  313. MUST(import_meta->create_data_property_or_throw(entry.key, entry.value));
  314. }
  315. // d. Perform HostFinalizeImportMeta(importMeta, module).
  316. host_finalize_import_meta(import_meta, module);
  317. // e. Set module.[[ImportMeta]] to importMeta.
  318. module.set_import_meta({}, import_meta);
  319. // f. Return importMeta.
  320. return import_meta;
  321. }
  322. // 5. Else,
  323. else {
  324. // a. Assert: Type(importMeta) is Object.
  325. // Note: This is always true by the type.
  326. // b. Return importMeta.
  327. return import_meta;
  328. }
  329. }
  330. // 9.4.5 GetGlobalObject ( ), https://tc39.es/ecma262/#sec-getglobalobject
  331. Object& VM::get_global_object()
  332. {
  333. // 1. Let currentRealm be the current Realm Record.
  334. auto& current_realm = *this->current_realm();
  335. // 2. Return currentRealm.[[GlobalObject]].
  336. return current_realm.global_object();
  337. }
  338. bool VM::in_strict_mode() const
  339. {
  340. if (execution_context_stack().is_empty())
  341. return false;
  342. return running_execution_context().is_strict_mode;
  343. }
  344. void VM::run_queued_promise_jobs()
  345. {
  346. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  347. while (!m_promise_jobs.is_empty()) {
  348. auto job = m_promise_jobs.take_first();
  349. dbgln_if(PROMISE_DEBUG, "Calling promise job function");
  350. [[maybe_unused]] auto result = job->function()();
  351. }
  352. }
  353. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  354. void VM::enqueue_promise_job(GC::Ref<GC::Function<ThrowCompletionOr<Value>()>> job, Realm*)
  355. {
  356. // An implementation of HostEnqueuePromiseJob must conform to the requirements in 9.5 as well as the following:
  357. // - FIXME: If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.
  358. // - FIXME: Let scriptOrModule be GetActiveScriptOrModule() at the time HostEnqueuePromiseJob is invoked. If realm is not null, each time job is invoked the implementation must perform implementation-defined steps
  359. // such that scriptOrModule is the active script or module at the time of job's invocation.
  360. // - Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
  361. m_promise_jobs.append(job);
  362. }
  363. void VM::run_queued_finalization_registry_cleanup_jobs()
  364. {
  365. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  366. auto registry = m_finalization_registry_cleanup_jobs.take_first();
  367. // FIXME: Handle any uncatched exceptions here.
  368. (void)registry->cleanup();
  369. }
  370. }
  371. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  372. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  373. {
  374. m_finalization_registry_cleanup_jobs.append(&registry);
  375. }
  376. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  377. void VM::promise_rejection_tracker(Promise& promise, Promise::RejectionOperation operation) const
  378. {
  379. switch (operation) {
  380. case Promise::RejectionOperation::Reject:
  381. // A promise was rejected without any handlers
  382. if (on_promise_unhandled_rejection)
  383. on_promise_unhandled_rejection(promise);
  384. break;
  385. case Promise::RejectionOperation::Handle:
  386. // A handler was added to an already rejected promise
  387. if (on_promise_rejection_handled)
  388. on_promise_rejection_handled(promise);
  389. break;
  390. default:
  391. VERIFY_NOT_REACHED();
  392. }
  393. }
  394. void VM::dump_backtrace() const
  395. {
  396. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  397. auto& frame = m_execution_context_stack[i];
  398. if (frame->executable && frame->program_counter.has_value()) {
  399. auto source_range = frame->executable->source_range_at(frame->program_counter.value()).realize();
  400. dbgln("-> {} @ {}:{},{}", frame->function_name ? frame->function_name->utf8_string() : ""_string, source_range.filename(), source_range.start.line, source_range.start.column);
  401. } else {
  402. dbgln("-> {}", frame->function_name ? frame->function_name->utf8_string() : ""_string);
  403. }
  404. }
  405. }
  406. void VM::save_execution_context_stack()
  407. {
  408. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  409. }
  410. void VM::clear_execution_context_stack()
  411. {
  412. m_execution_context_stack.clear_with_capacity();
  413. }
  414. void VM::restore_execution_context_stack()
  415. {
  416. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  417. }
  418. // 9.4.1 GetActiveScriptOrModule ( ), https://tc39.es/ecma262/#sec-getactivescriptormodule
  419. ScriptOrModule VM::get_active_script_or_module() const
  420. {
  421. // 1. If the execution context stack is empty, return null.
  422. if (m_execution_context_stack.is_empty())
  423. return Empty {};
  424. // 2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
  425. for (auto i = m_execution_context_stack.size() - 1; i > 0; i--) {
  426. if (!m_execution_context_stack[i]->script_or_module.has<Empty>())
  427. return m_execution_context_stack[i]->script_or_module;
  428. }
  429. // 3. If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule.
  430. // Note: Since it is not empty we have 0 and since we got here all the
  431. // above contexts don't have a non-null ScriptOrModule
  432. return m_execution_context_stack[0]->script_or_module;
  433. }
  434. VM::StoredModule* VM::get_stored_module(ImportedModuleReferrer const&, ByteString const& filename, ByteString const&)
  435. {
  436. // Note the spec says:
  437. // If this operation is called multiple times with the same (referrer, specifier) pair and it performs
  438. // FinishLoadingImportedModule(referrer, specifier, payload, result) where result is a normal completion,
  439. // then it must perform FinishLoadingImportedModule(referrer, specifier, payload, result) with the same result each time.
  440. // Editor's Note from https://tc39.es/proposal-json-modules/#sec-hostresolveimportedmodule
  441. // The above text implies that is recommended but not required that hosts do not use moduleRequest.[[Assertions]]
  442. // as part of the module cache key. In either case, an exception thrown from an import with a given assertion list
  443. // does not rule out success of another import with the same specifier but a different assertion list.
  444. // FIXME: This should probably check referrer as well.
  445. auto end_or_module = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  446. return stored_module.filename == filename;
  447. });
  448. if (end_or_module.is_end())
  449. return nullptr;
  450. return &(*end_or_module);
  451. }
  452. ThrowCompletionOr<void> VM::link_and_eval_module(Badge<Bytecode::Interpreter>, SourceTextModule& module)
  453. {
  454. return link_and_eval_module(module);
  455. }
  456. ThrowCompletionOr<void> VM::link_and_eval_module(CyclicModule& module)
  457. {
  458. auto filename = module.filename();
  459. module.load_requested_modules(nullptr);
  460. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking module {}", filename);
  461. auto linked_or_error = module.link(*this);
  462. if (linked_or_error.is_error())
  463. return linked_or_error.throw_completion();
  464. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking passed, now evaluating module {}", filename);
  465. auto evaluated_or_error = module.evaluate(*this);
  466. if (evaluated_or_error.is_error())
  467. return evaluated_or_error.throw_completion();
  468. auto* evaluated_value = evaluated_or_error.value();
  469. run_queued_promise_jobs();
  470. VERIFY(m_promise_jobs.is_empty());
  471. // FIXME: This will break if we start doing promises actually asynchronously.
  472. VERIFY(evaluated_value->state() != Promise::State::Pending);
  473. if (evaluated_value->state() == Promise::State::Rejected)
  474. return JS::throw_completion(evaluated_value->result());
  475. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Evaluating passed for module {}", module.filename());
  476. return {};
  477. }
  478. static ByteString resolve_module_filename(StringView filename, StringView module_type)
  479. {
  480. auto extensions = Vector<StringView, 2> { "js"sv, "mjs"sv };
  481. if (module_type == "json"sv)
  482. extensions = { "json"sv };
  483. if (!FileSystem::exists(filename)) {
  484. for (auto extension : extensions) {
  485. // import "./foo" -> import "./foo.ext"
  486. auto resolved_filepath = ByteString::formatted("{}.{}", filename, extension);
  487. if (FileSystem::exists(resolved_filepath))
  488. return resolved_filepath;
  489. }
  490. } else if (FileSystem::is_directory(filename)) {
  491. for (auto extension : extensions) {
  492. // import "./foo" -> import "./foo/index.ext"
  493. auto resolved_filepath = LexicalPath::join(filename, ByteString::formatted("index.{}", extension)).string();
  494. if (FileSystem::exists(resolved_filepath))
  495. return resolved_filepath;
  496. }
  497. }
  498. return filename;
  499. }
  500. // 16.2.1.8 HostLoadImportedModule ( referrer, specifier, hostDefined, payload ), https://tc39.es/ecma262/#sec-HostLoadImportedModule
  501. void VM::load_imported_module(ImportedModuleReferrer referrer, ModuleRequest const& module_request, GC::Ptr<GraphLoadingState::HostDefined>, ImportedModulePayload payload)
  502. {
  503. // An implementation of HostLoadImportedModule must conform to the following requirements:
  504. //
  505. // - The host environment must perform FinishLoadingImportedModule(referrer, specifier, payload, result),
  506. // where result is either a normal completion containing the loaded Module Record or a throw completion,
  507. // either synchronously or asynchronously.
  508. // - If this operation is called multiple times with the same (referrer, specifier) pair and it performs
  509. // FinishLoadingImportedModule(referrer, specifier, payload, result) where result is a normal completion,
  510. // then it must perform FinishLoadingImportedModule(referrer, specifier, payload, result) with the same result each time.
  511. // - The operation must treat payload as an opaque value to be passed through to FinishLoadingImportedModule.
  512. //
  513. // The actual process performed is host-defined, but typically consists of performing whatever I/O operations are necessary to
  514. // load the appropriate Module Record. Multiple different (referrer, specifier) pairs may map to the same Module Record instance.
  515. // The actual mapping semantics is host-defined but typically a normalization process is applied to specifier as part of the
  516. // mapping process. A typical normalization process would include actions such as expansion of relative and abbreviated path specifiers.
  517. // Here we check, against the spec, if payload is a promise capability, meaning that this was called for a dynamic import
  518. if (payload.has<GC::Ref<PromiseCapability>>() && !m_dynamic_imports_allowed) {
  519. // If you are here because you want to enable dynamic module importing make sure it won't be a security problem
  520. // by checking the default implementation of HostImportModuleDynamically and creating your own hook or calling
  521. // vm.allow_dynamic_imports().
  522. finish_loading_imported_module(referrer, module_request, payload, throw_completion<InternalError>(ErrorType::DynamicImportNotAllowed, module_request.module_specifier));
  523. return;
  524. }
  525. ByteString module_type;
  526. for (auto& attribute : module_request.attributes) {
  527. if (attribute.key == "type"sv) {
  528. module_type = attribute.value;
  529. break;
  530. }
  531. }
  532. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module at {} has type {}", module_request.module_specifier, module_type);
  533. StringView const base_filename = referrer.visit(
  534. [&](GC::Ref<Realm> const&) {
  535. // Generally within ECMA262 we always get a referencing_script_or_module. However, ShadowRealm gives an explicit null.
  536. // To get around this is we attempt to get the active script_or_module otherwise we might start loading "random" files from the working directory.
  537. return get_active_script_or_module().visit(
  538. [](Empty) {
  539. return "."sv;
  540. },
  541. [](auto const& script_or_module) {
  542. return script_or_module->filename();
  543. });
  544. },
  545. [&](auto const& script_or_module) {
  546. return script_or_module->filename();
  547. });
  548. LexicalPath base_path { base_filename };
  549. auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier);
  550. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] base path: '{}'", base_path);
  551. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] initial filename: '{}'", filename);
  552. filename = resolve_module_filename(filename, module_type);
  553. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved filename: '{}'", filename);
  554. #if JS_MODULE_DEBUG
  555. ByteString referencing_module_string = referrer.visit(
  556. [&](Empty) -> ByteString {
  557. return ".";
  558. },
  559. [&](auto& script_or_module) {
  560. if constexpr (IsSame<Script*, decltype(script_or_module)>) {
  561. return ByteString::formatted("Script @ {}", script_or_module.ptr());
  562. }
  563. return ByteString::formatted("Module @ {}", script_or_module.ptr());
  564. });
  565. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] load_imported_module({}, {})", referencing_module_string, filename);
  566. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved {} + {} -> {}", base_path, module_request.module_specifier, filename);
  567. #endif
  568. auto* loaded_module_or_end = get_stored_module(referrer, filename, module_type);
  569. if (loaded_module_or_end != nullptr) {
  570. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] load_imported_module({}) already loaded at {}", filename, loaded_module_or_end->module.ptr());
  571. finish_loading_imported_module(referrer, module_request, payload, *loaded_module_or_end->module);
  572. return;
  573. }
  574. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing module {}", filename);
  575. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  576. if (file_or_error.is_error()) {
  577. finish_loading_imported_module(referrer, module_request, payload, throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier));
  578. return;
  579. }
  580. // FIXME: Don't read the file in one go.
  581. auto file_content_or_error = file_or_error.value()->read_until_eof();
  582. if (file_content_or_error.is_error()) {
  583. if (file_content_or_error.error().code() == ENOMEM) {
  584. finish_loading_imported_module(referrer, module_request, payload, throw_completion<JS::InternalError>(error_message(::JS::VM::ErrorMessage::OutOfMemory)));
  585. return;
  586. }
  587. finish_loading_imported_module(referrer, module_request, payload, throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier));
  588. return;
  589. }
  590. StringView const content_view { file_content_or_error.value().bytes() };
  591. auto module = [&]() -> ThrowCompletionOr<GC::Ref<Module>> {
  592. // If assertions has an entry entry such that entry.[[Key]] is "type", let type be entry.[[Value]]. The following requirements apply:
  593. // If type is "json", then this algorithm must either invoke ParseJSONModule and return the resulting Completion Record, or throw an exception.
  594. if (module_type == "json"sv) {
  595. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing JSON module {}", filename);
  596. return parse_json_module(content_view, *current_realm(), filename);
  597. }
  598. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing as SourceTextModule module {}", filename);
  599. // Note: We treat all files as module, so if a script does not have exports it just runs it.
  600. auto module_or_errors = SourceTextModule::parse(content_view, *current_realm(), filename);
  601. if (module_or_errors.is_error()) {
  602. VERIFY(module_or_errors.error().size() > 0);
  603. return throw_completion<SyntaxError>(module_or_errors.error().first().to_byte_string());
  604. }
  605. auto module = module_or_errors.release_value();
  606. m_loaded_modules.empend(
  607. referrer,
  608. module->filename(),
  609. ByteString {}, // Null type
  610. make_root<Module>(*module),
  611. true);
  612. return module;
  613. }();
  614. finish_loading_imported_module(referrer, module_request, payload, module);
  615. }
  616. void VM::push_execution_context(ExecutionContext& context)
  617. {
  618. if (!m_execution_context_stack.is_empty())
  619. m_execution_context_stack.last()->program_counter = bytecode_interpreter().program_counter();
  620. m_execution_context_stack.append(&context);
  621. }
  622. void VM::pop_execution_context()
  623. {
  624. m_execution_context_stack.take_last();
  625. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  626. on_call_stack_emptied();
  627. }
  628. #if ARCH(X86_64)
  629. struct [[gnu::packed]] NativeStackFrame {
  630. NativeStackFrame* prev;
  631. FlatPtr return_address;
  632. };
  633. #endif
  634. static RefPtr<CachedSourceRange> get_source_range(ExecutionContext const* context)
  635. {
  636. // native function
  637. if (!context->executable)
  638. return {};
  639. if (!context->program_counter.has_value())
  640. return {};
  641. if (!context->cached_source_range
  642. || context->cached_source_range->program_counter != context->program_counter.value()) {
  643. auto unrealized_source_range = context->executable->source_range_at(context->program_counter.value());
  644. context->cached_source_range = adopt_ref(*new CachedSourceRange(
  645. context->program_counter.value(),
  646. move(unrealized_source_range)));
  647. }
  648. return context->cached_source_range;
  649. }
  650. Vector<StackTraceElement> VM::stack_trace() const
  651. {
  652. Vector<StackTraceElement> stack_trace;
  653. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; i--) {
  654. auto* context = m_execution_context_stack[i];
  655. stack_trace.append({
  656. .execution_context = context,
  657. .source_range = get_source_range(context),
  658. });
  659. }
  660. return stack_trace;
  661. }
  662. }