VM.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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_scope_object_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_scope_object_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->scope);
  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, ScopeObject* specific_scope)
  112. {
  113. Optional<Variable> possible_match;
  114. if (!specific_scope && m_call_stack.size()) {
  115. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  116. possible_match = scope->get_from_scope(name);
  117. if (possible_match.has_value()) {
  118. specific_scope = scope;
  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. ScopeObject* specific_scope = nullptr;
  140. Optional<Variable> possible_match;
  141. if (!m_call_stack.is_empty()) {
  142. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  143. possible_match = scope->get_from_scope(name);
  144. if (possible_match.has_value()) {
  145. specific_scope = scope;
  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, ScopeObject* 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, ScopeObject* 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, ScopeObject* 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. size_t index = 0;
  176. while (true) {
  177. if (exception())
  178. return;
  179. if (index >= binding.properties.size())
  180. break;
  181. auto pattern_property = binding.properties[index];
  182. ++index;
  183. if (pattern_property.is_rest) {
  184. auto* array = Array::create(global_object);
  185. for (;;) {
  186. auto next_object = iterator_next(*iterator);
  187. if (!next_object)
  188. return;
  189. auto done_property = next_object->get(names.done);
  190. if (exception())
  191. return;
  192. if (!done_property.is_empty() && done_property.to_boolean())
  193. break;
  194. auto next_value = next_object->get(names.value);
  195. if (exception())
  196. return;
  197. array->indexed_properties().append(next_value);
  198. }
  199. value = array;
  200. } else {
  201. auto next_object = iterator_next(*iterator);
  202. if (!next_object)
  203. return;
  204. auto done_property = next_object->get(names.done);
  205. if (exception())
  206. return;
  207. if (!done_property.is_empty() && done_property.to_boolean())
  208. break;
  209. value = next_object->get(names.value);
  210. if (exception())
  211. return;
  212. }
  213. if (value.is_undefined() && pattern_property.initializer)
  214. value = pattern_property.initializer->execute(interpreter(), global_object);
  215. if (exception())
  216. return;
  217. if (pattern_property.name) {
  218. set_variable(pattern_property.name->string(), value, global_object, first_assignment, specific_scope);
  219. if (pattern_property.is_rest)
  220. break;
  221. continue;
  222. }
  223. if (pattern_property.pattern) {
  224. assign(NonnullRefPtr(*pattern_property.pattern), value, global_object, first_assignment, specific_scope);
  225. if (pattern_property.is_rest)
  226. break;
  227. continue;
  228. }
  229. }
  230. break;
  231. }
  232. case BindingPattern::Kind::Object: {
  233. auto object = value.to_object(global_object);
  234. HashTable<FlyString> seen_names;
  235. for (auto& property : binding.properties) {
  236. VERIFY(!property.pattern);
  237. JS::Value value_to_assign;
  238. if (property.is_rest) {
  239. auto* rest_object = Object::create(global_object, nullptr);
  240. for (auto& property : object->shape().property_table()) {
  241. if (!property.value.attributes.has_enumerable())
  242. continue;
  243. if (seen_names.contains(property.key.to_display_string()))
  244. continue;
  245. rest_object->put(property.key, object->get(property.key));
  246. if (exception())
  247. return;
  248. }
  249. value_to_assign = rest_object;
  250. } else {
  251. value_to_assign = object->get(property.name->string());
  252. }
  253. seen_names.set(property.name->string());
  254. if (exception())
  255. break;
  256. auto assignment_name = property.name->string();
  257. if (property.alias)
  258. assignment_name = property.alias->string();
  259. if (value_to_assign.is_empty())
  260. value_to_assign = js_undefined();
  261. if (value_to_assign.is_undefined() && property.initializer)
  262. value_to_assign = property.initializer->execute(interpreter(), global_object);
  263. if (exception())
  264. break;
  265. set_variable(assignment_name, value_to_assign, global_object, first_assignment, specific_scope);
  266. if (property.is_rest)
  267. break;
  268. }
  269. break;
  270. }
  271. }
  272. }
  273. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  274. {
  275. if (!m_call_stack.is_empty()) {
  276. if (name == names.arguments.as_string() && !call_frame().callee.is_empty()) {
  277. // HACK: Special handling for the name "arguments":
  278. // If the name "arguments" is defined in the current scope, for example via
  279. // a function parameter, or by a local var declaration, we use that.
  280. // Otherwise, we return a lazily constructed Array with all the argument values.
  281. // FIXME: Do something much more spec-compliant.
  282. auto possible_match = current_scope()->get_from_scope(name);
  283. if (possible_match.has_value())
  284. return possible_match.value().value;
  285. if (!call_frame().arguments_object) {
  286. call_frame().arguments_object = Array::create(global_object);
  287. call_frame().arguments_object->put(names.callee, call_frame().callee);
  288. for (auto argument : call_frame().arguments) {
  289. call_frame().arguments_object->indexed_properties().append(argument);
  290. }
  291. }
  292. return call_frame().arguments_object;
  293. }
  294. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  295. auto possible_match = scope->get_from_scope(name);
  296. if (exception())
  297. return {};
  298. if (possible_match.has_value())
  299. return possible_match.value().value;
  300. }
  301. }
  302. auto value = global_object.get(name);
  303. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  304. return m_last_value;
  305. return value;
  306. }
  307. Reference VM::get_reference(const FlyString& name)
  308. {
  309. if (m_call_stack.size()) {
  310. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  311. if (is<GlobalObject>(scope))
  312. break;
  313. auto possible_match = scope->get_from_scope(name);
  314. if (possible_match.has_value())
  315. return { Reference::LocalVariable, name };
  316. }
  317. }
  318. return { Reference::GlobalVariable, name };
  319. }
  320. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments)
  321. {
  322. auto& global_object = function.global_object();
  323. CallFrame call_frame;
  324. call_frame.callee = &function;
  325. if (auto* interpreter = interpreter_if_exists())
  326. call_frame.current_node = interpreter->current_node();
  327. call_frame.is_strict_mode = function.is_strict_mode();
  328. push_call_frame(call_frame, global_object);
  329. if (exception())
  330. return {};
  331. ArmedScopeGuard call_frame_popper = [&] {
  332. pop_call_frame();
  333. };
  334. call_frame.function_name = function.name();
  335. call_frame.arguments = function.bound_arguments();
  336. if (arguments.has_value())
  337. call_frame.arguments.extend(arguments.value().values());
  338. auto* environment = function.create_environment();
  339. call_frame.scope = environment;
  340. if (environment)
  341. environment->set_new_target(&new_target);
  342. Object* new_object = nullptr;
  343. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  344. new_object = Object::create(global_object, nullptr);
  345. if (environment)
  346. environment->bind_this_value(global_object, new_object);
  347. if (exception())
  348. return {};
  349. auto prototype = new_target.get(names.prototype);
  350. if (exception())
  351. return {};
  352. if (prototype.is_object()) {
  353. new_object->set_prototype(&prototype.as_object());
  354. if (exception())
  355. return {};
  356. }
  357. }
  358. // If we are a Derived constructor, |this| has not been constructed before super is called.
  359. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  360. call_frame.this_value = this_value;
  361. auto result = function.construct(new_target);
  362. if (environment)
  363. this_value = environment->get_this_binding(global_object);
  364. pop_call_frame();
  365. call_frame_popper.disarm();
  366. // If we are constructing an instance of a derived class,
  367. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  368. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  369. if (environment) {
  370. VERIFY(is<LexicalEnvironment>(current_scope()));
  371. static_cast<LexicalEnvironment*>(current_scope())->replace_this_binding(result);
  372. }
  373. auto prototype = new_target.get(names.prototype);
  374. if (exception())
  375. return {};
  376. if (prototype.is_object()) {
  377. result.as_object().set_prototype(&prototype.as_object());
  378. if (exception())
  379. return {};
  380. }
  381. return result;
  382. }
  383. if (exception())
  384. return {};
  385. if (result.is_object())
  386. return result;
  387. return this_value;
  388. }
  389. void VM::throw_exception(Exception& exception)
  390. {
  391. set_exception(exception);
  392. unwind(ScopeType::Try);
  393. }
  394. String VM::join_arguments(size_t start_index) const
  395. {
  396. StringBuilder joined_arguments;
  397. for (size_t i = start_index; i < argument_count(); ++i) {
  398. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  399. if (i != argument_count() - 1)
  400. joined_arguments.append(' ');
  401. }
  402. return joined_arguments.build();
  403. }
  404. Value VM::resolve_this_binding(GlobalObject& global_object) const
  405. {
  406. return find_this_scope()->get_this_binding(global_object);
  407. }
  408. const ScopeObject* VM::find_this_scope() const
  409. {
  410. // We will always return because the Global environment will always be reached, which has a |this| binding.
  411. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  412. if (scope->has_this_binding())
  413. return scope;
  414. }
  415. VERIFY_NOT_REACHED();
  416. }
  417. Value VM::get_new_target() const
  418. {
  419. VERIFY(is<LexicalEnvironment>(find_this_scope()));
  420. return static_cast<const LexicalEnvironment*>(find_this_scope())->new_target();
  421. }
  422. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  423. {
  424. VERIFY(!exception());
  425. VERIFY(!this_value.is_empty());
  426. CallFrame call_frame;
  427. call_frame.callee = &function;
  428. if (auto* interpreter = interpreter_if_exists())
  429. call_frame.current_node = interpreter->current_node();
  430. call_frame.is_strict_mode = function.is_strict_mode();
  431. call_frame.function_name = function.name();
  432. call_frame.this_value = function.bound_this().value_or(this_value);
  433. call_frame.arguments = function.bound_arguments();
  434. if (arguments.has_value())
  435. call_frame.arguments.extend(arguments.value().values());
  436. auto* environment = function.create_environment();
  437. call_frame.scope = environment;
  438. if (environment) {
  439. VERIFY(environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  440. environment->bind_this_value(function.global_object(), call_frame.this_value);
  441. }
  442. if (exception())
  443. return {};
  444. push_call_frame(call_frame, function.global_object());
  445. if (exception())
  446. return {};
  447. auto result = function.call();
  448. pop_call_frame();
  449. return result;
  450. }
  451. bool VM::in_strict_mode() const
  452. {
  453. if (call_stack().is_empty())
  454. return false;
  455. return call_frame().is_strict_mode;
  456. }
  457. void VM::run_queued_promise_jobs()
  458. {
  459. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  460. // Temporarily get rid of the exception, if any - job functions must be called
  461. // either way, and that can't happen if we already have an exception stored.
  462. TemporaryClearException clear_exception(*this);
  463. while (!m_promise_jobs.is_empty()) {
  464. auto* job = m_promise_jobs.take_first();
  465. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  466. [[maybe_unused]] auto result = call(*job, js_undefined());
  467. }
  468. // Ensure no job has created a new exception, they must clean up after themselves.
  469. VERIFY(!m_exception);
  470. }
  471. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  472. void VM::enqueue_promise_job(NativeFunction& job)
  473. {
  474. m_promise_jobs.append(&job);
  475. }
  476. void VM::run_queued_finalization_registry_cleanup_jobs()
  477. {
  478. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  479. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  480. registry->cleanup();
  481. }
  482. }
  483. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  484. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  485. {
  486. m_finalization_registry_cleanup_jobs.append(&registry);
  487. }
  488. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  489. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  490. {
  491. switch (operation) {
  492. case Promise::RejectionOperation::Reject:
  493. // A promise was rejected without any handlers
  494. if (on_promise_unhandled_rejection)
  495. on_promise_unhandled_rejection(promise);
  496. break;
  497. case Promise::RejectionOperation::Handle:
  498. // A handler was added to an already rejected promise
  499. if (on_promise_rejection_handled)
  500. on_promise_rejection_handled(promise);
  501. break;
  502. default:
  503. VERIFY_NOT_REACHED();
  504. }
  505. }
  506. void VM::dump_backtrace() const
  507. {
  508. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i)
  509. dbgln("-> {}", m_call_stack[i]->function_name);
  510. }
  511. }