VM.cpp 33 KB

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