VM.cpp 34 KB

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