VM.cpp 34 KB

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