VM.cpp 22 KB

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