VM.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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/Error.h>
  14. #include <LibJS/Runtime/FinalizationRegistry.h>
  15. #include <LibJS/Runtime/FunctionEnvironmentRecord.h>
  16. #include <LibJS/Runtime/GlobalEnvironmentRecord.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibJS/Runtime/IteratorOperations.h>
  19. #include <LibJS/Runtime/NativeFunction.h>
  20. #include <LibJS/Runtime/PromiseReaction.h>
  21. #include <LibJS/Runtime/Reference.h>
  22. #include <LibJS/Runtime/ScriptFunction.h>
  23. #include <LibJS/Runtime/Symbol.h>
  24. #include <LibJS/Runtime/TemporaryClearException.h>
  25. #include <LibJS/Runtime/VM.h>
  26. namespace JS {
  27. NonnullRefPtr<VM> VM::create()
  28. {
  29. return adopt_ref(*new VM);
  30. }
  31. VM::VM()
  32. : m_heap(*this)
  33. {
  34. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  35. for (size_t i = 0; i < 128; ++i) {
  36. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  37. }
  38. #define __JS_ENUMERATE(SymbolName, snake_name) \
  39. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  40. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  41. #undef __JS_ENUMERATE
  42. }
  43. VM::~VM()
  44. {
  45. }
  46. Interpreter& VM::interpreter()
  47. {
  48. VERIFY(!m_interpreters.is_empty());
  49. return *m_interpreters.last();
  50. }
  51. Interpreter* VM::interpreter_if_exists()
  52. {
  53. if (m_interpreters.is_empty())
  54. return nullptr;
  55. return m_interpreters.last();
  56. }
  57. void VM::push_interpreter(Interpreter& interpreter)
  58. {
  59. m_interpreters.append(&interpreter);
  60. }
  61. void VM::pop_interpreter(Interpreter& interpreter)
  62. {
  63. VERIFY(!m_interpreters.is_empty());
  64. auto* popped_interpreter = m_interpreters.take_last();
  65. VERIFY(popped_interpreter == &interpreter);
  66. }
  67. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  68. : m_interpreter(interpreter)
  69. {
  70. m_interpreter.vm().push_interpreter(m_interpreter);
  71. }
  72. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  73. {
  74. m_interpreter.vm().pop_interpreter(m_interpreter);
  75. }
  76. void VM::gather_roots(HashTable<Cell*>& roots)
  77. {
  78. roots.set(m_empty_string);
  79. for (auto* string : m_single_ascii_character_strings)
  80. roots.set(string);
  81. roots.set(m_exception);
  82. if (m_last_value.is_cell())
  83. roots.set(&m_last_value.as_cell());
  84. for (auto& execution_context : m_execution_context_stack) {
  85. if (execution_context->this_value.is_cell())
  86. roots.set(&execution_context->this_value.as_cell());
  87. roots.set(execution_context->arguments_object);
  88. for (auto& argument : execution_context->arguments) {
  89. if (argument.is_cell())
  90. roots.set(&argument.as_cell());
  91. }
  92. roots.set(execution_context->lexical_environment);
  93. roots.set(execution_context->variable_environment);
  94. }
  95. #define __JS_ENUMERATE(SymbolName, snake_name) \
  96. roots.set(well_known_symbol_##snake_name());
  97. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  98. #undef __JS_ENUMERATE
  99. for (auto& symbol : m_global_symbol_map)
  100. roots.set(symbol.value);
  101. for (auto* job : m_promise_jobs)
  102. roots.set(job);
  103. }
  104. Symbol* VM::get_global_symbol(const String& description)
  105. {
  106. auto result = m_global_symbol_map.get(description);
  107. if (result.has_value())
  108. return result.value();
  109. auto new_global_symbol = js_symbol(*this, description, true);
  110. m_global_symbol_map.set(description, new_global_symbol);
  111. return new_global_symbol;
  112. }
  113. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment, EnvironmentRecord* specific_scope)
  114. {
  115. Optional<Variable> possible_match;
  116. if (!specific_scope && m_execution_context_stack.size()) {
  117. for (auto* environment_record = lexical_environment(); environment_record; environment_record = environment_record->outer_environment()) {
  118. possible_match = environment_record->get_from_environment_record(name);
  119. if (possible_match.has_value()) {
  120. specific_scope = environment_record;
  121. break;
  122. }
  123. }
  124. }
  125. if (specific_scope && possible_match.has_value()) {
  126. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  127. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  128. return;
  129. }
  130. specific_scope->put_into_environment_record(name, { value, possible_match.value().declaration_kind });
  131. return;
  132. }
  133. if (specific_scope) {
  134. specific_scope->put_into_environment_record(name, { value, DeclarationKind::Var });
  135. return;
  136. }
  137. global_object.put(name, value);
  138. }
  139. bool VM::delete_variable(FlyString const& name)
  140. {
  141. EnvironmentRecord* specific_scope = nullptr;
  142. Optional<Variable> possible_match;
  143. if (!m_execution_context_stack.is_empty()) {
  144. for (auto* environment_record = lexical_environment(); environment_record; environment_record = environment_record->outer_environment()) {
  145. possible_match = environment_record->get_from_environment_record(name);
  146. if (possible_match.has_value()) {
  147. specific_scope = environment_record;
  148. break;
  149. }
  150. }
  151. }
  152. if (!possible_match.has_value())
  153. return false;
  154. if (possible_match.value().declaration_kind == DeclarationKind::Const)
  155. return false;
  156. VERIFY(specific_scope);
  157. return specific_scope->delete_from_environment_record(name);
  158. }
  159. void VM::assign(const FlyString& target, Value value, GlobalObject& global_object, bool first_assignment, EnvironmentRecord* specific_scope)
  160. {
  161. set_variable(target, move(value), global_object, first_assignment, specific_scope);
  162. }
  163. void VM::assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value value, GlobalObject& global_object, bool first_assignment, EnvironmentRecord* specific_scope)
  164. {
  165. if (auto id_ptr = target.get_pointer<NonnullRefPtr<Identifier>>())
  166. return assign((*id_ptr)->string(), move(value), global_object, first_assignment, specific_scope);
  167. assign(target.get<NonnullRefPtr<BindingPattern>>(), move(value), global_object, first_assignment, specific_scope);
  168. }
  169. void VM::assign(const NonnullRefPtr<BindingPattern>& target, Value value, GlobalObject& global_object, bool first_assignment, EnvironmentRecord* specific_scope)
  170. {
  171. auto& binding = *target;
  172. switch (binding.kind) {
  173. case BindingPattern::Kind::Array: {
  174. auto iterator = get_iterator(global_object, value);
  175. if (!iterator)
  176. return;
  177. for (size_t i = 0; i < binding.entries.size(); i++) {
  178. if (exception())
  179. return;
  180. auto& entry = binding.entries[i];
  181. if (entry.is_rest) {
  182. VERIFY(i == binding.entries.size() - 1);
  183. auto* array = Array::create(global_object);
  184. for (;;) {
  185. auto next_object = iterator_next(*iterator);
  186. if (!next_object)
  187. return;
  188. auto done_property = next_object->get(names.done);
  189. if (exception())
  190. return;
  191. if (!done_property.is_empty() && done_property.to_boolean())
  192. break;
  193. auto next_value = next_object->get(names.value);
  194. if (exception())
  195. return;
  196. array->indexed_properties().append(next_value);
  197. }
  198. value = array;
  199. } else if (iterator) {
  200. auto next_object = iterator_next(*iterator);
  201. if (!next_object)
  202. return;
  203. auto done_property = next_object->get(names.done);
  204. if (exception())
  205. return;
  206. if (!done_property.is_empty() && done_property.to_boolean()) {
  207. iterator = nullptr;
  208. value = js_undefined();
  209. } else {
  210. value = next_object->get(names.value);
  211. if (exception())
  212. return;
  213. }
  214. } else {
  215. value = js_undefined();
  216. }
  217. if (value.is_undefined() && entry.initializer) {
  218. value = entry.initializer->execute(interpreter(), global_object);
  219. if (exception())
  220. return;
  221. }
  222. entry.alias.visit(
  223. [&](Empty) {},
  224. [&](NonnullRefPtr<Identifier> const& identifier) {
  225. set_variable(identifier->string(), value, global_object, first_assignment, specific_scope);
  226. },
  227. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  228. assign(pattern, value, global_object, first_assignment, specific_scope);
  229. });
  230. if (entry.is_rest)
  231. break;
  232. }
  233. break;
  234. }
  235. case BindingPattern::Kind::Object: {
  236. auto object = value.to_object(global_object);
  237. HashTable<PropertyName, PropertyNameTraits> seen_names;
  238. for (auto& property : binding.entries) {
  239. VERIFY(!property.is_elision());
  240. PropertyName assignment_name;
  241. JS::Value value_to_assign;
  242. if (property.is_rest) {
  243. VERIFY(property.name.has<NonnullRefPtr<Identifier>>());
  244. assignment_name = property.name.get<NonnullRefPtr<Identifier>>()->string();
  245. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  246. for (auto& object_property : object->shape().property_table()) {
  247. if (!object_property.value.attributes.has_enumerable())
  248. continue;
  249. if (seen_names.contains(object_property.key.to_display_string()))
  250. continue;
  251. rest_object->put(object_property.key, object->get(object_property.key));
  252. if (exception())
  253. return;
  254. }
  255. value_to_assign = rest_object;
  256. } else {
  257. property.name.visit(
  258. [&](Empty) { VERIFY_NOT_REACHED(); },
  259. [&](NonnullRefPtr<Identifier> const& identifier) {
  260. assignment_name = identifier->string();
  261. },
  262. [&](NonnullRefPtr<Expression> const& expression) {
  263. auto result = expression->execute(interpreter(), global_object);
  264. if (exception())
  265. return;
  266. assignment_name = result.to_property_key(global_object);
  267. });
  268. if (exception())
  269. break;
  270. value_to_assign = object->get(assignment_name);
  271. }
  272. seen_names.set(assignment_name);
  273. if (value_to_assign.is_empty())
  274. value_to_assign = js_undefined();
  275. if (value_to_assign.is_undefined() && property.initializer)
  276. value_to_assign = property.initializer->execute(interpreter(), global_object);
  277. if (exception())
  278. break;
  279. property.alias.visit(
  280. [&](Empty) {
  281. set_variable(assignment_name.to_string(), value_to_assign, global_object, first_assignment, specific_scope);
  282. },
  283. [&](NonnullRefPtr<Identifier> const& identifier) {
  284. VERIFY(!property.is_rest);
  285. set_variable(identifier->string(), value_to_assign, global_object, first_assignment, specific_scope);
  286. },
  287. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  288. VERIFY(!property.is_rest);
  289. assign(pattern, value_to_assign, global_object, first_assignment, specific_scope);
  290. });
  291. if (property.is_rest)
  292. break;
  293. }
  294. break;
  295. }
  296. }
  297. }
  298. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  299. {
  300. if (!m_execution_context_stack.is_empty()) {
  301. auto& context = running_execution_context();
  302. if (name == names.arguments.as_string() && context.function) {
  303. // HACK: Special handling for the name "arguments":
  304. // If the name "arguments" is defined in the current scope, for example via
  305. // a function parameter, or by a local var declaration, we use that.
  306. // Otherwise, we return a lazily constructed Array with all the argument values.
  307. // FIXME: Do something much more spec-compliant.
  308. auto possible_match = lexical_environment()->get_from_environment_record(name);
  309. if (possible_match.has_value())
  310. return possible_match.value().value;
  311. if (!context.arguments_object) {
  312. context.arguments_object = Array::create(global_object);
  313. context.arguments_object->put(names.callee, context.function);
  314. for (auto argument : context.arguments) {
  315. context.arguments_object->indexed_properties().append(argument);
  316. }
  317. }
  318. return context.arguments_object;
  319. }
  320. for (auto* environment_record = lexical_environment(); environment_record; environment_record = environment_record->outer_environment()) {
  321. auto possible_match = environment_record->get_from_environment_record(name);
  322. if (exception())
  323. return {};
  324. if (possible_match.has_value())
  325. return possible_match.value().value;
  326. }
  327. }
  328. auto value = global_object.get(name);
  329. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  330. return m_last_value;
  331. return value;
  332. }
  333. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  334. Reference VM::resolve_binding(FlyString const& name)
  335. {
  336. // FIXME: This implementation of ResolveBinding is non-conforming.
  337. for (auto* environment_record = lexical_environment(); environment_record && environment_record->outer_environment(); environment_record = environment_record->outer_environment()) {
  338. auto possible_match = environment_record->get_from_environment_record(name);
  339. if (possible_match.has_value())
  340. return { Reference::LocalVariable, name };
  341. }
  342. return { Reference::GlobalVariable, name };
  343. }
  344. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments)
  345. {
  346. auto& global_object = function.global_object();
  347. ExecutionContext execution_context;
  348. execution_context.function = &function;
  349. if (auto* interpreter = interpreter_if_exists())
  350. execution_context.current_node = interpreter->current_node();
  351. execution_context.is_strict_mode = function.is_strict_mode();
  352. push_execution_context(execution_context, global_object);
  353. if (exception())
  354. return {};
  355. ArmedScopeGuard pop_guard = [&] {
  356. pop_execution_context();
  357. };
  358. execution_context.function_name = function.name();
  359. execution_context.arguments = function.bound_arguments();
  360. if (arguments.has_value())
  361. execution_context.arguments.extend(arguments.value().values());
  362. auto* environment = function.create_environment_record();
  363. execution_context.lexical_environment = environment;
  364. execution_context.variable_environment = environment;
  365. if (environment)
  366. environment->set_new_target(&new_target);
  367. Object* new_object = nullptr;
  368. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  369. new_object = Object::create(global_object, nullptr);
  370. if (environment)
  371. environment->bind_this_value(global_object, new_object);
  372. if (exception())
  373. return {};
  374. auto prototype = new_target.get(names.prototype);
  375. if (exception())
  376. return {};
  377. if (prototype.is_object()) {
  378. new_object->set_prototype(&prototype.as_object());
  379. if (exception())
  380. return {};
  381. }
  382. }
  383. // If we are a Derived constructor, |this| has not been constructed before super is called.
  384. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  385. execution_context.this_value = this_value;
  386. auto result = function.construct(new_target);
  387. if (environment)
  388. this_value = environment->get_this_binding(global_object);
  389. pop_execution_context();
  390. pop_guard.disarm();
  391. // If we are constructing an instance of a derived class,
  392. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  393. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  394. if (environment) {
  395. verify_cast<FunctionEnvironmentRecord>(lexical_environment())->replace_this_binding(result);
  396. }
  397. auto prototype = new_target.get(names.prototype);
  398. if (exception())
  399. return {};
  400. if (prototype.is_object()) {
  401. result.as_object().set_prototype(&prototype.as_object());
  402. if (exception())
  403. return {};
  404. }
  405. return result;
  406. }
  407. if (exception())
  408. return {};
  409. if (result.is_object())
  410. return result;
  411. return this_value;
  412. }
  413. void VM::throw_exception(Exception& exception)
  414. {
  415. set_exception(exception);
  416. unwind(ScopeType::Try);
  417. }
  418. String VM::join_arguments(size_t start_index) const
  419. {
  420. StringBuilder joined_arguments;
  421. for (size_t i = start_index; i < argument_count(); ++i) {
  422. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  423. if (i != argument_count() - 1)
  424. joined_arguments.append(' ');
  425. }
  426. return joined_arguments.build();
  427. }
  428. Value VM::get_new_target()
  429. {
  430. auto& env = get_this_environment(*this);
  431. return verify_cast<FunctionEnvironmentRecord>(env).new_target();
  432. }
  433. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  434. {
  435. VERIFY(!exception());
  436. VERIFY(!this_value.is_empty());
  437. ExecutionContext execution_context;
  438. execution_context.function = &function;
  439. if (auto* interpreter = interpreter_if_exists())
  440. execution_context.current_node = interpreter->current_node();
  441. execution_context.is_strict_mode = function.is_strict_mode();
  442. execution_context.function_name = function.name();
  443. execution_context.this_value = function.bound_this().value_or(this_value);
  444. execution_context.arguments = function.bound_arguments();
  445. if (arguments.has_value())
  446. execution_context.arguments.extend(arguments.value().values());
  447. auto* environment = function.create_environment_record();
  448. execution_context.lexical_environment = environment;
  449. execution_context.variable_environment = environment;
  450. if (environment) {
  451. VERIFY(environment->this_binding_status() == FunctionEnvironmentRecord::ThisBindingStatus::Uninitialized);
  452. environment->bind_this_value(function.global_object(), execution_context.this_value);
  453. }
  454. if (exception())
  455. return {};
  456. push_execution_context(execution_context, function.global_object());
  457. if (exception())
  458. return {};
  459. auto result = function.call();
  460. pop_execution_context();
  461. return result;
  462. }
  463. bool VM::in_strict_mode() const
  464. {
  465. if (execution_context_stack().is_empty())
  466. return false;
  467. return running_execution_context().is_strict_mode;
  468. }
  469. void VM::run_queued_promise_jobs()
  470. {
  471. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  472. // Temporarily get rid of the exception, if any - job functions must be called
  473. // either way, and that can't happen if we already have an exception stored.
  474. TemporaryClearException clear_exception(*this);
  475. while (!m_promise_jobs.is_empty()) {
  476. auto* job = m_promise_jobs.take_first();
  477. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  478. [[maybe_unused]] auto result = call(*job, js_undefined());
  479. }
  480. // Ensure no job has created a new exception, they must clean up after themselves.
  481. VERIFY(!m_exception);
  482. }
  483. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  484. void VM::enqueue_promise_job(NativeFunction& job)
  485. {
  486. m_promise_jobs.append(&job);
  487. }
  488. void VM::run_queued_finalization_registry_cleanup_jobs()
  489. {
  490. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  491. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  492. registry->cleanup();
  493. }
  494. }
  495. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  496. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  497. {
  498. m_finalization_registry_cleanup_jobs.append(&registry);
  499. }
  500. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  501. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  502. {
  503. switch (operation) {
  504. case Promise::RejectionOperation::Reject:
  505. // A promise was rejected without any handlers
  506. if (on_promise_unhandled_rejection)
  507. on_promise_unhandled_rejection(promise);
  508. break;
  509. case Promise::RejectionOperation::Handle:
  510. // A handler was added to an already rejected promise
  511. if (on_promise_rejection_handled)
  512. on_promise_rejection_handled(promise);
  513. break;
  514. default:
  515. VERIFY_NOT_REACHED();
  516. }
  517. }
  518. void VM::dump_backtrace() const
  519. {
  520. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i)
  521. dbgln("-> {}", m_execution_context_stack[i]->function_name);
  522. }
  523. void VM::dump_environment_record_chain() const
  524. {
  525. for (auto* environment_record = lexical_environment(); environment_record; environment_record = environment_record->outer_environment()) {
  526. dbgln("+> {} ({:p})", environment_record->class_name(), environment_record);
  527. if (is<DeclarativeEnvironmentRecord>(*environment_record)) {
  528. auto& declarative_environment_record = static_cast<DeclarativeEnvironmentRecord const&>(*environment_record);
  529. for (auto& variable : declarative_environment_record.variables()) {
  530. dbgln(" {}", variable.key);
  531. }
  532. }
  533. }
  534. }
  535. }