VM.cpp 45 KB

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