VM.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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/GlobalObject.h>
  14. #include <LibJS/Runtime/IteratorOperations.h>
  15. #include <LibJS/Runtime/NativeFunction.h>
  16. #include <LibJS/Runtime/PromiseReaction.h>
  17. #include <LibJS/Runtime/Reference.h>
  18. #include <LibJS/Runtime/ScriptFunction.h>
  19. #include <LibJS/Runtime/Symbol.h>
  20. #include <LibJS/Runtime/TemporaryClearException.h>
  21. #include <LibJS/Runtime/VM.h>
  22. namespace JS {
  23. NonnullRefPtr<VM> VM::create()
  24. {
  25. return adopt_ref(*new VM);
  26. }
  27. VM::VM()
  28. : m_heap(*this)
  29. {
  30. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  31. for (size_t i = 0; i < 128; ++i) {
  32. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  33. }
  34. m_scope_object_shape = m_heap.allocate_without_global_object<Shape>(Shape::ShapeWithoutGlobalObjectTag::Tag);
  35. #define __JS_ENUMERATE(SymbolName, snake_name) \
  36. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  37. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  38. #undef __JS_ENUMERATE
  39. }
  40. VM::~VM()
  41. {
  42. }
  43. Interpreter& VM::interpreter()
  44. {
  45. VERIFY(!m_interpreters.is_empty());
  46. return *m_interpreters.last();
  47. }
  48. Interpreter* VM::interpreter_if_exists()
  49. {
  50. if (m_interpreters.is_empty())
  51. return nullptr;
  52. return m_interpreters.last();
  53. }
  54. void VM::push_interpreter(Interpreter& interpreter)
  55. {
  56. m_interpreters.append(&interpreter);
  57. }
  58. void VM::pop_interpreter(Interpreter& interpreter)
  59. {
  60. VERIFY(!m_interpreters.is_empty());
  61. auto* popped_interpreter = m_interpreters.take_last();
  62. VERIFY(popped_interpreter == &interpreter);
  63. }
  64. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  65. : m_interpreter(interpreter)
  66. {
  67. m_interpreter.vm().push_interpreter(m_interpreter);
  68. }
  69. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  70. {
  71. m_interpreter.vm().pop_interpreter(m_interpreter);
  72. }
  73. void VM::gather_roots(HashTable<Cell*>& roots)
  74. {
  75. roots.set(m_empty_string);
  76. for (auto* string : m_single_ascii_character_strings)
  77. roots.set(string);
  78. roots.set(m_scope_object_shape);
  79. roots.set(m_exception);
  80. if (m_last_value.is_cell())
  81. roots.set(&m_last_value.as_cell());
  82. for (auto& call_frame : m_call_stack) {
  83. if (call_frame->this_value.is_cell())
  84. roots.set(&call_frame->this_value.as_cell());
  85. roots.set(call_frame->arguments_object);
  86. for (auto& argument : call_frame->arguments) {
  87. if (argument.is_cell())
  88. roots.set(&argument.as_cell());
  89. }
  90. roots.set(call_frame->scope);
  91. }
  92. #define __JS_ENUMERATE(SymbolName, snake_name) \
  93. roots.set(well_known_symbol_##snake_name());
  94. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  95. #undef __JS_ENUMERATE
  96. for (auto& symbol : m_global_symbol_map)
  97. roots.set(symbol.value);
  98. for (auto* job : m_promise_jobs)
  99. roots.set(job);
  100. }
  101. Symbol* VM::get_global_symbol(const String& description)
  102. {
  103. auto result = m_global_symbol_map.get(description);
  104. if (result.has_value())
  105. return result.value();
  106. auto new_global_symbol = js_symbol(*this, description, true);
  107. m_global_symbol_map.set(description, new_global_symbol);
  108. return new_global_symbol;
  109. }
  110. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment, ScopeObject* specific_scope)
  111. {
  112. Optional<Variable> possible_match;
  113. if (!specific_scope && m_call_stack.size()) {
  114. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  115. possible_match = scope->get_from_scope(name);
  116. if (possible_match.has_value()) {
  117. specific_scope = scope;
  118. break;
  119. }
  120. }
  121. }
  122. if (specific_scope && possible_match.has_value()) {
  123. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  124. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  125. return;
  126. }
  127. specific_scope->put_to_scope(name, { value, possible_match.value().declaration_kind });
  128. return;
  129. }
  130. if (specific_scope) {
  131. specific_scope->put_to_scope(name, { value, DeclarationKind::Var });
  132. return;
  133. }
  134. global_object.put(name, value);
  135. }
  136. bool VM::delete_variable(FlyString const& name)
  137. {
  138. ScopeObject* specific_scope = nullptr;
  139. Optional<Variable> possible_match;
  140. if (!m_call_stack.is_empty()) {
  141. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  142. possible_match = scope->get_from_scope(name);
  143. if (possible_match.has_value()) {
  144. specific_scope = scope;
  145. break;
  146. }
  147. }
  148. }
  149. if (!possible_match.has_value())
  150. return false;
  151. if (possible_match.value().declaration_kind == DeclarationKind::Const)
  152. return false;
  153. VERIFY(specific_scope);
  154. return specific_scope->delete_from_scope(name);
  155. }
  156. void VM::assign(const FlyString& target, Value value, GlobalObject& global_object, bool first_assignment, ScopeObject* specific_scope)
  157. {
  158. set_variable(target, move(value), global_object, first_assignment, specific_scope);
  159. }
  160. void VM::assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value value, GlobalObject& global_object, bool first_assignment, ScopeObject* specific_scope)
  161. {
  162. if (auto id_ptr = target.get_pointer<NonnullRefPtr<Identifier>>())
  163. return assign((*id_ptr)->string(), move(value), global_object, first_assignment, specific_scope);
  164. assign(target.get<NonnullRefPtr<BindingPattern>>(), move(value), global_object, first_assignment, specific_scope);
  165. }
  166. void VM::assign(const NonnullRefPtr<BindingPattern>& target, Value value, GlobalObject& global_object, bool first_assignment, ScopeObject* specific_scope)
  167. {
  168. auto& binding = *target;
  169. switch (binding.kind) {
  170. case BindingPattern::Kind::Array: {
  171. auto iterator = get_iterator(global_object, value);
  172. if (!iterator)
  173. return;
  174. size_t index = 0;
  175. while (true) {
  176. if (exception())
  177. return;
  178. if (index >= binding.properties.size())
  179. break;
  180. auto pattern_property = binding.properties[index];
  181. ++index;
  182. if (pattern_property.is_rest) {
  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 {
  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. break;
  208. value = next_object->get(names.value);
  209. if (exception())
  210. return;
  211. }
  212. if (value.is_undefined() && pattern_property.initializer)
  213. value = pattern_property.initializer->execute(interpreter(), global_object);
  214. if (exception())
  215. return;
  216. if (pattern_property.name) {
  217. set_variable(pattern_property.name->string(), value, global_object, first_assignment, specific_scope);
  218. if (pattern_property.is_rest)
  219. break;
  220. continue;
  221. }
  222. if (pattern_property.pattern) {
  223. assign(NonnullRefPtr(*pattern_property.pattern), value, global_object, first_assignment, specific_scope);
  224. if (pattern_property.is_rest)
  225. break;
  226. continue;
  227. }
  228. }
  229. break;
  230. }
  231. case BindingPattern::Kind::Object: {
  232. auto object = value.to_object(global_object);
  233. HashTable<FlyString> seen_names;
  234. for (auto& property : binding.properties) {
  235. VERIFY(!property.pattern);
  236. JS::Value value_to_assign;
  237. if (property.is_rest) {
  238. auto* rest_object = Object::create_empty(global_object);
  239. rest_object->set_prototype(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 && !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, GlobalObject& global_object)
  321. {
  322. CallFrame call_frame;
  323. call_frame.callee = &function;
  324. if (auto* interpreter = interpreter_if_exists())
  325. call_frame.current_node = interpreter->current_node();
  326. call_frame.is_strict_mode = function.is_strict_mode();
  327. push_call_frame(call_frame, function.global_object());
  328. if (exception())
  329. return {};
  330. ArmedScopeGuard call_frame_popper = [&] {
  331. pop_call_frame();
  332. };
  333. call_frame.function_name = function.name();
  334. call_frame.arguments = function.bound_arguments();
  335. if (arguments.has_value())
  336. call_frame.arguments.append(arguments.value().values());
  337. auto* environment = function.create_environment();
  338. call_frame.scope = environment;
  339. environment->set_new_target(&new_target);
  340. Object* new_object = nullptr;
  341. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  342. new_object = Object::create_empty(global_object);
  343. environment->bind_this_value(global_object, new_object);
  344. if (exception())
  345. return {};
  346. auto prototype = new_target.get(names.prototype);
  347. if (exception())
  348. return {};
  349. if (prototype.is_object()) {
  350. new_object->set_prototype(&prototype.as_object());
  351. if (exception())
  352. return {};
  353. }
  354. }
  355. // If we are a Derived constructor, |this| has not been constructed before super is called.
  356. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  357. call_frame.this_value = this_value;
  358. auto result = function.construct(new_target);
  359. this_value = call_frame.scope->get_this_binding(global_object);
  360. pop_call_frame();
  361. call_frame_popper.disarm();
  362. // If we are constructing an instance of a derived class,
  363. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  364. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  365. VERIFY(is<LexicalEnvironment>(current_scope()));
  366. static_cast<LexicalEnvironment*>(current_scope())->replace_this_binding(result);
  367. auto prototype = new_target.get(names.prototype);
  368. if (exception())
  369. return {};
  370. if (prototype.is_object()) {
  371. result.as_object().set_prototype(&prototype.as_object());
  372. if (exception())
  373. return {};
  374. }
  375. return result;
  376. }
  377. if (exception())
  378. return {};
  379. if (result.is_object())
  380. return result;
  381. return this_value;
  382. }
  383. void VM::throw_exception(Exception& exception)
  384. {
  385. set_exception(exception);
  386. unwind(ScopeType::Try);
  387. }
  388. String VM::join_arguments(size_t start_index) const
  389. {
  390. StringBuilder joined_arguments;
  391. for (size_t i = start_index; i < argument_count(); ++i) {
  392. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  393. if (i != argument_count() - 1)
  394. joined_arguments.append(' ');
  395. }
  396. return joined_arguments.build();
  397. }
  398. Value VM::resolve_this_binding(GlobalObject& global_object) const
  399. {
  400. return find_this_scope()->get_this_binding(global_object);
  401. }
  402. const ScopeObject* VM::find_this_scope() const
  403. {
  404. // We will always return because the Global environment will always be reached, which has a |this| binding.
  405. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  406. if (scope->has_this_binding())
  407. return scope;
  408. }
  409. VERIFY_NOT_REACHED();
  410. }
  411. Value VM::get_new_target() const
  412. {
  413. VERIFY(is<LexicalEnvironment>(find_this_scope()));
  414. return static_cast<const LexicalEnvironment*>(find_this_scope())->new_target();
  415. }
  416. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  417. {
  418. VERIFY(!exception());
  419. VERIFY(!this_value.is_empty());
  420. CallFrame call_frame;
  421. call_frame.callee = &function;
  422. if (auto* interpreter = interpreter_if_exists())
  423. call_frame.current_node = interpreter->current_node();
  424. call_frame.is_strict_mode = function.is_strict_mode();
  425. call_frame.function_name = function.name();
  426. call_frame.this_value = function.bound_this().value_or(this_value);
  427. call_frame.arguments = function.bound_arguments();
  428. if (arguments.has_value())
  429. call_frame.arguments.append(arguments.value().values());
  430. auto* environment = function.create_environment();
  431. call_frame.scope = environment;
  432. VERIFY(environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  433. environment->bind_this_value(function.global_object(), call_frame.this_value);
  434. if (exception())
  435. return {};
  436. push_call_frame(call_frame, function.global_object());
  437. if (exception())
  438. return {};
  439. auto result = function.call();
  440. pop_call_frame();
  441. return result;
  442. }
  443. bool VM::in_strict_mode() const
  444. {
  445. if (call_stack().is_empty())
  446. return false;
  447. return call_frame().is_strict_mode;
  448. }
  449. void VM::run_queued_promise_jobs()
  450. {
  451. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  452. // Temporarily get rid of the exception, if any - job functions must be called
  453. // either way, and that can't happen if we already have an exception stored.
  454. TemporaryClearException clear_exception(*this);
  455. while (!m_promise_jobs.is_empty()) {
  456. auto* job = m_promise_jobs.take_first();
  457. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  458. [[maybe_unused]] auto result = call(*job, js_undefined());
  459. }
  460. // Ensure no job has created a new exception, they must clean up after themselves.
  461. VERIFY(!m_exception);
  462. }
  463. // 9.4.4 HostEnqueuePromiseJob, https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  464. void VM::enqueue_promise_job(NativeFunction& job)
  465. {
  466. m_promise_jobs.append(&job);
  467. }
  468. // 27.2.1.9 HostPromiseRejectionTracker, https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  469. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  470. {
  471. switch (operation) {
  472. case Promise::RejectionOperation::Reject:
  473. // A promise was rejected without any handlers
  474. if (on_promise_unhandled_rejection)
  475. on_promise_unhandled_rejection(promise);
  476. break;
  477. case Promise::RejectionOperation::Handle:
  478. // A handler was added to an already rejected promise
  479. if (on_promise_rejection_handled)
  480. on_promise_rejection_handled(promise);
  481. break;
  482. default:
  483. VERIFY_NOT_REACHED();
  484. }
  485. }
  486. void VM::dump_backtrace() const
  487. {
  488. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i)
  489. dbgln("-> {}", m_call_stack[i]->function_name);
  490. }
  491. }