VM.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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/JIT/NativeExecutable.h>
  18. #include <LibJS/Runtime/AbstractOperations.h>
  19. #include <LibJS/Runtime/Array.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<u32... code_points>
  50. static constexpr auto make_single_ascii_character_strings(IndexSequence<code_points...>)
  51. {
  52. return AK::Array { (String::from_code_point(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, MarkedVector<Value> arguments) {
  69. return call_job_callback(*this, job_callback, this_value, move(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](Function<ThrowCompletionOr<Value>()> job, Realm* realm) {
  75. enqueue_promise_job(move(job), realm);
  76. };
  77. host_make_job_callback = [](FunctionObject& function_object) {
  78. return make_job_callback(function_object);
  79. };
  80. host_resolve_imported_module = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier) {
  81. return resolve_imported_module(move(referencing_script_or_module), specifier);
  82. };
  83. host_import_module_dynamically = [&](ScriptOrModule, ModuleRequest const&, PromiseCapability const& promise_capability) -> ThrowCompletionOr<void> {
  84. // By default, we throw on dynamic imports this is to prevent arbitrary file access by scripts.
  85. VERIFY(current_realm());
  86. auto& realm = *current_realm();
  87. auto promise = Promise::create(realm);
  88. // If you are here because you want to enable dynamic module importing make sure it won't be a security problem
  89. // by checking the default implementation of HostImportModuleDynamically and creating your own hook or calling
  90. // vm.enable_default_host_import_module_dynamically_hook().
  91. promise->reject(Error::create(realm, ErrorType::DynamicImportNotAllowed.message()));
  92. promise->perform_then(
  93. NativeFunction::create(realm, "", [](auto&) -> ThrowCompletionOr<Value> {
  94. VERIFY_NOT_REACHED();
  95. }),
  96. NativeFunction::create(realm, "", [&promise_capability](auto& vm) -> ThrowCompletionOr<Value> {
  97. auto error = vm.argument(0);
  98. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « error »).
  99. MUST(call(vm, *promise_capability.reject(), js_undefined(), error));
  100. // b. Return undefined.
  101. return js_undefined();
  102. }),
  103. {});
  104. return {};
  105. };
  106. host_finish_dynamic_import = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier, PromiseCapability const& promise_capability, Promise* promise) {
  107. return finish_dynamic_import(move(referencing_script_or_module), specifier, promise_capability, promise);
  108. };
  109. host_get_import_meta_properties = [&](SourceTextModule const&) -> HashMap<PropertyKey, Value> {
  110. return {};
  111. };
  112. host_finalize_import_meta = [&](Object*, SourceTextModule const&) {
  113. };
  114. host_get_supported_import_assertions = [&] {
  115. return Vector<DeprecatedString> { "type" };
  116. };
  117. // 19.2.1.2 HostEnsureCanCompileStrings ( callerRealm, calleeRealm ), https://tc39.es/ecma262/#sec-hostensurecancompilestrings
  118. host_ensure_can_compile_strings = [](Realm&) -> ThrowCompletionOr<void> {
  119. // The host-defined abstract operation HostEnsureCanCompileStrings takes argument calleeRealm (a Realm Record)
  120. // and returns either a normal completion containing unused or a throw completion.
  121. // It allows host environments to block certain ECMAScript functions which allow developers to compile strings into ECMAScript code.
  122. // An implementation of HostEnsureCanCompileStrings must conform to the following requirements:
  123. // - If the returned Completion Record is a normal completion, it must be a normal completion containing unused.
  124. // The default implementation of HostEnsureCanCompileStrings is to return NormalCompletion(unused).
  125. return {};
  126. };
  127. host_ensure_can_add_private_element = [](Object&) -> ThrowCompletionOr<void> {
  128. // The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument O (an Object)
  129. // and returns either a normal completion containing unused or a throw completion.
  130. // It allows host environments to prevent the addition of private elements to particular host-defined exotic objects.
  131. // An implementation of HostEnsureCanAddPrivateElement must conform to the following requirements:
  132. // - If O is not a host-defined exotic object, this abstract operation must return NormalCompletion(unused) and perform no other steps.
  133. // - Any two calls of this abstract operation with the same argument must return the same kind of Completion Record.
  134. // The default implementation of HostEnsureCanAddPrivateElement is to return NormalCompletion(unused).
  135. return {};
  136. // This abstract operation is only invoked by ECMAScript hosts that are web browsers.
  137. // NOTE: Since LibJS has no way of knowing whether the current environment is a browser we always
  138. // call HostEnsureCanAddPrivateElement when needed.
  139. };
  140. }
  141. VM::~VM() = default;
  142. String const& VM::error_message(ErrorMessage type) const
  143. {
  144. VERIFY(type < ErrorMessage::__Count);
  145. auto const& message = m_error_messages[to_underlying(type)];
  146. VERIFY(!message.is_empty());
  147. return message;
  148. }
  149. void VM::enable_default_host_import_module_dynamically_hook()
  150. {
  151. host_import_module_dynamically = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier, PromiseCapability const& promise_capability) {
  152. return import_module_dynamically(move(referencing_script_or_module), specifier, promise_capability);
  153. };
  154. }
  155. Bytecode::Interpreter& VM::bytecode_interpreter()
  156. {
  157. return *m_bytecode_interpreter;
  158. }
  159. void VM::gather_roots(HashMap<Cell*, HeapRoot>& roots)
  160. {
  161. roots.set(m_empty_string, HeapRoot { .type = HeapRoot::Type::VM });
  162. for (auto string : m_single_ascii_character_strings)
  163. roots.set(string, HeapRoot { .type = HeapRoot::Type::VM });
  164. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  165. for (auto& execution_context : stack) {
  166. if (execution_context->this_value.is_cell())
  167. roots.set(&execution_context->this_value.as_cell(), { .type = HeapRoot::Type::VM });
  168. for (auto& argument : execution_context->arguments) {
  169. if (argument.is_cell())
  170. roots.set(&argument.as_cell(), HeapRoot { .type = HeapRoot::Type::VM });
  171. }
  172. roots.set(execution_context->lexical_environment, HeapRoot { .type = HeapRoot::Type::VM });
  173. roots.set(execution_context->variable_environment, HeapRoot { .type = HeapRoot::Type::VM });
  174. roots.set(execution_context->private_environment, HeapRoot { .type = HeapRoot::Type::VM });
  175. if (auto context_owner = execution_context->context_owner)
  176. roots.set(context_owner, HeapRoot { .type = HeapRoot::Type::VM });
  177. execution_context->script_or_module.visit(
  178. [](Empty) {},
  179. [&](auto& script_or_module) {
  180. roots.set(script_or_module.ptr(), HeapRoot { .type = HeapRoot::Type::VM });
  181. });
  182. }
  183. };
  184. gather_roots_from_execution_context_stack(m_execution_context_stack);
  185. for (auto& saved_stack : m_saved_execution_context_stacks)
  186. gather_roots_from_execution_context_stack(saved_stack);
  187. #define __JS_ENUMERATE(SymbolName, snake_name) \
  188. roots.set(m_well_known_symbols.snake_name, HeapRoot { .type = HeapRoot::Type::VM });
  189. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  190. #undef __JS_ENUMERATE
  191. for (auto& symbol : m_global_symbol_registry)
  192. roots.set(symbol.value, HeapRoot { .type = HeapRoot::Type::VM });
  193. for (auto finalization_registry : m_finalization_registry_cleanup_jobs)
  194. roots.set(finalization_registry, HeapRoot { .type = HeapRoot::Type::VM });
  195. }
  196. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(ASTNode const& expression, DeprecatedFlyString const& name)
  197. {
  198. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  199. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  200. if (is<FunctionExpression>(expression)) {
  201. auto& function = static_cast<FunctionExpression const&>(expression);
  202. if (!function.has_name()) {
  203. return function.instantiate_ordinary_function_expression(*this, name);
  204. }
  205. } else if (is<ClassExpression>(expression)) {
  206. auto& class_expression = static_cast<ClassExpression const&>(expression);
  207. if (!class_expression.has_name()) {
  208. return TRY(class_expression.class_definition_evaluation(*this, {}, name));
  209. }
  210. }
  211. return execute_ast_node(expression);
  212. }
  213. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  214. ThrowCompletionOr<void> VM::binding_initialization(DeprecatedFlyString const& target, Value value, Environment* environment)
  215. {
  216. // 1. Let name be StringValue of Identifier.
  217. // 2. Return ? InitializeBoundName(name, value, environment).
  218. return initialize_bound_name(*this, target, value, environment);
  219. }
  220. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  221. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern const> const& target, Value value, Environment* environment)
  222. {
  223. auto& vm = *this;
  224. // BindingPattern : ObjectBindingPattern
  225. if (target->kind == BindingPattern::Kind::Object) {
  226. // 1. Perform ? RequireObjectCoercible(value).
  227. TRY(require_object_coercible(vm, value));
  228. // 2. Return ? BindingInitialization of ObjectBindingPattern with arguments value and environment.
  229. // BindingInitialization of ObjectBindingPattern
  230. // 1. Perform ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
  231. TRY(property_binding_initialization(*target, value, environment));
  232. // 2. Return unused.
  233. return {};
  234. }
  235. // BindingPattern : ArrayBindingPattern
  236. else {
  237. // 1. Let iteratorRecord be ? GetIterator(value, sync).
  238. auto iterator_record = TRY(get_iterator(vm, value, IteratorHint::Sync));
  239. // 2. Let result be Completion(IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment).
  240. auto result = iterator_binding_initialization(*target, iterator_record, environment);
  241. // 3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  242. if (!iterator_record.done) {
  243. // iterator_close() always returns a Completion, which ThrowCompletionOr will interpret as a throw
  244. // completion. So only return the result of iterator_close() if it is indeed a throw completion.
  245. auto completion = result.is_throw_completion() ? result.release_error() : normal_completion({});
  246. if (completion = iterator_close(vm, iterator_record, move(completion)); completion.is_error())
  247. return completion.release_error();
  248. }
  249. // 4. Return ? result.
  250. return result;
  251. }
  252. }
  253. ThrowCompletionOr<Value> VM::execute_ast_node(ASTNode const& node)
  254. {
  255. auto executable = TRY(Bytecode::compile(*this, node, FunctionKind::Normal, ""sv));
  256. auto result_or_error = bytecode_interpreter().run_and_return_frame(*executable, nullptr);
  257. if (result_or_error.value.is_error())
  258. return result_or_error.value.release_error();
  259. return result_or_error.frame->registers[0];
  260. }
  261. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  262. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  263. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment)
  264. {
  265. auto& vm = *this;
  266. auto& realm = *vm.current_realm();
  267. auto object = TRY(value.to_object(vm));
  268. HashTable<PropertyKey> seen_names;
  269. for (auto& property : binding.entries) {
  270. VERIFY(!property.is_elision());
  271. if (property.is_rest) {
  272. Reference assignment_target;
  273. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier const>>()) {
  274. assignment_target = TRY(resolve_binding((*identifier_ptr)->string(), environment));
  275. } else {
  276. VERIFY_NOT_REACHED();
  277. }
  278. auto rest_object = Object::create(realm, realm.intrinsics().object_prototype());
  279. VERIFY(rest_object);
  280. TRY(rest_object->copy_data_properties(vm, object, seen_names));
  281. if (!environment)
  282. return assignment_target.put_value(vm, rest_object);
  283. else
  284. return assignment_target.initialize_referenced_binding(vm, rest_object);
  285. }
  286. auto name = TRY(property.name.visit(
  287. [&](Empty) -> ThrowCompletionOr<PropertyKey> { VERIFY_NOT_REACHED(); },
  288. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<PropertyKey> {
  289. return identifier->string();
  290. },
  291. [&](NonnullRefPtr<Expression const> const& expression) -> ThrowCompletionOr<PropertyKey> {
  292. auto result = TRY(execute_ast_node(*expression));
  293. return result.to_property_key(vm);
  294. }));
  295. seen_names.set(name);
  296. if (property.name.has<NonnullRefPtr<Identifier const>>() && property.alias.has<Empty>()) {
  297. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  298. auto& identifier = *property.name.get<NonnullRefPtr<Identifier const>>();
  299. auto reference = TRY(resolve_binding(identifier.string(), environment));
  300. auto value_to_assign = TRY(object->get(name));
  301. if (property.initializer && value_to_assign.is_undefined()) {
  302. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, identifier.string()));
  303. }
  304. if (!environment)
  305. TRY(reference.put_value(vm, value_to_assign));
  306. else
  307. TRY(reference.initialize_referenced_binding(vm, value_to_assign));
  308. continue;
  309. }
  310. auto reference_to_assign_to = TRY(property.alias.visit(
  311. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  312. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  313. return TRY(resolve_binding(identifier->string(), environment));
  314. },
  315. [&](NonnullRefPtr<BindingPattern const> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  316. [&](NonnullRefPtr<MemberExpression const> const&) -> ThrowCompletionOr<Optional<Reference>> {
  317. VERIFY_NOT_REACHED();
  318. }));
  319. auto value_to_assign = TRY(object->get(name));
  320. if (property.initializer && value_to_assign.is_undefined()) {
  321. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier const>>())
  322. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, (*identifier_ptr)->string()));
  323. else
  324. value_to_assign = TRY(execute_ast_node(*property.initializer));
  325. }
  326. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern const>>()) {
  327. TRY(binding_initialization(*binding_ptr, value_to_assign, environment));
  328. } else {
  329. VERIFY(reference_to_assign_to.has_value());
  330. if (!environment)
  331. TRY(reference_to_assign_to->put_value(vm, value_to_assign));
  332. else
  333. TRY(reference_to_assign_to->initialize_referenced_binding(vm, value_to_assign));
  334. }
  335. }
  336. return {};
  337. }
  338. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  339. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  340. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, IteratorRecord& iterator_record, Environment* environment)
  341. {
  342. auto& vm = *this;
  343. auto& realm = *vm.current_realm();
  344. // FIXME: this method is nearly identical to destructuring assignment!
  345. for (size_t i = 0; i < binding.entries.size(); i++) {
  346. auto& entry = binding.entries[i];
  347. Value value;
  348. auto assignment_target = TRY(entry.alias.visit(
  349. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  350. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  351. return TRY(resolve_binding(identifier->string(), environment));
  352. },
  353. [&](NonnullRefPtr<BindingPattern const> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  354. [&](NonnullRefPtr<MemberExpression const> const&) -> ThrowCompletionOr<Optional<Reference>> {
  355. VERIFY_NOT_REACHED();
  356. }));
  357. // BindingRestElement : ... BindingIdentifier
  358. // BindingRestElement : ... BindingPattern
  359. if (entry.is_rest) {
  360. VERIFY(i == binding.entries.size() - 1);
  361. // 2. Let A be ! ArrayCreate(0).
  362. auto array = MUST(Array::create(realm, 0));
  363. // 3. Let n be 0.
  364. // 4. Repeat,
  365. while (true) {
  366. ThrowCompletionOr<GCPtr<Object>> next { nullptr };
  367. // a. If iteratorRecord.[[Done]] is false, then
  368. if (!iterator_record.done) {
  369. // i. Let next be Completion(IteratorStep(iteratorRecord)).
  370. next = iterator_step(vm, iterator_record);
  371. // ii. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  372. // iii. ReturnIfAbrupt(next).
  373. if (next.is_error()) {
  374. iterator_record.done = true;
  375. return next.release_error();
  376. }
  377. // iv. If next is false, set iteratorRecord.[[Done]] to true.
  378. if (!next.value())
  379. iterator_record.done = true;
  380. }
  381. // b. If iteratorRecord.[[Done]] is true, then
  382. if (iterator_record.done) {
  383. // NOTE: Step i. and ii. are handled below.
  384. break;
  385. }
  386. // c. Let nextValue be Completion(IteratorValue(next)).
  387. auto next_value = iterator_value(vm, *next.value());
  388. // d. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  389. // e. ReturnIfAbrupt(nextValue).
  390. if (next_value.is_error()) {
  391. iterator_record.done = true;
  392. return next_value.release_error();
  393. }
  394. // f. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
  395. array->indexed_properties().append(next_value.value());
  396. // g. Set n to n + 1.
  397. }
  398. value = array;
  399. }
  400. // SingleNameBinding : BindingIdentifier Initializer[opt]
  401. // BindingElement : BindingPattern Initializer[opt]
  402. else {
  403. // 1. Let v be undefined.
  404. value = js_undefined();
  405. // 2. If iteratorRecord.[[Done]] is false, then
  406. if (!iterator_record.done) {
  407. // a. Let next be Completion(IteratorStep(iteratorRecord)).
  408. auto next = iterator_step(vm, iterator_record);
  409. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  410. // c. ReturnIfAbrupt(next).
  411. if (next.is_error()) {
  412. iterator_record.done = true;
  413. return next.release_error();
  414. }
  415. // d. If next is false, set iteratorRecord.[[Done]] to true.
  416. if (!next.value()) {
  417. iterator_record.done = true;
  418. }
  419. // e. Else,
  420. else {
  421. // i. Set v to Completion(IteratorValue(next)).
  422. auto value_or_error = iterator_value(vm, *next.value());
  423. // ii. If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
  424. // iii. ReturnIfAbrupt(v).
  425. if (value_or_error.is_throw_completion()) {
  426. iterator_record.done = true;
  427. return value_or_error.release_error();
  428. }
  429. value = value_or_error.release_value();
  430. }
  431. }
  432. // NOTE: Step 3. and 4. are handled below.
  433. }
  434. if (value.is_undefined() && entry.initializer) {
  435. VERIFY(!entry.is_rest);
  436. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier const>>())
  437. value = TRY(named_evaluation_if_anonymous_function(*entry.initializer, (*identifier_ptr)->string()));
  438. else
  439. value = TRY(execute_ast_node(*entry.initializer));
  440. }
  441. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern const>>()) {
  442. TRY(binding_initialization(*binding_ptr, value, environment));
  443. } else if (!entry.alias.has<Empty>()) {
  444. VERIFY(assignment_target.has_value());
  445. if (!environment)
  446. TRY(assignment_target->put_value(vm, value));
  447. else
  448. TRY(assignment_target->initialize_referenced_binding(vm, value));
  449. }
  450. }
  451. return {};
  452. }
  453. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  454. ThrowCompletionOr<Reference> VM::get_identifier_reference(Environment* environment, DeprecatedFlyString name, bool strict, size_t hops)
  455. {
  456. // 1. If env is the value null, then
  457. if (!environment) {
  458. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  459. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  460. }
  461. // 2. Let exists be ? env.HasBinding(name).
  462. Optional<size_t> index;
  463. auto exists = TRY(environment->has_binding(name, &index));
  464. // Note: This is an optimization for looking up the same reference.
  465. Optional<EnvironmentCoordinate> environment_coordinate;
  466. if (index.has_value()) {
  467. VERIFY(hops <= NumericLimits<u32>::max());
  468. VERIFY(index.value() <= NumericLimits<u32>::max());
  469. environment_coordinate = EnvironmentCoordinate { .hops = static_cast<u32>(hops), .index = static_cast<u32>(index.value()) };
  470. }
  471. // 3. If exists is true, then
  472. if (exists) {
  473. // a. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  474. return Reference { *environment, move(name), strict, environment_coordinate };
  475. }
  476. // 4. Else,
  477. else {
  478. // a. Let outer be env.[[OuterEnv]].
  479. // b. Return ? GetIdentifierReference(outer, name, strict).
  480. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  481. }
  482. }
  483. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  484. ThrowCompletionOr<Reference> VM::resolve_binding(DeprecatedFlyString const& name, Environment* environment)
  485. {
  486. // 1. If env is not present or if env is undefined, then
  487. if (!environment) {
  488. // a. Set env to the running execution context's LexicalEnvironment.
  489. environment = running_execution_context().lexical_environment;
  490. }
  491. // 2. Assert: env is an Environment Record.
  492. VERIFY(environment);
  493. // 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.
  494. bool strict = in_strict_mode();
  495. // 4. Return ? GetIdentifierReference(env, name, strict).
  496. return get_identifier_reference(environment, name, strict);
  497. // NOTE: The spec says:
  498. // Note: The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
  499. // But this is not actually correct as GetIdentifierReference (or really the methods it calls) can throw.
  500. }
  501. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  502. ThrowCompletionOr<Value> VM::resolve_this_binding()
  503. {
  504. auto& vm = *this;
  505. // 1. Let envRec be GetThisEnvironment().
  506. auto environment = get_this_environment(vm);
  507. // 2. Return ? envRec.GetThisBinding().
  508. return TRY(environment->get_this_binding(vm));
  509. }
  510. // 9.4.5 GetNewTarget ( ), https://tc39.es/ecma262/#sec-getnewtarget
  511. Value VM::get_new_target()
  512. {
  513. // 1. Let envRec be GetThisEnvironment().
  514. auto env = get_this_environment(*this);
  515. // 2. Assert: envRec has a [[NewTarget]] field.
  516. // 3. Return envRec.[[NewTarget]].
  517. return verify_cast<FunctionEnvironment>(*env).new_target();
  518. }
  519. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  520. // ImportMeta branch only
  521. Object* VM::get_import_meta()
  522. {
  523. // 1. Let module be GetActiveScriptOrModule().
  524. auto script_or_module = get_active_script_or_module();
  525. // 2. Assert: module is a Source Text Module Record.
  526. auto& module = verify_cast<SourceTextModule>(*script_or_module.get<NonnullGCPtr<Module>>());
  527. // 3. Let importMeta be module.[[ImportMeta]].
  528. auto* import_meta = module.import_meta();
  529. // 4. If importMeta is empty, then
  530. if (import_meta == nullptr) {
  531. // a. Set importMeta to OrdinaryObjectCreate(null).
  532. import_meta = Object::create(*current_realm(), nullptr);
  533. // b. Let importMetaValues be HostGetImportMetaProperties(module).
  534. auto import_meta_values = host_get_import_meta_properties(module);
  535. // c. For each Record { [[Key]], [[Value]] } p of importMetaValues, do
  536. for (auto& entry : import_meta_values) {
  537. // i. Perform ! CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]).
  538. MUST(import_meta->create_data_property_or_throw(entry.key, entry.value));
  539. }
  540. // d. Perform HostFinalizeImportMeta(importMeta, module).
  541. host_finalize_import_meta(import_meta, module);
  542. // e. Set module.[[ImportMeta]] to importMeta.
  543. module.set_import_meta({}, import_meta);
  544. // f. Return importMeta.
  545. return import_meta;
  546. }
  547. // 5. Else,
  548. else {
  549. // a. Assert: Type(importMeta) is Object.
  550. // Note: This is always true by the type.
  551. // b. Return importMeta.
  552. return import_meta;
  553. }
  554. }
  555. // 9.4.5 GetGlobalObject ( ), https://tc39.es/ecma262/#sec-getglobalobject
  556. Object& VM::get_global_object()
  557. {
  558. // 1. Let currentRealm be the current Realm Record.
  559. auto& current_realm = *this->current_realm();
  560. // 2. Return currentRealm.[[GlobalObject]].
  561. return current_realm.global_object();
  562. }
  563. bool VM::in_strict_mode() const
  564. {
  565. if (execution_context_stack().is_empty())
  566. return false;
  567. return running_execution_context().is_strict_mode;
  568. }
  569. void VM::run_queued_promise_jobs()
  570. {
  571. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  572. while (!m_promise_jobs.is_empty()) {
  573. auto job = m_promise_jobs.take_first();
  574. dbgln_if(PROMISE_DEBUG, "Calling promise job function");
  575. [[maybe_unused]] auto result = job();
  576. }
  577. }
  578. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  579. void VM::enqueue_promise_job(Function<ThrowCompletionOr<Value>()> job, Realm*)
  580. {
  581. // An implementation of HostEnqueuePromiseJob must conform to the requirements in 9.5 as well as the following:
  582. // - 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.
  583. // - 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
  584. // such that scriptOrModule is the active script or module at the time of job's invocation.
  585. // - Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
  586. m_promise_jobs.append(move(job));
  587. }
  588. void VM::run_queued_finalization_registry_cleanup_jobs()
  589. {
  590. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  591. auto registry = m_finalization_registry_cleanup_jobs.take_first();
  592. // FIXME: Handle any uncatched exceptions here.
  593. (void)registry->cleanup();
  594. }
  595. }
  596. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  597. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  598. {
  599. m_finalization_registry_cleanup_jobs.append(&registry);
  600. }
  601. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  602. void VM::promise_rejection_tracker(Promise& promise, Promise::RejectionOperation operation) const
  603. {
  604. switch (operation) {
  605. case Promise::RejectionOperation::Reject:
  606. // A promise was rejected without any handlers
  607. if (on_promise_unhandled_rejection)
  608. on_promise_unhandled_rejection(promise);
  609. break;
  610. case Promise::RejectionOperation::Handle:
  611. // A handler was added to an already rejected promise
  612. if (on_promise_rejection_handled)
  613. on_promise_rejection_handled(promise);
  614. break;
  615. default:
  616. VERIFY_NOT_REACHED();
  617. }
  618. }
  619. void VM::dump_backtrace() const
  620. {
  621. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  622. auto& frame = m_execution_context_stack[i];
  623. if (frame->instruction_stream_iterator.has_value() && frame->instruction_stream_iterator->source_code()) {
  624. auto source_range = frame->instruction_stream_iterator->source_range().realize();
  625. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename(), source_range.start.line, source_range.start.column);
  626. } else {
  627. dbgln("-> {}", frame->function_name);
  628. }
  629. }
  630. }
  631. void VM::save_execution_context_stack()
  632. {
  633. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  634. }
  635. void VM::restore_execution_context_stack()
  636. {
  637. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  638. }
  639. // 9.4.1 GetActiveScriptOrModule ( ), https://tc39.es/ecma262/#sec-getactivescriptormodule
  640. ScriptOrModule VM::get_active_script_or_module() const
  641. {
  642. // 1. If the execution context stack is empty, return null.
  643. if (m_execution_context_stack.is_empty())
  644. return Empty {};
  645. // 2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
  646. for (auto i = m_execution_context_stack.size() - 1; i > 0; i--) {
  647. if (!m_execution_context_stack[i]->script_or_module.has<Empty>())
  648. return m_execution_context_stack[i]->script_or_module;
  649. }
  650. // 3. If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule.
  651. // Note: Since it is not empty we have 0 and since we got here all the
  652. // above contexts don't have a non-null ScriptOrModule
  653. return m_execution_context_stack[0]->script_or_module;
  654. }
  655. VM::StoredModule* VM::get_stored_module(ScriptOrModule const&, DeprecatedString const& filename, DeprecatedString const&)
  656. {
  657. // Note the spec says:
  658. // Each time this operation is called with a specific referencingScriptOrModule, specifier pair as arguments
  659. // it must return the same Module Record instance if it completes normally.
  660. // Currently, we ignore the referencing script or module but this might not be correct in all cases.
  661. // Editor's Note from https://tc39.es/proposal-json-modules/#sec-hostresolveimportedmodule
  662. // The above text implies that is recommended but not required that hosts do not use moduleRequest.[[Assertions]]
  663. // as part of the module cache key. In either case, an exception thrown from an import with a given assertion list
  664. // does not rule out success of another import with the same specifier but a different assertion list.
  665. auto end_or_module = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  666. return stored_module.filename == filename;
  667. });
  668. if (end_or_module.is_end())
  669. return nullptr;
  670. return &(*end_or_module);
  671. }
  672. ThrowCompletionOr<void> VM::link_and_eval_module(Badge<Bytecode::Interpreter>, SourceTextModule& module)
  673. {
  674. return link_and_eval_module(module);
  675. }
  676. ThrowCompletionOr<void> VM::link_and_eval_module(Module& module)
  677. {
  678. auto filename = module.filename();
  679. auto module_or_end = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  680. return stored_module.module.ptr() == &module;
  681. });
  682. StoredModule* stored_module;
  683. if (module_or_end.is_end()) {
  684. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Warning introducing module via link_and_eval_module {}", module.filename());
  685. if (m_loaded_modules.size() > 0)
  686. dbgln("Warning: Using multiple modules as entry point can lead to unexpected results");
  687. m_loaded_modules.empend(
  688. NonnullGCPtr(module),
  689. module.filename(),
  690. DeprecatedString {}, // Null type
  691. module,
  692. true);
  693. stored_module = &m_loaded_modules.last();
  694. } else {
  695. stored_module = module_or_end.operator->();
  696. if (stored_module->has_once_started_linking) {
  697. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Module already has started linking once {}", module.filename());
  698. return {};
  699. }
  700. stored_module->has_once_started_linking = true;
  701. }
  702. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking module {}", filename);
  703. auto linked_or_error = module.link(*this);
  704. if (linked_or_error.is_error())
  705. return linked_or_error.throw_completion();
  706. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking passed, now evaluating module {}", filename);
  707. auto evaluated_or_error = module.evaluate(*this);
  708. if (evaluated_or_error.is_error())
  709. return evaluated_or_error.throw_completion();
  710. auto* evaluated_value = evaluated_or_error.value();
  711. run_queued_promise_jobs();
  712. VERIFY(m_promise_jobs.is_empty());
  713. // FIXME: This will break if we start doing promises actually asynchronously.
  714. VERIFY(evaluated_value->state() != Promise::State::Pending);
  715. if (evaluated_value->state() == Promise::State::Rejected)
  716. return JS::throw_completion(evaluated_value->result());
  717. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Evaluating passed for module {}", module.filename());
  718. return {};
  719. }
  720. static DeprecatedString resolve_module_filename(StringView filename, StringView module_type)
  721. {
  722. auto extensions = Vector<StringView, 2> { "js"sv, "mjs"sv };
  723. if (module_type == "json"sv)
  724. extensions = { "json"sv };
  725. if (!FileSystem::exists(filename)) {
  726. for (auto extension : extensions) {
  727. // import "./foo" -> import "./foo.ext"
  728. auto resolved_filepath = DeprecatedString::formatted("{}.{}", filename, extension);
  729. if (FileSystem::exists(resolved_filepath))
  730. return resolved_filepath;
  731. }
  732. } else if (FileSystem::is_directory(filename)) {
  733. for (auto extension : extensions) {
  734. // import "./foo" -> import "./foo/index.ext"
  735. auto resolved_filepath = LexicalPath::join(filename, DeprecatedString::formatted("index.{}", extension)).string();
  736. if (FileSystem::exists(resolved_filepath))
  737. return resolved_filepath;
  738. }
  739. }
  740. return filename;
  741. }
  742. // 16.2.1.7 HostResolveImportedModule ( referencingScriptOrModule, specifier ), https://tc39.es/ecma262/#sec-hostresolveimportedmodule
  743. ThrowCompletionOr<NonnullGCPtr<Module>> VM::resolve_imported_module(ScriptOrModule referencing_script_or_module, ModuleRequest const& module_request)
  744. {
  745. // An implementation of HostResolveImportedModule must conform to the following requirements:
  746. // - If it completes normally, the [[Value]] slot of the completion must contain an instance of a concrete subclass of Module Record.
  747. // - If a Module Record corresponding to the pair referencingScriptOrModule, moduleRequest does not exist or cannot be created, an exception must be thrown.
  748. // - Each time this operation is called with a specific referencingScriptOrModule, moduleRequest.[[Specifier]], moduleRequest.[[Assertions]] triple
  749. // as arguments it must return the same Module Record instance if it completes normally.
  750. // * It is recommended but not required that implementations additionally conform to the following stronger constraint:
  751. // each time this operation is called with a specific referencingScriptOrModule, moduleRequest.[[Specifier]] pair as arguments it must return the same Module Record instance if it completes normally.
  752. // - moduleRequest.[[Assertions]] must not influence the interpretation of the module or the module specifier;
  753. // instead, it may be used to determine whether the algorithm completes normally or with an abrupt completion.
  754. // Multiple different referencingScriptOrModule, moduleRequest.[[Specifier]] pairs may map to the same Module Record instance.
  755. // The actual mapping semantic is host-defined but typically a normalization process is applied to specifier as part of the mapping process.
  756. // A typical normalization process would include actions such as alphabetic case folding and expansion of relative and abbreviated path specifiers.
  757. // We only allow "type" as a supported assertion so it is the only valid key that should ever arrive here.
  758. VERIFY(module_request.assertions.is_empty() || (module_request.assertions.size() == 1 && module_request.assertions.first().key == "type"));
  759. auto module_type = module_request.assertions.is_empty() ? DeprecatedString {} : module_request.assertions.first().value;
  760. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module at {} has type {}", module_request.module_specifier, module_type);
  761. StringView base_filename = referencing_script_or_module.visit(
  762. [&](Empty) {
  763. return "."sv;
  764. },
  765. [&](auto& script_or_module) {
  766. return script_or_module->filename();
  767. });
  768. LexicalPath base_path { base_filename };
  769. auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier);
  770. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] base path: '{}'", base_path);
  771. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] initial filename: '{}'", filename);
  772. filename = resolve_module_filename(filename, module_type);
  773. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved filename: '{}'", filename);
  774. #if JS_MODULE_DEBUG
  775. DeprecatedString referencing_module_string = referencing_script_or_module.visit(
  776. [&](Empty) -> DeprecatedString {
  777. return ".";
  778. },
  779. [&](auto& script_or_module) {
  780. if constexpr (IsSame<Script*, decltype(script_or_module)>) {
  781. return DeprecatedString::formatted("Script @ {}", script_or_module.ptr());
  782. }
  783. return DeprecatedString::formatted("Module @ {}", script_or_module.ptr());
  784. });
  785. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module({}, {})", referencing_module_string, filename);
  786. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved {} + {} -> {}", base_path, module_request.module_specifier, filename);
  787. #endif
  788. auto* loaded_module_or_end = get_stored_module(referencing_script_or_module, filename, module_type);
  789. if (loaded_module_or_end != nullptr) {
  790. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module({}) already loaded at {}", filename, loaded_module_or_end->module.ptr());
  791. return NonnullGCPtr(*loaded_module_or_end->module);
  792. }
  793. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing module {}", filename);
  794. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  795. if (file_or_error.is_error()) {
  796. return throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier);
  797. }
  798. // FIXME: Don't read the file in one go.
  799. auto file_content_or_error = file_or_error.value()->read_until_eof();
  800. if (file_content_or_error.is_error()) {
  801. if (file_content_or_error.error().code() == ENOMEM)
  802. return throw_completion<JS::InternalError>(error_message(::JS::VM::ErrorMessage::OutOfMemory));
  803. return throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier);
  804. }
  805. StringView const content_view { file_content_or_error.value().bytes() };
  806. auto module = TRY([&]() -> ThrowCompletionOr<NonnullGCPtr<Module>> {
  807. // If assertions has an entry entry such that entry.[[Key]] is "type", let type be entry.[[Value]]. The following requirements apply:
  808. // If type is "json", then this algorithm must either invoke ParseJSONModule and return the resulting Completion Record, or throw an exception.
  809. if (module_type == "json"sv) {
  810. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing JSON module {}", filename);
  811. return parse_json_module(content_view, *current_realm(), filename);
  812. }
  813. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing as SourceTextModule module {}", filename);
  814. // Note: We treat all files as module, so if a script does not have exports it just runs it.
  815. auto module_or_errors = SourceTextModule::parse(content_view, *current_realm(), filename);
  816. if (module_or_errors.is_error()) {
  817. VERIFY(module_or_errors.error().size() > 0);
  818. return throw_completion<SyntaxError>(module_or_errors.error().first().to_deprecated_string());
  819. }
  820. return module_or_errors.release_value();
  821. }());
  822. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module(...) parsed {} to {}", filename, module.ptr());
  823. // We have to set it here already in case it references itself.
  824. m_loaded_modules.empend(
  825. referencing_script_or_module,
  826. filename,
  827. module_type,
  828. *module,
  829. false);
  830. return module;
  831. }
  832. // 16.2.1.8 HostImportModuleDynamically ( referencingScriptOrModule, specifier, promiseCapability ), https://tc39.es/ecma262/#sec-hostimportmoduledynamically
  833. ThrowCompletionOr<void> VM::import_module_dynamically(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability)
  834. {
  835. auto& realm = *current_realm();
  836. // Success path:
  837. // - At some future time, the host environment must perform FinishDynamicImport(referencingScriptOrModule, moduleRequest, promiseCapability, promise),
  838. // where promise is a Promise resolved with undefined.
  839. // - Any subsequent call to HostResolveImportedModule after FinishDynamicImport has completed,
  840. // given the arguments referencingScriptOrModule and specifier, must return a normal completion
  841. // containing a module which has already been evaluated, i.e. whose Evaluate concrete method has
  842. // already been called and returned a normal completion.
  843. // Failure path:
  844. // - At some future time, the host environment must perform
  845. // FinishDynamicImport(referencingScriptOrModule, moduleRequest, promiseCapability, promise),
  846. // where promise is a Promise rejected with an error representing the cause of failure.
  847. auto promise = Promise::create(realm);
  848. ScopeGuard finish_dynamic_import = [&] {
  849. host_finish_dynamic_import(referencing_script_or_module, module_request, promise_capability, promise);
  850. };
  851. // Generally within ECMA262 we always get a referencing_script_or_module. However, ShadowRealm gives an explicit null.
  852. // 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.
  853. if (referencing_script_or_module.has<Empty>()) {
  854. referencing_script_or_module = get_active_script_or_module();
  855. // If there is no ScriptOrModule in any of the execution contexts
  856. if (referencing_script_or_module.has<Empty>()) {
  857. // Throw an error for now
  858. promise->reject(InternalError::create(realm, TRY_OR_THROW_OOM(*this, String::formatted(ErrorType::ModuleNotFoundNoReferencingScript.message(), module_request.module_specifier))));
  859. return {};
  860. }
  861. }
  862. // Note: If host_resolve_imported_module returns a module it has been loaded successfully and the next call in finish_dynamic_import will retrieve it again.
  863. auto module_or_error = host_resolve_imported_module(referencing_script_or_module, module_request);
  864. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] HostImportModuleDynamically(..., {}) -> {}", module_request.module_specifier, module_or_error.is_error() ? "failed" : "passed");
  865. if (module_or_error.is_throw_completion()) {
  866. promise->reject(*module_or_error.throw_completion().value());
  867. } else {
  868. auto module = module_or_error.release_value();
  869. auto& source_text_module = static_cast<Module&>(*module);
  870. auto evaluated_or_error = link_and_eval_module(source_text_module);
  871. if (evaluated_or_error.is_throw_completion()) {
  872. promise->reject(*evaluated_or_error.throw_completion().value());
  873. } else {
  874. promise->fulfill(js_undefined());
  875. }
  876. }
  877. // It must return unused.
  878. // Note: Just return void always since the resulting value cannot be accessed by user code.
  879. return {};
  880. }
  881. // 16.2.1.9 FinishDynamicImport ( referencingScriptOrModule, specifier, promiseCapability, innerPromise ), https://tc39.es/ecma262/#sec-finishdynamicimport
  882. void VM::finish_dynamic_import(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability, Promise* inner_promise)
  883. {
  884. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] finish_dynamic_import on {}", module_request.module_specifier);
  885. auto& realm = *current_realm();
  886. // 1. Let fulfilledClosure be a new Abstract Closure with parameters (result) that captures referencingScriptOrModule, specifier, and promiseCapability and performs the following steps when called:
  887. auto fulfilled_closure = [referencing_script_or_module = move(referencing_script_or_module), module_request = move(module_request), &promise_capability](VM& vm) -> ThrowCompletionOr<Value> {
  888. auto result = vm.argument(0);
  889. // a. Assert: result is undefined.
  890. VERIFY(result.is_undefined());
  891. // b. Let moduleRecord be ! HostResolveImportedModule(referencingScriptOrModule, specifier).
  892. auto module_record = MUST(vm.host_resolve_imported_module(referencing_script_or_module, module_request));
  893. // c. Assert: Evaluate has already been invoked on moduleRecord and successfully completed.
  894. // Note: If HostResolveImportedModule returns a module evaluate will have been called on it.
  895. // d. Let namespace be Completion(GetModuleNamespace(moduleRecord)).
  896. auto namespace_ = module_record->get_module_namespace(vm);
  897. // e. If namespace is an abrupt completion, then
  898. if (namespace_.is_throw_completion()) {
  899. // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « namespace.[[Value]] »).
  900. MUST(call(vm, *promise_capability.reject(), js_undefined(), *namespace_.throw_completion().value()));
  901. }
  902. // f. Else,
  903. else {
  904. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « namespace.[[Value]] »).
  905. MUST(call(vm, *promise_capability.resolve(), js_undefined(), namespace_.release_value()));
  906. }
  907. // g. Return unused.
  908. // NOTE: We don't support returning an empty/optional/unused value here.
  909. return js_undefined();
  910. };
  911. // 2. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
  912. auto on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 0, "");
  913. // 3. Let rejectedClosure be a new Abstract Closure with parameters (error) that captures promiseCapability and performs the following steps when called:
  914. auto rejected_closure = [&promise_capability](VM& vm) -> ThrowCompletionOr<Value> {
  915. auto error = vm.argument(0);
  916. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « error »).
  917. MUST(call(vm, *promise_capability.reject(), js_undefined(), error));
  918. // b. Return unused.
  919. // NOTE: We don't support returning an empty/optional/unused value here.
  920. return js_undefined();
  921. };
  922. // 4. Let onRejected be CreateBuiltinFunction(rejectedClosure, 0, "", « »).
  923. auto on_rejected = NativeFunction::create(realm, move(rejected_closure), 0, "");
  924. // 5. Perform PerformPromiseThen(innerPromise, onFulfilled, onRejected).
  925. inner_promise->perform_then(on_fulfilled, on_rejected, {});
  926. // 6. Return unused.
  927. }
  928. void VM::push_execution_context(ExecutionContext& context)
  929. {
  930. if (!m_execution_context_stack.is_empty())
  931. m_execution_context_stack.last()->instruction_stream_iterator = bytecode_interpreter().instruction_stream_iterator();
  932. m_execution_context_stack.append(&context);
  933. }
  934. void VM::pop_execution_context()
  935. {
  936. m_execution_context_stack.take_last();
  937. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  938. on_call_stack_emptied();
  939. }
  940. #if ARCH(X86_64)
  941. struct [[gnu::packed]] NativeStackFrame {
  942. NativeStackFrame* prev;
  943. FlatPtr return_address;
  944. };
  945. #endif
  946. Vector<FlatPtr> VM::get_native_stack_trace() const
  947. {
  948. Vector<FlatPtr> buffer;
  949. #if ARCH(X86_64)
  950. // Manually walk the stack, because backtrace() does not traverse through JIT frames.
  951. auto* frame = bit_cast<NativeStackFrame*>(__builtin_frame_address(0));
  952. while (bit_cast<FlatPtr>(frame) < m_stack_info.top() && bit_cast<FlatPtr>(frame) >= m_stack_info.base()) {
  953. buffer.append(frame->return_address);
  954. frame = frame->prev;
  955. }
  956. #endif
  957. return buffer;
  958. }
  959. static Optional<UnrealizedSourceRange> get_source_range(ExecutionContext const* context, Vector<FlatPtr> const& native_stack)
  960. {
  961. // native function
  962. if (!context->executable)
  963. return {};
  964. auto const* native_executable = context->executable->native_executable();
  965. if (!native_executable) {
  966. // Interpreter frame
  967. if (context->instruction_stream_iterator.has_value())
  968. return context->instruction_stream_iterator->source_range();
  969. return {};
  970. }
  971. // JIT frame
  972. for (auto address : native_stack) {
  973. auto range = native_executable->get_source_range(*context->executable, address);
  974. if (range.has_value())
  975. return range;
  976. }
  977. return {};
  978. }
  979. Vector<StackTraceElement> VM::stack_trace() const
  980. {
  981. auto native_stack = get_native_stack_trace();
  982. Vector<StackTraceElement> stack_trace;
  983. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; i--) {
  984. auto* context = m_execution_context_stack[i];
  985. stack_trace.append({
  986. .execution_context = context,
  987. .source_range = get_source_range(context, native_stack).value_or({}),
  988. });
  989. }
  990. return stack_trace;
  991. }
  992. }