VM.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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, 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](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_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<DeprecatedString> { "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. }
  115. VM::~VM() = default;
  116. String const& VM::error_message(ErrorMessage type) const
  117. {
  118. VERIFY(type < ErrorMessage::__Count);
  119. auto const& message = m_error_messages[to_underlying(type)];
  120. VERIFY(!message.is_empty());
  121. return message;
  122. }
  123. Bytecode::Interpreter& VM::bytecode_interpreter()
  124. {
  125. return *m_bytecode_interpreter;
  126. }
  127. void VM::gather_roots(HashMap<Cell*, HeapRoot>& roots)
  128. {
  129. roots.set(m_empty_string, HeapRoot { .type = HeapRoot::Type::VM });
  130. for (auto string : m_single_ascii_character_strings)
  131. roots.set(string, HeapRoot { .type = HeapRoot::Type::VM });
  132. #define __JS_ENUMERATE(SymbolName, snake_name) \
  133. roots.set(m_well_known_symbols.snake_name, HeapRoot { .type = HeapRoot::Type::VM });
  134. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  135. #undef __JS_ENUMERATE
  136. for (auto& symbol : m_global_symbol_registry)
  137. roots.set(symbol.value, HeapRoot { .type = HeapRoot::Type::VM });
  138. for (auto finalization_registry : m_finalization_registry_cleanup_jobs)
  139. roots.set(finalization_registry, HeapRoot { .type = HeapRoot::Type::VM });
  140. }
  141. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(ASTNode const& expression, DeprecatedFlyString const& name)
  142. {
  143. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  144. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  145. if (is<FunctionExpression>(expression)) {
  146. auto& function = static_cast<FunctionExpression const&>(expression);
  147. if (!function.has_name()) {
  148. return function.instantiate_ordinary_function_expression(*this, name);
  149. }
  150. } else if (is<ClassExpression>(expression)) {
  151. auto& class_expression = static_cast<ClassExpression const&>(expression);
  152. if (!class_expression.has_name()) {
  153. return TRY(class_expression.class_definition_evaluation(*this, {}, name));
  154. }
  155. }
  156. return execute_ast_node(expression);
  157. }
  158. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  159. ThrowCompletionOr<void> VM::binding_initialization(DeprecatedFlyString const& target, Value value, Environment* environment)
  160. {
  161. // 1. Let name be StringValue of Identifier.
  162. // 2. Return ? InitializeBoundName(name, value, environment).
  163. return initialize_bound_name(*this, target, value, environment);
  164. }
  165. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  166. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern const> const& target, Value value, Environment* environment)
  167. {
  168. auto& vm = *this;
  169. // BindingPattern : ObjectBindingPattern
  170. if (target->kind == BindingPattern::Kind::Object) {
  171. // 1. Perform ? RequireObjectCoercible(value).
  172. TRY(require_object_coercible(vm, value));
  173. // 2. Return ? BindingInitialization of ObjectBindingPattern with arguments value and environment.
  174. // BindingInitialization of ObjectBindingPattern
  175. // 1. Perform ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
  176. TRY(property_binding_initialization(*target, value, environment));
  177. // 2. Return unused.
  178. return {};
  179. }
  180. // BindingPattern : ArrayBindingPattern
  181. else {
  182. // 1. Let iteratorRecord be ? GetIterator(value, sync).
  183. auto iterator_record = TRY(get_iterator(vm, value, IteratorHint::Sync));
  184. // 2. Let result be Completion(IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment).
  185. auto result = iterator_binding_initialization(*target, iterator_record, environment);
  186. // 3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  187. if (!iterator_record->done) {
  188. // iterator_close() always returns a Completion, which ThrowCompletionOr will interpret as a throw
  189. // completion. So only return the result of iterator_close() if it is indeed a throw completion.
  190. auto completion = result.is_throw_completion() ? result.release_error() : normal_completion({});
  191. if (completion = iterator_close(vm, iterator_record, move(completion)); completion.is_error())
  192. return completion.release_error();
  193. }
  194. // 4. Return ? result.
  195. return result;
  196. }
  197. }
  198. ThrowCompletionOr<Value> VM::execute_ast_node(ASTNode const& node)
  199. {
  200. auto executable = TRY(Bytecode::compile(*this, node, FunctionKind::Normal, ""sv));
  201. auto result_or_error = bytecode_interpreter().run_and_return_frame(*executable, nullptr);
  202. if (result_or_error.value.is_error())
  203. return result_or_error.value.release_error();
  204. return result_or_error.frame->registers()[0];
  205. }
  206. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  207. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  208. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment)
  209. {
  210. auto& vm = *this;
  211. auto& realm = *vm.current_realm();
  212. auto object = TRY(value.to_object(vm));
  213. HashTable<PropertyKey> seen_names;
  214. for (auto& property : binding.entries) {
  215. VERIFY(!property.is_elision());
  216. if (property.is_rest) {
  217. Reference assignment_target;
  218. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier const>>()) {
  219. assignment_target = TRY(resolve_binding((*identifier_ptr)->string(), environment));
  220. } else {
  221. VERIFY_NOT_REACHED();
  222. }
  223. auto rest_object = Object::create(realm, realm.intrinsics().object_prototype());
  224. VERIFY(rest_object);
  225. TRY(rest_object->copy_data_properties(vm, object, seen_names));
  226. if (!environment)
  227. return assignment_target.put_value(vm, rest_object);
  228. else
  229. return assignment_target.initialize_referenced_binding(vm, rest_object);
  230. }
  231. auto name = TRY(property.name.visit(
  232. [&](Empty) -> ThrowCompletionOr<PropertyKey> { VERIFY_NOT_REACHED(); },
  233. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<PropertyKey> {
  234. return identifier->string();
  235. },
  236. [&](NonnullRefPtr<Expression const> const& expression) -> ThrowCompletionOr<PropertyKey> {
  237. auto result = TRY(execute_ast_node(*expression));
  238. return result.to_property_key(vm);
  239. }));
  240. seen_names.set(name);
  241. if (property.name.has<NonnullRefPtr<Identifier const>>() && property.alias.has<Empty>()) {
  242. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  243. auto& identifier = *property.name.get<NonnullRefPtr<Identifier const>>();
  244. auto reference = TRY(resolve_binding(identifier.string(), environment));
  245. auto value_to_assign = TRY(object->get(name));
  246. if (property.initializer && value_to_assign.is_undefined()) {
  247. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, identifier.string()));
  248. }
  249. if (!environment)
  250. TRY(reference.put_value(vm, value_to_assign));
  251. else
  252. TRY(reference.initialize_referenced_binding(vm, value_to_assign));
  253. continue;
  254. }
  255. auto reference_to_assign_to = TRY(property.alias.visit(
  256. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  257. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  258. return TRY(resolve_binding(identifier->string(), environment));
  259. },
  260. [&](NonnullRefPtr<BindingPattern const> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  261. [&](NonnullRefPtr<MemberExpression const> const&) -> ThrowCompletionOr<Optional<Reference>> {
  262. VERIFY_NOT_REACHED();
  263. }));
  264. auto value_to_assign = TRY(object->get(name));
  265. if (property.initializer && value_to_assign.is_undefined()) {
  266. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier const>>())
  267. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, (*identifier_ptr)->string()));
  268. else
  269. value_to_assign = TRY(execute_ast_node(*property.initializer));
  270. }
  271. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern const>>()) {
  272. TRY(binding_initialization(*binding_ptr, value_to_assign, environment));
  273. } else {
  274. VERIFY(reference_to_assign_to.has_value());
  275. if (!environment)
  276. TRY(reference_to_assign_to->put_value(vm, value_to_assign));
  277. else
  278. TRY(reference_to_assign_to->initialize_referenced_binding(vm, value_to_assign));
  279. }
  280. }
  281. return {};
  282. }
  283. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  284. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  285. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, IteratorRecord& iterator_record, Environment* environment)
  286. {
  287. auto& vm = *this;
  288. auto& realm = *vm.current_realm();
  289. // FIXME: this method is nearly identical to destructuring assignment!
  290. for (size_t i = 0; i < binding.entries.size(); i++) {
  291. auto& entry = binding.entries[i];
  292. Value value;
  293. auto assignment_target = TRY(entry.alias.visit(
  294. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  295. [&](NonnullRefPtr<Identifier const> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  296. return TRY(resolve_binding(identifier->string(), environment));
  297. },
  298. [&](NonnullRefPtr<BindingPattern const> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  299. [&](NonnullRefPtr<MemberExpression const> const&) -> ThrowCompletionOr<Optional<Reference>> {
  300. VERIFY_NOT_REACHED();
  301. }));
  302. // BindingRestElement : ... BindingIdentifier
  303. // BindingRestElement : ... BindingPattern
  304. if (entry.is_rest) {
  305. VERIFY(i == binding.entries.size() - 1);
  306. // 2. Let A be ! ArrayCreate(0).
  307. auto array = MUST(Array::create(realm, 0));
  308. // 3. Let n be 0.
  309. // 4. Repeat,
  310. while (true) {
  311. ThrowCompletionOr<GCPtr<Object>> next { nullptr };
  312. // a. If iteratorRecord.[[Done]] is false, then
  313. if (!iterator_record.done) {
  314. // i. Let next be Completion(IteratorStep(iteratorRecord)).
  315. next = iterator_step(vm, iterator_record);
  316. // ii. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  317. // iii. ReturnIfAbrupt(next).
  318. if (next.is_error()) {
  319. iterator_record.done = true;
  320. return next.release_error();
  321. }
  322. // iv. If next is false, set iteratorRecord.[[Done]] to true.
  323. if (!next.value())
  324. iterator_record.done = true;
  325. }
  326. // b. If iteratorRecord.[[Done]] is true, then
  327. if (iterator_record.done) {
  328. // NOTE: Step i. and ii. are handled below.
  329. break;
  330. }
  331. // c. Let nextValue be Completion(IteratorValue(next)).
  332. auto next_value = iterator_value(vm, *next.value());
  333. // d. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  334. // e. ReturnIfAbrupt(nextValue).
  335. if (next_value.is_error()) {
  336. iterator_record.done = true;
  337. return next_value.release_error();
  338. }
  339. // f. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
  340. array->indexed_properties().append(next_value.value());
  341. // g. Set n to n + 1.
  342. }
  343. value = array;
  344. }
  345. // SingleNameBinding : BindingIdentifier Initializer[opt]
  346. // BindingElement : BindingPattern Initializer[opt]
  347. else {
  348. // 1. Let v be undefined.
  349. value = js_undefined();
  350. // 2. If iteratorRecord.[[Done]] is false, then
  351. if (!iterator_record.done) {
  352. // a. Let next be Completion(IteratorStep(iteratorRecord)).
  353. auto next = iterator_step(vm, iterator_record);
  354. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  355. // c. ReturnIfAbrupt(next).
  356. if (next.is_error()) {
  357. iterator_record.done = true;
  358. return next.release_error();
  359. }
  360. // d. If next is false, set iteratorRecord.[[Done]] to true.
  361. if (!next.value()) {
  362. iterator_record.done = true;
  363. }
  364. // e. Else,
  365. else {
  366. // i. Set v to Completion(IteratorValue(next)).
  367. auto value_or_error = iterator_value(vm, *next.value());
  368. // ii. If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
  369. // iii. ReturnIfAbrupt(v).
  370. if (value_or_error.is_throw_completion()) {
  371. iterator_record.done = true;
  372. return value_or_error.release_error();
  373. }
  374. value = value_or_error.release_value();
  375. }
  376. }
  377. // NOTE: Step 3. and 4. are handled below.
  378. }
  379. if (value.is_undefined() && entry.initializer) {
  380. VERIFY(!entry.is_rest);
  381. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier const>>())
  382. value = TRY(named_evaluation_if_anonymous_function(*entry.initializer, (*identifier_ptr)->string()));
  383. else
  384. value = TRY(execute_ast_node(*entry.initializer));
  385. }
  386. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern const>>()) {
  387. TRY(binding_initialization(*binding_ptr, value, environment));
  388. } else if (!entry.alias.has<Empty>()) {
  389. VERIFY(assignment_target.has_value());
  390. if (!environment)
  391. TRY(assignment_target->put_value(vm, value));
  392. else
  393. TRY(assignment_target->initialize_referenced_binding(vm, value));
  394. }
  395. }
  396. return {};
  397. }
  398. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  399. ThrowCompletionOr<Reference> VM::get_identifier_reference(Environment* environment, DeprecatedFlyString name, bool strict, size_t hops)
  400. {
  401. // 1. If env is the value null, then
  402. if (!environment) {
  403. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  404. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  405. }
  406. // 2. Let exists be ? env.HasBinding(name).
  407. Optional<size_t> index;
  408. auto exists = TRY(environment->has_binding(name, &index));
  409. // Note: This is an optimization for looking up the same reference.
  410. Optional<EnvironmentCoordinate> environment_coordinate;
  411. if (index.has_value()) {
  412. VERIFY(hops <= NumericLimits<u32>::max());
  413. VERIFY(index.value() <= NumericLimits<u32>::max());
  414. environment_coordinate = EnvironmentCoordinate { .hops = static_cast<u32>(hops), .index = static_cast<u32>(index.value()) };
  415. }
  416. // 3. If exists is true, then
  417. if (exists) {
  418. // a. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  419. return Reference { *environment, move(name), strict, environment_coordinate };
  420. }
  421. // 4. Else,
  422. else {
  423. // a. Let outer be env.[[OuterEnv]].
  424. // b. Return ? GetIdentifierReference(outer, name, strict).
  425. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  426. }
  427. }
  428. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  429. ThrowCompletionOr<Reference> VM::resolve_binding(DeprecatedFlyString const& name, Environment* environment)
  430. {
  431. // 1. If env is not present or if env is undefined, then
  432. if (!environment) {
  433. // a. Set env to the running execution context's LexicalEnvironment.
  434. environment = running_execution_context().lexical_environment;
  435. }
  436. // 2. Assert: env is an Environment Record.
  437. VERIFY(environment);
  438. // 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.
  439. bool strict = in_strict_mode();
  440. // 4. Return ? GetIdentifierReference(env, name, strict).
  441. return get_identifier_reference(environment, name, strict);
  442. // NOTE: The spec says:
  443. // Note: The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
  444. // But this is not actually correct as GetIdentifierReference (or really the methods it calls) can throw.
  445. }
  446. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  447. ThrowCompletionOr<Value> VM::resolve_this_binding()
  448. {
  449. auto& vm = *this;
  450. // 1. Let envRec be GetThisEnvironment().
  451. auto environment = get_this_environment(vm);
  452. // 2. Return ? envRec.GetThisBinding().
  453. return TRY(environment->get_this_binding(vm));
  454. }
  455. // 9.4.5 GetNewTarget ( ), https://tc39.es/ecma262/#sec-getnewtarget
  456. Value VM::get_new_target()
  457. {
  458. // 1. Let envRec be GetThisEnvironment().
  459. auto env = get_this_environment(*this);
  460. // 2. Assert: envRec has a [[NewTarget]] field.
  461. // 3. Return envRec.[[NewTarget]].
  462. return verify_cast<FunctionEnvironment>(*env).new_target();
  463. }
  464. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  465. // ImportMeta branch only
  466. Object* VM::get_import_meta()
  467. {
  468. // 1. Let module be GetActiveScriptOrModule().
  469. auto script_or_module = get_active_script_or_module();
  470. // 2. Assert: module is a Source Text Module Record.
  471. auto& module = verify_cast<SourceTextModule>(*script_or_module.get<NonnullGCPtr<Module>>());
  472. // 3. Let importMeta be module.[[ImportMeta]].
  473. auto* import_meta = module.import_meta();
  474. // 4. If importMeta is empty, then
  475. if (import_meta == nullptr) {
  476. // a. Set importMeta to OrdinaryObjectCreate(null).
  477. import_meta = Object::create(*current_realm(), nullptr);
  478. // b. Let importMetaValues be HostGetImportMetaProperties(module).
  479. auto import_meta_values = host_get_import_meta_properties(module);
  480. // c. For each Record { [[Key]], [[Value]] } p of importMetaValues, do
  481. for (auto& entry : import_meta_values) {
  482. // i. Perform ! CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]).
  483. MUST(import_meta->create_data_property_or_throw(entry.key, entry.value));
  484. }
  485. // d. Perform HostFinalizeImportMeta(importMeta, module).
  486. host_finalize_import_meta(import_meta, module);
  487. // e. Set module.[[ImportMeta]] to importMeta.
  488. module.set_import_meta({}, import_meta);
  489. // f. Return importMeta.
  490. return import_meta;
  491. }
  492. // 5. Else,
  493. else {
  494. // a. Assert: Type(importMeta) is Object.
  495. // Note: This is always true by the type.
  496. // b. Return importMeta.
  497. return import_meta;
  498. }
  499. }
  500. // 9.4.5 GetGlobalObject ( ), https://tc39.es/ecma262/#sec-getglobalobject
  501. Object& VM::get_global_object()
  502. {
  503. // 1. Let currentRealm be the current Realm Record.
  504. auto& current_realm = *this->current_realm();
  505. // 2. Return currentRealm.[[GlobalObject]].
  506. return current_realm.global_object();
  507. }
  508. bool VM::in_strict_mode() const
  509. {
  510. if (execution_context_stack().is_empty())
  511. return false;
  512. return running_execution_context().is_strict_mode;
  513. }
  514. void VM::run_queued_promise_jobs()
  515. {
  516. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  517. while (!m_promise_jobs.is_empty()) {
  518. auto job = m_promise_jobs.take_first();
  519. dbgln_if(PROMISE_DEBUG, "Calling promise job function");
  520. [[maybe_unused]] auto result = job();
  521. }
  522. }
  523. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  524. void VM::enqueue_promise_job(Function<ThrowCompletionOr<Value>()> job, Realm*)
  525. {
  526. // An implementation of HostEnqueuePromiseJob must conform to the requirements in 9.5 as well as the following:
  527. // - 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.
  528. // - 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
  529. // such that scriptOrModule is the active script or module at the time of job's invocation.
  530. // - Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
  531. m_promise_jobs.append(move(job));
  532. }
  533. void VM::run_queued_finalization_registry_cleanup_jobs()
  534. {
  535. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  536. auto registry = m_finalization_registry_cleanup_jobs.take_first();
  537. // FIXME: Handle any uncatched exceptions here.
  538. (void)registry->cleanup();
  539. }
  540. }
  541. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  542. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  543. {
  544. m_finalization_registry_cleanup_jobs.append(&registry);
  545. }
  546. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  547. void VM::promise_rejection_tracker(Promise& promise, Promise::RejectionOperation operation) const
  548. {
  549. switch (operation) {
  550. case Promise::RejectionOperation::Reject:
  551. // A promise was rejected without any handlers
  552. if (on_promise_unhandled_rejection)
  553. on_promise_unhandled_rejection(promise);
  554. break;
  555. case Promise::RejectionOperation::Handle:
  556. // A handler was added to an already rejected promise
  557. if (on_promise_rejection_handled)
  558. on_promise_rejection_handled(promise);
  559. break;
  560. default:
  561. VERIFY_NOT_REACHED();
  562. }
  563. }
  564. void VM::dump_backtrace() const
  565. {
  566. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  567. auto& frame = m_execution_context_stack[i];
  568. if (frame->instruction_stream_iterator.has_value() && frame->instruction_stream_iterator->source_code()) {
  569. auto source_range = frame->instruction_stream_iterator->source_range().realize();
  570. dbgln("-> {} @ {}:{},{}", frame->function_name ? frame->function_name->utf8_string() : ""_string, source_range.filename(), source_range.start.line, source_range.start.column);
  571. } else {
  572. dbgln("-> {}", frame->function_name ? frame->function_name->utf8_string() : ""_string);
  573. }
  574. }
  575. }
  576. void VM::save_execution_context_stack()
  577. {
  578. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  579. }
  580. void VM::restore_execution_context_stack()
  581. {
  582. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  583. }
  584. // 9.4.1 GetActiveScriptOrModule ( ), https://tc39.es/ecma262/#sec-getactivescriptormodule
  585. ScriptOrModule VM::get_active_script_or_module() const
  586. {
  587. // 1. If the execution context stack is empty, return null.
  588. if (m_execution_context_stack.is_empty())
  589. return Empty {};
  590. // 2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
  591. for (auto i = m_execution_context_stack.size() - 1; i > 0; i--) {
  592. if (!m_execution_context_stack[i]->script_or_module.has<Empty>())
  593. return m_execution_context_stack[i]->script_or_module;
  594. }
  595. // 3. If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule.
  596. // Note: Since it is not empty we have 0 and since we got here all the
  597. // above contexts don't have a non-null ScriptOrModule
  598. return m_execution_context_stack[0]->script_or_module;
  599. }
  600. VM::StoredModule* VM::get_stored_module(ImportedModuleReferrer const&, DeprecatedString const& filename, DeprecatedString const&)
  601. {
  602. // Note the spec says:
  603. // If this operation is called multiple times with the same (referrer, specifier) pair and it performs
  604. // FinishLoadingImportedModule(referrer, specifier, payload, result) where result is a normal completion,
  605. // then it must perform FinishLoadingImportedModule(referrer, specifier, payload, result) with the same result each time.
  606. // Editor's Note from https://tc39.es/proposal-json-modules/#sec-hostresolveimportedmodule
  607. // The above text implies that is recommended but not required that hosts do not use moduleRequest.[[Assertions]]
  608. // as part of the module cache key. In either case, an exception thrown from an import with a given assertion list
  609. // does not rule out success of another import with the same specifier but a different assertion list.
  610. // FIXME: This should probably check referrer as well.
  611. auto end_or_module = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  612. return stored_module.filename == filename;
  613. });
  614. if (end_or_module.is_end())
  615. return nullptr;
  616. return &(*end_or_module);
  617. }
  618. ThrowCompletionOr<void> VM::link_and_eval_module(Badge<Bytecode::Interpreter>, SourceTextModule& module)
  619. {
  620. return link_and_eval_module(module);
  621. }
  622. ThrowCompletionOr<void> VM::link_and_eval_module(CyclicModule& module)
  623. {
  624. auto filename = module.filename();
  625. module.load_requested_modules(nullptr);
  626. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking module {}", filename);
  627. auto linked_or_error = module.link(*this);
  628. if (linked_or_error.is_error())
  629. return linked_or_error.throw_completion();
  630. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking passed, now evaluating module {}", filename);
  631. auto evaluated_or_error = module.evaluate(*this);
  632. if (evaluated_or_error.is_error())
  633. return evaluated_or_error.throw_completion();
  634. auto* evaluated_value = evaluated_or_error.value();
  635. run_queued_promise_jobs();
  636. VERIFY(m_promise_jobs.is_empty());
  637. // FIXME: This will break if we start doing promises actually asynchronously.
  638. VERIFY(evaluated_value->state() != Promise::State::Pending);
  639. if (evaluated_value->state() == Promise::State::Rejected)
  640. return JS::throw_completion(evaluated_value->result());
  641. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Evaluating passed for module {}", module.filename());
  642. return {};
  643. }
  644. static DeprecatedString resolve_module_filename(StringView filename, StringView module_type)
  645. {
  646. auto extensions = Vector<StringView, 2> { "js"sv, "mjs"sv };
  647. if (module_type == "json"sv)
  648. extensions = { "json"sv };
  649. if (!FileSystem::exists(filename)) {
  650. for (auto extension : extensions) {
  651. // import "./foo" -> import "./foo.ext"
  652. auto resolved_filepath = DeprecatedString::formatted("{}.{}", filename, extension);
  653. if (FileSystem::exists(resolved_filepath))
  654. return resolved_filepath;
  655. }
  656. } else if (FileSystem::is_directory(filename)) {
  657. for (auto extension : extensions) {
  658. // import "./foo" -> import "./foo/index.ext"
  659. auto resolved_filepath = LexicalPath::join(filename, DeprecatedString::formatted("index.{}", extension)).string();
  660. if (FileSystem::exists(resolved_filepath))
  661. return resolved_filepath;
  662. }
  663. }
  664. return filename;
  665. }
  666. // 16.2.1.8 HostLoadImportedModule ( referrer, specifier, hostDefined, payload ), https://tc39.es/ecma262/#sec-HostLoadImportedModule
  667. void VM::load_imported_module(ImportedModuleReferrer referrer, ModuleRequest const& module_request, GCPtr<GraphLoadingState::HostDefined>, ImportedModulePayload payload)
  668. {
  669. // An implementation of HostLoadImportedModule must conform to the following requirements:
  670. //
  671. // - The host environment must perform FinishLoadingImportedModule(referrer, specifier, payload, result),
  672. // where result is either a normal completion containing the loaded Module Record or a throw completion,
  673. // either synchronously or asynchronously.
  674. // - If this operation is called multiple times with the same (referrer, specifier) pair and it performs
  675. // FinishLoadingImportedModule(referrer, specifier, payload, result) where result is a normal completion,
  676. // then it must perform FinishLoadingImportedModule(referrer, specifier, payload, result) with the same result each time.
  677. // - The operation must treat payload as an opaque value to be passed through to FinishLoadingImportedModule.
  678. //
  679. // The actual process performed is host-defined, but typically consists of performing whatever I/O operations are necessary to
  680. // load the appropriate Module Record. Multiple different (referrer, specifier) pairs may map to the same Module Record instance.
  681. // The actual mapping semantics is host-defined but typically a normalization process is applied to specifier as part of the
  682. // mapping process. A typical normalization process would include actions such as expansion of relative and abbreviated path specifiers.
  683. // Here we check, against the spec, if payload is a promise capability, meaning that this was called for a dynamic import
  684. if (payload.has<NonnullGCPtr<PromiseCapability>>() && !m_dynamic_imports_allowed) {
  685. // If you are here because you want to enable dynamic module importing make sure it won't be a security problem
  686. // by checking the default implementation of HostImportModuleDynamically and creating your own hook or calling
  687. // vm.allow_dynamic_imports().
  688. finish_loading_imported_module(referrer, module_request, payload, throw_completion<InternalError>(ErrorType::DynamicImportNotAllowed, module_request.module_specifier));
  689. return;
  690. }
  691. DeprecatedString module_type;
  692. for (auto& attribute : module_request.attributes) {
  693. if (attribute.key == "type"sv) {
  694. module_type = attribute.value;
  695. break;
  696. }
  697. }
  698. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module at {} has type {}", module_request.module_specifier, module_type);
  699. StringView const base_filename = referrer.visit(
  700. [&](NonnullGCPtr<Realm> const&) {
  701. // Generally within ECMA262 we always get a referencing_script_or_module. However, ShadowRealm gives an explicit null.
  702. // 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.
  703. return get_active_script_or_module().visit(
  704. [](Empty) {
  705. return "."sv;
  706. },
  707. [](auto const& script_or_module) {
  708. return script_or_module->filename();
  709. });
  710. },
  711. [&](auto const& script_or_module) {
  712. return script_or_module->filename();
  713. });
  714. LexicalPath base_path { base_filename };
  715. auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier);
  716. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] base path: '{}'", base_path);
  717. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] initial filename: '{}'", filename);
  718. filename = resolve_module_filename(filename, module_type);
  719. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved filename: '{}'", filename);
  720. #if JS_MODULE_DEBUG
  721. DeprecatedString referencing_module_string = referrer.visit(
  722. [&](Empty) -> DeprecatedString {
  723. return ".";
  724. },
  725. [&](auto& script_or_module) {
  726. if constexpr (IsSame<Script*, decltype(script_or_module)>) {
  727. return DeprecatedString::formatted("Script @ {}", script_or_module.ptr());
  728. }
  729. return DeprecatedString::formatted("Module @ {}", script_or_module.ptr());
  730. });
  731. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] load_imported_module({}, {})", referencing_module_string, filename);
  732. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved {} + {} -> {}", base_path, module_request.module_specifier, filename);
  733. #endif
  734. auto* loaded_module_or_end = get_stored_module(referrer, filename, module_type);
  735. if (loaded_module_or_end != nullptr) {
  736. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] load_imported_module({}) already loaded at {}", filename, loaded_module_or_end->module.ptr());
  737. finish_loading_imported_module(referrer, module_request, payload, *loaded_module_or_end->module);
  738. return;
  739. }
  740. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing module {}", filename);
  741. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  742. if (file_or_error.is_error()) {
  743. finish_loading_imported_module(referrer, module_request, payload, throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier));
  744. return;
  745. }
  746. // FIXME: Don't read the file in one go.
  747. auto file_content_or_error = file_or_error.value()->read_until_eof();
  748. if (file_content_or_error.is_error()) {
  749. if (file_content_or_error.error().code() == ENOMEM) {
  750. finish_loading_imported_module(referrer, module_request, payload, throw_completion<JS::InternalError>(error_message(::JS::VM::ErrorMessage::OutOfMemory)));
  751. return;
  752. }
  753. finish_loading_imported_module(referrer, module_request, payload, throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier));
  754. return;
  755. }
  756. StringView const content_view { file_content_or_error.value().bytes() };
  757. auto module = [&]() -> ThrowCompletionOr<NonnullGCPtr<Module>> {
  758. // If assertions has an entry entry such that entry.[[Key]] is "type", let type be entry.[[Value]]. The following requirements apply:
  759. // If type is "json", then this algorithm must either invoke ParseJSONModule and return the resulting Completion Record, or throw an exception.
  760. if (module_type == "json"sv) {
  761. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing JSON module {}", filename);
  762. return parse_json_module(content_view, *current_realm(), filename);
  763. }
  764. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing as SourceTextModule module {}", filename);
  765. // Note: We treat all files as module, so if a script does not have exports it just runs it.
  766. auto module_or_errors = SourceTextModule::parse(content_view, *current_realm(), filename);
  767. if (module_or_errors.is_error()) {
  768. VERIFY(module_or_errors.error().size() > 0);
  769. return throw_completion<SyntaxError>(module_or_errors.error().first().to_deprecated_string());
  770. }
  771. auto module = module_or_errors.release_value();
  772. m_loaded_modules.empend(
  773. referrer,
  774. module->filename(),
  775. DeprecatedString {}, // Null type
  776. make_handle<Module>(*module),
  777. true);
  778. return module;
  779. }();
  780. finish_loading_imported_module(referrer, module_request, payload, module);
  781. }
  782. void VM::push_execution_context(ExecutionContext& context)
  783. {
  784. if (!m_execution_context_stack.is_empty())
  785. m_execution_context_stack.last()->instruction_stream_iterator = bytecode_interpreter().instruction_stream_iterator();
  786. m_execution_context_stack.append(&context);
  787. }
  788. void VM::pop_execution_context()
  789. {
  790. m_execution_context_stack.take_last();
  791. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  792. on_call_stack_emptied();
  793. }
  794. #if ARCH(X86_64)
  795. struct [[gnu::packed]] NativeStackFrame {
  796. NativeStackFrame* prev;
  797. FlatPtr return_address;
  798. };
  799. #endif
  800. Vector<FlatPtr> VM::get_native_stack_trace() const
  801. {
  802. Vector<FlatPtr> buffer;
  803. #if ARCH(X86_64)
  804. // Manually walk the stack, because backtrace() does not traverse through JIT frames.
  805. auto* frame = bit_cast<NativeStackFrame*>(__builtin_frame_address(0));
  806. while (bit_cast<FlatPtr>(frame) < m_stack_info.top() && bit_cast<FlatPtr>(frame) >= m_stack_info.base()) {
  807. buffer.append(frame->return_address);
  808. frame = frame->prev;
  809. }
  810. #endif
  811. return buffer;
  812. }
  813. static Optional<UnrealizedSourceRange> get_source_range(ExecutionContext const* context, Vector<FlatPtr> const& native_stack)
  814. {
  815. // native function
  816. if (!context->executable)
  817. return {};
  818. auto const* native_executable = context->executable->native_executable();
  819. if (!native_executable) {
  820. // Interpreter frame
  821. if (context->instruction_stream_iterator.has_value())
  822. return context->instruction_stream_iterator->source_range();
  823. return {};
  824. }
  825. // JIT frame
  826. for (auto address : native_stack) {
  827. auto range = native_executable->get_source_range(*context->executable, address);
  828. if (range.has_value())
  829. return range;
  830. }
  831. return {};
  832. }
  833. Vector<StackTraceElement> VM::stack_trace() const
  834. {
  835. auto native_stack = get_native_stack_trace();
  836. Vector<StackTraceElement> stack_trace;
  837. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; i--) {
  838. auto* context = m_execution_context_stack[i];
  839. stack_trace.append({
  840. .execution_context = context,
  841. .source_range = get_source_range(context, native_stack).value_or({}),
  842. });
  843. }
  844. return stack_trace;
  845. }
  846. }