VM.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibJS/Interpreter.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/BoundFunction.h>
  14. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  15. #include <LibJS/Runtime/Error.h>
  16. #include <LibJS/Runtime/FinalizationRegistry.h>
  17. #include <LibJS/Runtime/FunctionEnvironment.h>
  18. #include <LibJS/Runtime/GlobalEnvironment.h>
  19. #include <LibJS/Runtime/GlobalObject.h>
  20. #include <LibJS/Runtime/IteratorOperations.h>
  21. #include <LibJS/Runtime/NativeFunction.h>
  22. #include <LibJS/Runtime/PromiseReaction.h>
  23. #include <LibJS/Runtime/Reference.h>
  24. #include <LibJS/Runtime/Symbol.h>
  25. #include <LibJS/Runtime/TemporaryClearException.h>
  26. #include <LibJS/Runtime/VM.h>
  27. namespace JS {
  28. NonnullRefPtr<VM> VM::create(OwnPtr<CustomData> custom_data)
  29. {
  30. return adopt_ref(*new VM(move(custom_data)));
  31. }
  32. VM::VM(OwnPtr<CustomData> custom_data)
  33. : m_heap(*this)
  34. , m_custom_data(move(custom_data))
  35. {
  36. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  37. for (size_t i = 0; i < 128; ++i) {
  38. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  39. }
  40. #define __JS_ENUMERATE(SymbolName, snake_name) \
  41. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  42. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  43. #undef __JS_ENUMERATE
  44. }
  45. VM::~VM()
  46. {
  47. }
  48. Interpreter& VM::interpreter()
  49. {
  50. VERIFY(!m_interpreters.is_empty());
  51. return *m_interpreters.last();
  52. }
  53. Interpreter* VM::interpreter_if_exists()
  54. {
  55. if (m_interpreters.is_empty())
  56. return nullptr;
  57. return m_interpreters.last();
  58. }
  59. void VM::push_interpreter(Interpreter& interpreter)
  60. {
  61. m_interpreters.append(&interpreter);
  62. }
  63. void VM::pop_interpreter(Interpreter& interpreter)
  64. {
  65. VERIFY(!m_interpreters.is_empty());
  66. auto* popped_interpreter = m_interpreters.take_last();
  67. VERIFY(popped_interpreter == &interpreter);
  68. }
  69. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  70. : m_interpreter(interpreter)
  71. {
  72. m_interpreter.vm().push_interpreter(m_interpreter);
  73. }
  74. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  75. {
  76. m_interpreter.vm().pop_interpreter(m_interpreter);
  77. }
  78. void VM::gather_roots(HashTable<Cell*>& roots)
  79. {
  80. roots.set(m_empty_string);
  81. for (auto* string : m_single_ascii_character_strings)
  82. roots.set(string);
  83. roots.set(m_exception);
  84. if (m_last_value.is_cell())
  85. roots.set(&m_last_value.as_cell());
  86. for (auto& execution_context : m_execution_context_stack) {
  87. if (execution_context->this_value.is_cell())
  88. roots.set(&execution_context->this_value.as_cell());
  89. roots.set(execution_context->arguments_object);
  90. for (auto& argument : execution_context->arguments) {
  91. if (argument.is_cell())
  92. roots.set(&argument.as_cell());
  93. }
  94. roots.set(execution_context->lexical_environment);
  95. roots.set(execution_context->variable_environment);
  96. }
  97. #define __JS_ENUMERATE(SymbolName, snake_name) \
  98. roots.set(well_known_symbol_##snake_name());
  99. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  100. #undef __JS_ENUMERATE
  101. for (auto& symbol : m_global_symbol_map)
  102. roots.set(symbol.value);
  103. for (auto* job : m_promise_jobs)
  104. roots.set(job);
  105. for (auto* finalization_registry : m_finalization_registry_cleanup_jobs)
  106. roots.set(finalization_registry);
  107. }
  108. Symbol* VM::get_global_symbol(const String& description)
  109. {
  110. auto result = m_global_symbol_map.get(description);
  111. if (result.has_value())
  112. return result.value();
  113. auto new_global_symbol = js_symbol(*this, description, true);
  114. m_global_symbol_map.set(description, new_global_symbol);
  115. return new_global_symbol;
  116. }
  117. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  118. {
  119. Optional<Variable> possible_match;
  120. if (!specific_scope && m_execution_context_stack.size()) {
  121. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  122. possible_match = environment->get_from_environment(name);
  123. if (possible_match.has_value()) {
  124. specific_scope = environment;
  125. break;
  126. }
  127. }
  128. }
  129. if (specific_scope && possible_match.has_value()) {
  130. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  131. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  132. return;
  133. }
  134. specific_scope->put_into_environment(name, { value, possible_match.value().declaration_kind });
  135. return;
  136. }
  137. if (specific_scope) {
  138. specific_scope->put_into_environment(name, { value, DeclarationKind::Var });
  139. return;
  140. }
  141. global_object.set(name, value, Object::ShouldThrowExceptions::Yes);
  142. }
  143. bool VM::delete_variable(FlyString const& name)
  144. {
  145. Environment* specific_scope = nullptr;
  146. Optional<Variable> possible_match;
  147. if (!m_execution_context_stack.is_empty()) {
  148. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  149. possible_match = environment->get_from_environment(name);
  150. if (possible_match.has_value()) {
  151. specific_scope = environment;
  152. break;
  153. }
  154. }
  155. }
  156. if (!possible_match.has_value())
  157. return false;
  158. if (possible_match.value().declaration_kind == DeclarationKind::Const)
  159. return false;
  160. VERIFY(specific_scope);
  161. return specific_scope->delete_from_environment(name);
  162. }
  163. void VM::assign(const FlyString& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  164. {
  165. set_variable(target, move(value), global_object, first_assignment, specific_scope);
  166. }
  167. void VM::assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  168. {
  169. if (auto id_ptr = target.get_pointer<NonnullRefPtr<Identifier>>())
  170. return assign((*id_ptr)->string(), move(value), global_object, first_assignment, specific_scope);
  171. assign(target.get<NonnullRefPtr<BindingPattern>>(), move(value), global_object, first_assignment, specific_scope);
  172. }
  173. void VM::assign(const NonnullRefPtr<BindingPattern>& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  174. {
  175. auto& binding = *target;
  176. switch (binding.kind) {
  177. case BindingPattern::Kind::Array: {
  178. auto iterator = get_iterator(global_object, value);
  179. if (!iterator)
  180. return;
  181. for (size_t i = 0; i < binding.entries.size(); i++) {
  182. if (exception())
  183. return;
  184. auto& entry = binding.entries[i];
  185. if (entry.is_rest) {
  186. VERIFY(i == binding.entries.size() - 1);
  187. auto* array = Array::create(global_object, 0);
  188. for (;;) {
  189. auto next_object = iterator_next(*iterator);
  190. if (!next_object)
  191. return;
  192. auto done_property = next_object->get(names.done);
  193. if (exception())
  194. return;
  195. if (done_property.to_boolean())
  196. break;
  197. auto next_value = next_object->get(names.value);
  198. if (exception())
  199. return;
  200. array->indexed_properties().append(next_value);
  201. }
  202. value = array;
  203. } else if (iterator) {
  204. auto next_object = iterator_next(*iterator);
  205. if (!next_object)
  206. return;
  207. auto done_property = next_object->get(names.done);
  208. if (exception())
  209. return;
  210. if (done_property.to_boolean()) {
  211. iterator = nullptr;
  212. value = js_undefined();
  213. } else {
  214. value = next_object->get(names.value);
  215. if (exception())
  216. return;
  217. }
  218. } else {
  219. value = js_undefined();
  220. }
  221. if (value.is_undefined() && entry.initializer) {
  222. value = entry.initializer->execute(interpreter(), global_object);
  223. if (exception())
  224. return;
  225. }
  226. entry.alias.visit(
  227. [&](Empty) {},
  228. [&](NonnullRefPtr<Identifier> const& identifier) {
  229. set_variable(identifier->string(), value, global_object, first_assignment, specific_scope);
  230. },
  231. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  232. assign(pattern, value, global_object, first_assignment, specific_scope);
  233. });
  234. if (entry.is_rest)
  235. break;
  236. }
  237. break;
  238. }
  239. case BindingPattern::Kind::Object: {
  240. auto object = value.to_object(global_object);
  241. HashTable<PropertyName, PropertyNameTraits> seen_names;
  242. for (auto& property : binding.entries) {
  243. VERIFY(!property.is_elision());
  244. PropertyName assignment_name;
  245. JS::Value value_to_assign;
  246. if (property.is_rest) {
  247. VERIFY(property.name.has<NonnullRefPtr<Identifier>>());
  248. assignment_name = property.name.get<NonnullRefPtr<Identifier>>()->string();
  249. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  250. for (auto& object_property : object->shape().property_table()) {
  251. if (!object_property.value.attributes.is_enumerable())
  252. continue;
  253. if (seen_names.contains(object_property.key.to_display_string()))
  254. continue;
  255. rest_object->set(object_property.key, object->get(object_property.key), Object::ShouldThrowExceptions::Yes);
  256. if (exception())
  257. return;
  258. }
  259. value_to_assign = rest_object;
  260. } else {
  261. property.name.visit(
  262. [&](Empty) { VERIFY_NOT_REACHED(); },
  263. [&](NonnullRefPtr<Identifier> const& identifier) {
  264. assignment_name = identifier->string();
  265. },
  266. [&](NonnullRefPtr<Expression> const& expression) {
  267. auto result = expression->execute(interpreter(), global_object);
  268. if (exception())
  269. return;
  270. assignment_name = result.to_property_key(global_object);
  271. });
  272. if (exception())
  273. break;
  274. value_to_assign = object->get(assignment_name);
  275. }
  276. seen_names.set(assignment_name);
  277. if (value_to_assign.is_empty())
  278. value_to_assign = js_undefined();
  279. if (value_to_assign.is_undefined() && property.initializer)
  280. value_to_assign = property.initializer->execute(interpreter(), global_object);
  281. if (exception())
  282. break;
  283. property.alias.visit(
  284. [&](Empty) {
  285. set_variable(assignment_name.to_string(), value_to_assign, global_object, first_assignment, specific_scope);
  286. },
  287. [&](NonnullRefPtr<Identifier> const& identifier) {
  288. VERIFY(!property.is_rest);
  289. set_variable(identifier->string(), value_to_assign, global_object, first_assignment, specific_scope);
  290. },
  291. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  292. VERIFY(!property.is_rest);
  293. assign(pattern, value_to_assign, global_object, first_assignment, specific_scope);
  294. });
  295. if (property.is_rest)
  296. break;
  297. }
  298. break;
  299. }
  300. }
  301. }
  302. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  303. {
  304. if (!m_execution_context_stack.is_empty()) {
  305. auto& context = running_execution_context();
  306. if (name == names.arguments.as_string() && context.function) {
  307. // HACK: Special handling for the name "arguments":
  308. // If the name "arguments" is defined in the current scope, for example via
  309. // a function parameter, or by a local var declaration, we use that.
  310. // Otherwise, we return a lazily constructed Array with all the argument values.
  311. // FIXME: Do something much more spec-compliant.
  312. auto possible_match = lexical_environment()->get_from_environment(name);
  313. if (possible_match.has_value())
  314. return possible_match.value().value;
  315. if (!context.arguments_object) {
  316. if (context.function->is_strict_mode() || !context.function->has_simple_parameter_list()) {
  317. context.arguments_object = create_unmapped_arguments_object(global_object, context.arguments.span());
  318. } else {
  319. context.arguments_object = create_mapped_arguments_object(global_object, *context.function, verify_cast<ECMAScriptFunctionObject>(context.function)->formal_parameters(), context.arguments.span(), *lexical_environment());
  320. }
  321. }
  322. return context.arguments_object;
  323. }
  324. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  325. auto possible_match = environment->get_from_environment(name);
  326. if (exception())
  327. return {};
  328. if (possible_match.has_value())
  329. return possible_match.value().value;
  330. if (environment->has_binding(name))
  331. return environment->get_binding_value(global_object, name, false);
  332. }
  333. }
  334. if (!global_object.storage_has(name)) {
  335. if (m_underscore_is_last_value && name == "_")
  336. return m_last_value;
  337. return {};
  338. }
  339. return global_object.get(name);
  340. }
  341. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  342. Reference VM::get_identifier_reference(Environment* environment, FlyString name, bool strict)
  343. {
  344. // 1. If env is the value null, then
  345. if (!environment) {
  346. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  347. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  348. }
  349. // FIXME: The remainder of this function is non-conforming.
  350. for (; environment && environment->outer_environment(); environment = environment->outer_environment()) {
  351. auto possible_match = environment->get_from_environment(name);
  352. if (possible_match.has_value())
  353. return Reference { *environment, move(name), strict };
  354. if (environment->has_binding(name))
  355. return Reference { *environment, move(name), strict };
  356. }
  357. auto& global_environment = interpreter().realm().global_environment();
  358. if (global_environment.has_binding(name) || !in_strict_mode()) {
  359. return Reference { global_environment, move(name), strict };
  360. }
  361. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  362. }
  363. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  364. Reference VM::resolve_binding(FlyString const& name, Environment* environment)
  365. {
  366. // 1. If env is not present or if env is undefined, then
  367. if (!environment) {
  368. // a. Set env to the running execution context's LexicalEnvironment.
  369. environment = running_execution_context().lexical_environment;
  370. }
  371. // 2. Assert: env is an Environment Record.
  372. VERIFY(environment);
  373. // 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.
  374. bool strict = in_strict_mode();
  375. // 4. Return ? GetIdentifierReference(env, name, strict).
  376. return get_identifier_reference(environment, name, strict);
  377. }
  378. static void append_bound_and_passed_arguments(MarkedValueList& arguments, Vector<Value> bound_arguments, Optional<MarkedValueList> passed_arguments)
  379. {
  380. arguments.ensure_capacity(bound_arguments.size());
  381. arguments.extend(move(bound_arguments));
  382. if (passed_arguments.has_value()) {
  383. auto arguments_list = move(passed_arguments.release_value().values());
  384. arguments.grow_capacity(arguments_list.size());
  385. arguments.extend(move(arguments_list));
  386. }
  387. }
  388. // 7.3.32 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  389. void VM::initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor)
  390. {
  391. for (auto& field : constructor.fields()) {
  392. field.define_field(*this, object);
  393. if (exception())
  394. return;
  395. }
  396. }
  397. // FIXME: This function should not exist as-is, most of it should be moved to the individual
  398. // [[Construct]] implementations so that this becomes the Construct() AO (3 steps).
  399. Value VM::construct(FunctionObject& function, FunctionObject& new_target, Optional<MarkedValueList> arguments)
  400. {
  401. auto& global_object = function.global_object();
  402. Value this_argument;
  403. if (!is<ECMAScriptFunctionObject>(function) || static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base)
  404. this_argument = TRY_OR_DISCARD(ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype));
  405. // FIXME: prepare_for_ordinary_call() is not supposed to receive a BoundFunction, ProxyObject, etc. - ever.
  406. // This needs to be moved to NativeFunction/ECMAScriptFunctionObject's construct() (10.2.2 [[Construct]])
  407. ExecutionContext callee_context(heap());
  408. prepare_for_ordinary_call(function, callee_context, &new_target);
  409. if (exception())
  410. return {};
  411. ArmedScopeGuard pop_guard = [&] {
  412. pop_execution_context();
  413. };
  414. if (auto* interpreter = interpreter_if_exists())
  415. callee_context.current_node = interpreter->current_node();
  416. append_bound_and_passed_arguments(callee_context.arguments, function.bound_arguments(), move(arguments));
  417. if (auto* environment = callee_context.lexical_environment) {
  418. auto& function_environment = verify_cast<FunctionEnvironment>(*environment);
  419. function_environment.set_new_target(&new_target);
  420. if (!this_argument.is_empty() && function_environment.this_binding_status() != FunctionEnvironment::ThisBindingStatus::Lexical) {
  421. function_environment.bind_this_value(global_object, this_argument);
  422. if (exception())
  423. return {};
  424. }
  425. }
  426. // If we are a Derived constructor, |this| has not been constructed before super is called.
  427. callee_context.this_value = this_argument;
  428. if (is<ECMAScriptFunctionObject>(function) && static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base) {
  429. VERIFY(this_argument.is_object());
  430. initialize_instance_elements(this_argument.as_object(), static_cast<ECMAScriptFunctionObject&>(function));
  431. if (exception())
  432. return {};
  433. }
  434. auto result = function.construct(new_target);
  435. pop_execution_context();
  436. pop_guard.disarm();
  437. // If we are constructing an instance of a derived class,
  438. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  439. if ((!is<ECMAScriptFunctionObject>(function) || static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base)
  440. && is<ECMAScriptFunctionObject>(new_target) && static_cast<ECMAScriptFunctionObject&>(new_target).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Derived
  441. && result.is_object()) {
  442. if (auto* environment = callee_context.lexical_environment)
  443. verify_cast<FunctionEnvironment>(environment)->replace_this_binding(result);
  444. auto prototype = new_target.get(names.prototype);
  445. if (exception())
  446. return {};
  447. if (prototype.is_object()) {
  448. result.as_object().internal_set_prototype_of(&prototype.as_object());
  449. if (exception())
  450. return {};
  451. }
  452. return result;
  453. }
  454. if (exception())
  455. return {};
  456. if (result.is_object())
  457. return result;
  458. if (auto* environment = callee_context.lexical_environment)
  459. return environment->get_this_binding(global_object);
  460. return this_argument;
  461. }
  462. void VM::throw_exception(Exception& exception)
  463. {
  464. set_exception(exception);
  465. unwind(ScopeType::Try);
  466. }
  467. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  468. Value VM::resolve_this_binding(GlobalObject& global_object)
  469. {
  470. auto& environment = get_this_environment(*this);
  471. return environment.get_this_binding(global_object);
  472. }
  473. String VM::join_arguments(size_t start_index) const
  474. {
  475. StringBuilder joined_arguments;
  476. for (size_t i = start_index; i < argument_count(); ++i) {
  477. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  478. if (i != argument_count() - 1)
  479. joined_arguments.append(' ');
  480. }
  481. return joined_arguments.build();
  482. }
  483. Value VM::get_new_target()
  484. {
  485. auto& env = get_this_environment(*this);
  486. return verify_cast<FunctionEnvironment>(env).new_target();
  487. }
  488. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  489. void VM::prepare_for_ordinary_call(FunctionObject& function, ExecutionContext& callee_context, [[maybe_unused]] Object* new_target)
  490. {
  491. // NOTE: This is a LibJS specific hack for NativeFunction to inherit the strictness of its caller.
  492. // FIXME: I feel like we should be able to get rid of this.
  493. if (is<NativeFunction>(function))
  494. callee_context.is_strict_mode = in_strict_mode();
  495. else
  496. callee_context.is_strict_mode = function.is_strict_mode();
  497. // 1. Let callerContext be the running execution context.
  498. // 2. Let calleeContext be a new ECMAScript code execution context.
  499. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  500. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  501. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  502. // 3. Set the Function of calleeContext to F.
  503. callee_context.function = &function;
  504. callee_context.function_name = function.name();
  505. // 4. Let calleeRealm be F.[[Realm]].
  506. auto* callee_realm = function.realm();
  507. // FIXME: See FIXME in VM::call_internal() / VM::construct().
  508. if (!callee_realm)
  509. callee_realm = current_realm();
  510. VERIFY(callee_realm);
  511. // 5. Set the Realm of calleeContext to calleeRealm.
  512. callee_context.realm = callee_realm;
  513. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  514. // FIXME: Our execution context struct currently does not track this item.
  515. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  516. // FIXME: This should call NewFunctionEnvironment instead of the ad-hoc FunctionObject::create_environment()
  517. auto* local_environment = function.create_environment(function);
  518. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  519. callee_context.lexical_environment = local_environment;
  520. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  521. callee_context.variable_environment = local_environment;
  522. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  523. // FIXME: We currently don't support private environments.
  524. // 11. If callerContext is not already suspended, suspend callerContext.
  525. // FIXME: We don't have this concept yet.
  526. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  527. push_execution_context(callee_context, function.global_object());
  528. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  529. // 14. Return calleeContext. (See NOTE above about how contexts are allocated on the C++ stack.)
  530. }
  531. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  532. void VM::ordinary_call_bind_this(FunctionObject& function, ExecutionContext& callee_context, Value this_argument)
  533. {
  534. auto* callee_realm = function.realm();
  535. auto* local_environment = callee_context.lexical_environment;
  536. auto& function_environment = verify_cast<FunctionEnvironment>(*local_environment);
  537. // This almost as the spec describes it however we sometimes don't have callee_realm when dealing
  538. // with proxies and arrow functions however this does seemingly achieve spec like behavior.
  539. if (!callee_realm || (is<ECMAScriptFunctionObject>(function) && static_cast<ECMAScriptFunctionObject&>(function).this_mode() == ECMAScriptFunctionObject::ThisMode::Lexical)) {
  540. return;
  541. }
  542. Value this_value;
  543. if (function.is_strict_mode()) {
  544. this_value = this_argument;
  545. } else if (this_argument.is_nullish()) {
  546. auto& global_environment = callee_realm->global_environment();
  547. this_value = &global_environment.global_this_value();
  548. } else {
  549. this_value = this_argument.to_object(function.global_object());
  550. }
  551. function_environment.bind_this_value(function.global_object(), this_value);
  552. callee_context.this_value = this_value;
  553. }
  554. ThrowCompletionOr<Value> VM::call_internal(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments)
  555. {
  556. VERIFY(!exception());
  557. VERIFY(!this_value.is_empty());
  558. if (is<BoundFunction>(function)) {
  559. auto& bound_function = static_cast<BoundFunction&>(function);
  560. MarkedValueList with_bound_arguments { heap() };
  561. append_bound_and_passed_arguments(with_bound_arguments, bound_function.bound_arguments(), move(arguments));
  562. return call_internal(bound_function.target_function(), bound_function.bound_this(), move(with_bound_arguments));
  563. }
  564. // FIXME: prepare_for_ordinary_call() is not supposed to receive a BoundFunction, ProxyObject, etc. - ever.
  565. // This needs to be moved to NativeFunction/ECMAScriptFunctionObject's construct() (10.2.2 [[Construct]])
  566. ExecutionContext callee_context(heap());
  567. prepare_for_ordinary_call(function, callee_context, nullptr);
  568. if (auto* exception = this->exception())
  569. return JS::throw_completion(exception->value());
  570. ScopeGuard pop_guard = [&] {
  571. pop_execution_context();
  572. };
  573. if (auto* interpreter = interpreter_if_exists())
  574. callee_context.current_node = interpreter->current_node();
  575. callee_context.this_value = function.bound_this().value_or(this_value);
  576. append_bound_and_passed_arguments(callee_context.arguments, function.bound_arguments(), move(arguments));
  577. if (callee_context.lexical_environment)
  578. ordinary_call_bind_this(function, callee_context, this_value);
  579. if (auto* exception = this->exception())
  580. return JS::throw_completion(exception->value());
  581. auto result = function.call();
  582. if (auto* exception = this->exception())
  583. return JS::throw_completion(exception->value());
  584. return result;
  585. }
  586. bool VM::in_strict_mode() const
  587. {
  588. if (execution_context_stack().is_empty())
  589. return false;
  590. return running_execution_context().is_strict_mode;
  591. }
  592. void VM::run_queued_promise_jobs()
  593. {
  594. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  595. // Temporarily get rid of the exception, if any - job functions must be called
  596. // either way, and that can't happen if we already have an exception stored.
  597. TemporaryClearException clear_exception(*this);
  598. while (!m_promise_jobs.is_empty()) {
  599. auto* job = m_promise_jobs.take_first();
  600. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  601. [[maybe_unused]] auto result = call(*job, js_undefined());
  602. }
  603. // Ensure no job has created a new exception, they must clean up after themselves.
  604. VERIFY(!m_exception);
  605. }
  606. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  607. void VM::enqueue_promise_job(NativeFunction& job)
  608. {
  609. m_promise_jobs.append(&job);
  610. }
  611. void VM::run_queued_finalization_registry_cleanup_jobs()
  612. {
  613. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  614. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  615. registry->cleanup();
  616. }
  617. }
  618. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  619. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  620. {
  621. m_finalization_registry_cleanup_jobs.append(&registry);
  622. }
  623. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  624. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  625. {
  626. switch (operation) {
  627. case Promise::RejectionOperation::Reject:
  628. // A promise was rejected without any handlers
  629. if (on_promise_unhandled_rejection)
  630. on_promise_unhandled_rejection(promise);
  631. break;
  632. case Promise::RejectionOperation::Handle:
  633. // A handler was added to an already rejected promise
  634. if (on_promise_rejection_handled)
  635. on_promise_rejection_handled(promise);
  636. break;
  637. default:
  638. VERIFY_NOT_REACHED();
  639. }
  640. }
  641. void VM::dump_backtrace() const
  642. {
  643. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  644. auto& frame = m_execution_context_stack[i];
  645. if (frame->current_node) {
  646. auto& source_range = frame->current_node->source_range();
  647. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename, source_range.start.line, source_range.start.column);
  648. } else {
  649. dbgln("-> {}", frame->function_name);
  650. }
  651. }
  652. }
  653. void VM::dump_environment_chain() const
  654. {
  655. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  656. dbgln("+> {} ({:p})", environment->class_name(), environment);
  657. if (is<DeclarativeEnvironment>(*environment)) {
  658. auto& declarative_environment = static_cast<DeclarativeEnvironment const&>(*environment);
  659. for (auto& variable : declarative_environment.variables()) {
  660. dbgln(" {}", variable.key);
  661. }
  662. }
  663. }
  664. }
  665. VM::CustomData::~CustomData()
  666. {
  667. }
  668. }