VM.cpp 30 KB

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