VM.cpp 19 KB

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