VM.cpp 22 KB

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