VM.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/ScopeGuard.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibJS/Interpreter.h>
  12. #include <LibJS/Runtime/AbstractOperations.h>
  13. #include <LibJS/Runtime/Array.h>
  14. #include <LibJS/Runtime/BoundFunction.h>
  15. #include <LibJS/Runtime/Completion.h>
  16. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  17. #include <LibJS/Runtime/Error.h>
  18. #include <LibJS/Runtime/FinalizationRegistry.h>
  19. #include <LibJS/Runtime/FunctionEnvironment.h>
  20. #include <LibJS/Runtime/GlobalObject.h>
  21. #include <LibJS/Runtime/IteratorOperations.h>
  22. #include <LibJS/Runtime/NativeFunction.h>
  23. #include <LibJS/Runtime/PromiseReaction.h>
  24. #include <LibJS/Runtime/Reference.h>
  25. #include <LibJS/Runtime/Symbol.h>
  26. #include <LibJS/Runtime/TemporaryClearException.h>
  27. #include <LibJS/Runtime/VM.h>
  28. namespace JS {
  29. NonnullRefPtr<VM> VM::create(OwnPtr<CustomData> custom_data)
  30. {
  31. return adopt_ref(*new VM(move(custom_data)));
  32. }
  33. VM::VM(OwnPtr<CustomData> custom_data)
  34. : m_heap(*this)
  35. , m_custom_data(move(custom_data))
  36. {
  37. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  38. for (size_t i = 0; i < 128; ++i) {
  39. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  40. }
  41. #define __JS_ENUMERATE(SymbolName, snake_name) \
  42. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  43. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  44. #undef __JS_ENUMERATE
  45. }
  46. VM::~VM()
  47. {
  48. }
  49. Interpreter& VM::interpreter()
  50. {
  51. VERIFY(!m_interpreters.is_empty());
  52. return *m_interpreters.last();
  53. }
  54. Interpreter* VM::interpreter_if_exists()
  55. {
  56. if (m_interpreters.is_empty())
  57. return nullptr;
  58. return m_interpreters.last();
  59. }
  60. void VM::push_interpreter(Interpreter& interpreter)
  61. {
  62. m_interpreters.append(&interpreter);
  63. }
  64. void VM::pop_interpreter(Interpreter& interpreter)
  65. {
  66. VERIFY(!m_interpreters.is_empty());
  67. auto* popped_interpreter = m_interpreters.take_last();
  68. VERIFY(popped_interpreter == &interpreter);
  69. }
  70. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  71. : m_interpreter(interpreter)
  72. {
  73. m_interpreter.vm().push_interpreter(m_interpreter);
  74. }
  75. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  76. {
  77. m_interpreter.vm().pop_interpreter(m_interpreter);
  78. }
  79. void VM::gather_roots(HashTable<Cell*>& roots)
  80. {
  81. roots.set(m_empty_string);
  82. for (auto* string : m_single_ascii_character_strings)
  83. roots.set(string);
  84. roots.set(m_exception);
  85. if (m_last_value.is_cell())
  86. roots.set(&m_last_value.as_cell());
  87. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  88. for (auto& execution_context : stack) {
  89. if (execution_context->this_value.is_cell())
  90. roots.set(&execution_context->this_value.as_cell());
  91. for (auto& argument : execution_context->arguments) {
  92. if (argument.is_cell())
  93. roots.set(&argument.as_cell());
  94. }
  95. roots.set(execution_context->lexical_environment);
  96. roots.set(execution_context->variable_environment);
  97. roots.set(execution_context->private_environment);
  98. }
  99. };
  100. gather_roots_from_execution_context_stack(m_execution_context_stack);
  101. for (auto& saved_stack : m_saved_execution_context_stacks)
  102. gather_roots_from_execution_context_stack(saved_stack);
  103. #define __JS_ENUMERATE(SymbolName, snake_name) \
  104. roots.set(well_known_symbol_##snake_name());
  105. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  106. #undef __JS_ENUMERATE
  107. for (auto& symbol : m_global_symbol_map)
  108. roots.set(symbol.value);
  109. for (auto* job : m_promise_jobs)
  110. roots.set(job);
  111. for (auto* finalization_registry : m_finalization_registry_cleanup_jobs)
  112. roots.set(finalization_registry);
  113. }
  114. Symbol* VM::get_global_symbol(const String& description)
  115. {
  116. auto result = m_global_symbol_map.get(description);
  117. if (result.has_value())
  118. return result.value();
  119. auto new_global_symbol = js_symbol(*this, description, true);
  120. m_global_symbol_map.set(description, new_global_symbol);
  121. return new_global_symbol;
  122. }
  123. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name)
  124. {
  125. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  126. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  127. if (is<FunctionExpression>(expression)) {
  128. auto& function = static_cast<FunctionExpression const&>(expression);
  129. if (!function.has_name()) {
  130. return function.instantiate_ordinary_function_expression(interpreter(), global_object, name);
  131. }
  132. } else if (is<ClassExpression>(expression)) {
  133. auto& class_expression = static_cast<ClassExpression const&>(expression);
  134. if (!class_expression.has_name()) {
  135. return TRY(class_expression.class_definition_evaluation(interpreter(), global_object, {}, name));
  136. }
  137. }
  138. auto value = expression.execute(interpreter(), global_object);
  139. if (auto* thrown_exception = exception())
  140. return JS::throw_completion(thrown_exception->value());
  141. return value;
  142. }
  143. // 13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation
  144. ThrowCompletionOr<void> VM::destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object)
  145. {
  146. // Note: DestructuringAssignmentEvaluation is just like BindingInitialization without an environment
  147. // And it allows member expressions. We thus trust the parser to disallow member expressions
  148. // in any non assignment binding and just call BindingInitialization with a nullptr environment
  149. return binding_initialization(target, value, nullptr, global_object);
  150. }
  151. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  152. ThrowCompletionOr<void> VM::binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object)
  153. {
  154. if (environment) {
  155. MUST(environment->initialize_binding(global_object, target, value));
  156. return {};
  157. }
  158. auto reference = resolve_binding(target);
  159. return reference.put_value(global_object, value);
  160. }
  161. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  162. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object)
  163. {
  164. if (target->kind == BindingPattern::Kind::Object) {
  165. TRY(require_object_coercible(global_object, value));
  166. TRY(property_binding_initialization(*target, value, environment, global_object));
  167. return {};
  168. } else {
  169. auto* iterator = TRY(get_iterator(global_object, value));
  170. auto iterator_done = false;
  171. auto result = iterator_binding_initialization(*target, iterator, iterator_done, environment, global_object);
  172. if (!iterator_done) {
  173. // iterator_close() always returns a Completion, which ThrowCompletionOr will interpret as a throw
  174. // completion. So only return the result of iterator_close() if it is indeed a throw completion.
  175. auto completion = result.is_throw_completion() ? result.release_error() : normal_completion({});
  176. if (completion = iterator_close(*iterator, move(completion)); completion.is_error())
  177. return completion.release_error();
  178. }
  179. return result;
  180. }
  181. }
  182. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  183. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  184. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object)
  185. {
  186. auto* object = TRY(value.to_object(global_object));
  187. HashTable<PropertyKey> seen_names;
  188. for (auto& property : binding.entries) {
  189. VERIFY(!property.is_elision());
  190. if (property.is_rest) {
  191. Reference assignment_target;
  192. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier>>()) {
  193. assignment_target = resolve_binding((*identifier_ptr)->string(), environment);
  194. } else if (auto member_ptr = property.alias.get_pointer<NonnullRefPtr<MemberExpression>>()) {
  195. assignment_target = (*member_ptr)->to_reference(interpreter(), global_object);
  196. } else {
  197. VERIFY_NOT_REACHED();
  198. }
  199. if (auto* thrown_exception = exception())
  200. return JS::throw_completion(thrown_exception->value());
  201. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  202. VERIFY(rest_object);
  203. TRY(rest_object->copy_data_properties(object, seen_names, global_object));
  204. if (!environment)
  205. return assignment_target.put_value(global_object, rest_object);
  206. else
  207. return assignment_target.initialize_referenced_binding(global_object, rest_object);
  208. }
  209. PropertyKey name;
  210. property.name.visit(
  211. [&](Empty) { VERIFY_NOT_REACHED(); },
  212. [&](NonnullRefPtr<Identifier> const& identifier) {
  213. name = identifier->string();
  214. },
  215. [&](NonnullRefPtr<Expression> const& expression) {
  216. auto result = expression->execute(interpreter(), global_object);
  217. if (exception())
  218. return;
  219. auto name_or_error = result.to_property_key(global_object);
  220. if (name_or_error.is_error())
  221. return;
  222. name = name_or_error.release_value();
  223. });
  224. if (auto* thrown_exception = exception())
  225. return JS::throw_completion(thrown_exception->value());
  226. seen_names.set(name);
  227. if (property.name.has<NonnullRefPtr<Identifier>>() && property.alias.has<Empty>()) {
  228. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  229. auto& identifier = *property.name.get<NonnullRefPtr<Identifier>>();
  230. auto reference = resolve_binding(identifier.string(), environment);
  231. if (auto* thrown_exception = exception())
  232. return JS::throw_completion(thrown_exception->value());
  233. auto value_to_assign = TRY(object->get(name));
  234. if (property.initializer && value_to_assign.is_undefined()) {
  235. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, identifier.string()));
  236. }
  237. if (!environment)
  238. TRY(reference.put_value(global_object, value_to_assign));
  239. else
  240. TRY(reference.initialize_referenced_binding(global_object, value_to_assign));
  241. continue;
  242. }
  243. Optional<Reference> reference_to_assign_to;
  244. property.alias.visit(
  245. [&](Empty) {},
  246. [&](NonnullRefPtr<Identifier> const& identifier) {
  247. reference_to_assign_to = resolve_binding(identifier->string(), environment);
  248. },
  249. [&](NonnullRefPtr<BindingPattern> const&) {},
  250. [&](NonnullRefPtr<MemberExpression> const& member_expression) {
  251. reference_to_assign_to = member_expression->to_reference(interpreter(), global_object);
  252. });
  253. if (auto* thrown_exception = exception())
  254. return JS::throw_completion(thrown_exception->value());
  255. auto value_to_assign = TRY(object->get(name));
  256. if (property.initializer && value_to_assign.is_undefined()) {
  257. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier>>())
  258. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, (*identifier_ptr)->string()));
  259. else
  260. value_to_assign = property.initializer->execute(interpreter(), global_object);
  261. if (auto* thrown_exception = exception())
  262. return JS::throw_completion(thrown_exception->value());
  263. }
  264. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  265. TRY(binding_initialization(*binding_ptr, value_to_assign, environment, global_object));
  266. } else {
  267. VERIFY(reference_to_assign_to.has_value());
  268. if (!environment)
  269. TRY(reference_to_assign_to->put_value(global_object, value_to_assign));
  270. else
  271. TRY(reference_to_assign_to->initialize_referenced_binding(global_object, value_to_assign));
  272. }
  273. }
  274. return {};
  275. }
  276. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  277. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  278. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, Object* iterator, bool& iterator_done, Environment* environment, GlobalObject& global_object)
  279. {
  280. // FIXME: this method is nearly identical to destructuring assignment!
  281. for (size_t i = 0; i < binding.entries.size(); i++) {
  282. auto& entry = binding.entries[i];
  283. Value value;
  284. Optional<Reference> assignment_target;
  285. entry.alias.visit(
  286. [&](Empty) {},
  287. [&](NonnullRefPtr<Identifier> const& identifier) {
  288. assignment_target = resolve_binding(identifier->string(), environment);
  289. },
  290. [&](NonnullRefPtr<BindingPattern> const&) {},
  291. [&](NonnullRefPtr<MemberExpression> const& member_expression) {
  292. assignment_target = member_expression->to_reference(interpreter(), global_object);
  293. });
  294. if (auto* thrown_exception = exception())
  295. return JS::throw_completion(thrown_exception->value());
  296. if (entry.is_rest) {
  297. VERIFY(i == binding.entries.size() - 1);
  298. auto* array = MUST(Array::create(global_object, 0));
  299. while (!iterator_done) {
  300. auto next_object_or_error = iterator_next(*iterator);
  301. if (next_object_or_error.is_throw_completion()) {
  302. iterator_done = true;
  303. return JS::throw_completion(next_object_or_error.release_error().value());
  304. }
  305. auto* next_object = next_object_or_error.release_value();
  306. auto done_property = TRY(next_object->get(names.done));
  307. if (done_property.to_boolean()) {
  308. iterator_done = true;
  309. break;
  310. }
  311. auto next_value = TRY(next_object->get(names.value));
  312. array->indexed_properties().append(next_value);
  313. }
  314. value = array;
  315. } else if (!iterator_done) {
  316. auto next_object_or_error = iterator_next(*iterator);
  317. if (next_object_or_error.is_throw_completion()) {
  318. iterator_done = true;
  319. return JS::throw_completion(next_object_or_error.release_error().value());
  320. }
  321. auto* next_object = next_object_or_error.release_value();
  322. auto done_property = TRY(next_object->get(names.done));
  323. if (done_property.to_boolean()) {
  324. iterator_done = true;
  325. value = js_undefined();
  326. } else {
  327. auto value_or_error = next_object->get(names.value);
  328. if (value_or_error.is_throw_completion()) {
  329. iterator_done = true;
  330. return JS::throw_completion(value_or_error.release_error().value());
  331. }
  332. value = value_or_error.release_value();
  333. }
  334. } else {
  335. value = js_undefined();
  336. }
  337. if (value.is_undefined() && entry.initializer) {
  338. VERIFY(!entry.is_rest);
  339. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier>>())
  340. value = TRY(named_evaluation_if_anonymous_function(global_object, *entry.initializer, (*identifier_ptr)->string()));
  341. else
  342. value = entry.initializer->execute(interpreter(), global_object);
  343. if (auto* thrown_exception = exception())
  344. return JS::throw_completion(thrown_exception->value());
  345. }
  346. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  347. TRY(binding_initialization(*binding_ptr, value, environment, global_object));
  348. } else if (!entry.alias.has<Empty>()) {
  349. VERIFY(assignment_target.has_value());
  350. if (!environment)
  351. TRY(assignment_target->put_value(global_object, value));
  352. else
  353. TRY(assignment_target->initialize_referenced_binding(global_object, value));
  354. }
  355. }
  356. return {};
  357. }
  358. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  359. Reference VM::get_identifier_reference(Environment* environment, FlyString name, bool strict, size_t hops)
  360. {
  361. // 1. If env is the value null, then
  362. if (!environment) {
  363. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  364. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  365. }
  366. Optional<size_t> index;
  367. auto exists = TRY_OR_DISCARD(environment->has_binding(name, &index));
  368. Optional<EnvironmentCoordinate> environment_coordinate;
  369. if (index.has_value())
  370. environment_coordinate = EnvironmentCoordinate { .hops = hops, .index = index.value() };
  371. if (exists)
  372. return Reference { *environment, move(name), strict, environment_coordinate };
  373. else
  374. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  375. }
  376. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  377. Reference VM::resolve_binding(FlyString const& name, Environment* environment)
  378. {
  379. // 1. If env is not present or if env is undefined, then
  380. if (!environment) {
  381. // a. Set env to the running execution context's LexicalEnvironment.
  382. environment = running_execution_context().lexical_environment;
  383. }
  384. // 2. Assert: env is an Environment Record.
  385. VERIFY(environment);
  386. // 3. If the code matching the syntactic production that is being evaluated is contained in strict mode code, let strict be true; else let strict be false.
  387. bool strict = in_strict_mode();
  388. // 4. Return ? GetIdentifierReference(env, name, strict).
  389. return get_identifier_reference(environment, name, strict);
  390. }
  391. // 7.3.33 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  392. ThrowCompletionOr<void> VM::initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor)
  393. {
  394. for (auto& method : constructor.private_methods())
  395. TRY(object.private_method_or_accessor_add(method));
  396. for (auto& field : constructor.fields())
  397. TRY(object.define_field(field.name, field.initializer));
  398. return {};
  399. }
  400. void VM::throw_exception(Exception& exception)
  401. {
  402. set_exception(exception);
  403. unwind(ScopeType::Try);
  404. }
  405. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  406. Value VM::resolve_this_binding(GlobalObject& global_object)
  407. {
  408. auto& environment = get_this_environment(*this);
  409. return TRY_OR_DISCARD(environment.get_this_binding(global_object));
  410. }
  411. String VM::join_arguments(size_t start_index) const
  412. {
  413. StringBuilder joined_arguments;
  414. for (size_t i = start_index; i < argument_count(); ++i) {
  415. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  416. if (i != argument_count() - 1)
  417. joined_arguments.append(' ');
  418. }
  419. return joined_arguments.build();
  420. }
  421. Value VM::get_new_target()
  422. {
  423. auto& env = get_this_environment(*this);
  424. return verify_cast<FunctionEnvironment>(env).new_target();
  425. }
  426. // NOTE: This is only here because there's a million invocations of vm.call() - it used to be tied to the VM in weird ways.
  427. // We should update all of those and then remove this, along with the call() template functions in VM.h, and use the standalone call() AO.
  428. ThrowCompletionOr<Value> VM::call_internal(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments)
  429. {
  430. VERIFY(!exception());
  431. VERIFY(!this_value.is_empty());
  432. return JS::call_impl(function.global_object(), &function, this_value, move(arguments));
  433. }
  434. bool VM::in_strict_mode() const
  435. {
  436. if (execution_context_stack().is_empty())
  437. return false;
  438. return running_execution_context().is_strict_mode;
  439. }
  440. void VM::run_queued_promise_jobs()
  441. {
  442. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  443. // Temporarily get rid of the exception, if any - job functions must be called
  444. // either way, and that can't happen if we already have an exception stored.
  445. TemporaryClearException temporary_clear_exception(*this);
  446. while (!m_promise_jobs.is_empty()) {
  447. auto* job = m_promise_jobs.take_first();
  448. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  449. // NOTE: If the execution context stack is empty, we make and push a temporary context.
  450. ExecutionContext execution_context(heap());
  451. bool pushed_execution_context = false;
  452. if (m_execution_context_stack.is_empty()) {
  453. static FlyString promise_execution_context_name = "(promise execution context)";
  454. execution_context.function_name = promise_execution_context_name;
  455. // FIXME: Propagate potential failure
  456. MUST(push_execution_context(execution_context, job->global_object()));
  457. pushed_execution_context = true;
  458. }
  459. [[maybe_unused]] auto result = call(*job, js_undefined());
  460. // This doesn't match the spec, it actually defines that Job Abstract Closures must return
  461. // a normal completion. In reality that's not the case however, and all major engines clear
  462. // exceptions when running Promise jobs. See the commit where these two lines were initially
  463. // added for a much more detailed explanation.
  464. clear_exception();
  465. stop_unwind();
  466. if (pushed_execution_context)
  467. pop_execution_context();
  468. }
  469. // Ensure no job has created a new exception, they must clean up after themselves.
  470. // If they don't, we help a little (see above) so that this assumption remains valid.
  471. VERIFY(!m_exception);
  472. }
  473. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  474. void VM::enqueue_promise_job(NativeFunction& job)
  475. {
  476. m_promise_jobs.append(&job);
  477. }
  478. void VM::run_queued_finalization_registry_cleanup_jobs()
  479. {
  480. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  481. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  482. registry->cleanup();
  483. }
  484. }
  485. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  486. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  487. {
  488. m_finalization_registry_cleanup_jobs.append(&registry);
  489. }
  490. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  491. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  492. {
  493. switch (operation) {
  494. case Promise::RejectionOperation::Reject:
  495. // A promise was rejected without any handlers
  496. if (on_promise_unhandled_rejection)
  497. on_promise_unhandled_rejection(promise);
  498. break;
  499. case Promise::RejectionOperation::Handle:
  500. // A handler was added to an already rejected promise
  501. if (on_promise_rejection_handled)
  502. on_promise_rejection_handled(promise);
  503. break;
  504. default:
  505. VERIFY_NOT_REACHED();
  506. }
  507. }
  508. void VM::dump_backtrace() const
  509. {
  510. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  511. auto& frame = m_execution_context_stack[i];
  512. if (frame->current_node) {
  513. auto& source_range = frame->current_node->source_range();
  514. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename, source_range.start.line, source_range.start.column);
  515. } else {
  516. dbgln("-> {}", frame->function_name);
  517. }
  518. }
  519. }
  520. VM::CustomData::~CustomData()
  521. {
  522. }
  523. void VM::save_execution_context_stack()
  524. {
  525. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  526. }
  527. void VM::restore_execution_context_stack()
  528. {
  529. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  530. }
  531. }