VM.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/Debug.h>
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/StringBuilder.h>
  30. #include <AK/TemporaryChange.h>
  31. #include <LibJS/Interpreter.h>
  32. #include <LibJS/Runtime/Array.h>
  33. #include <LibJS/Runtime/Error.h>
  34. #include <LibJS/Runtime/GlobalObject.h>
  35. #include <LibJS/Runtime/NativeFunction.h>
  36. #include <LibJS/Runtime/PromiseReaction.h>
  37. #include <LibJS/Runtime/Reference.h>
  38. #include <LibJS/Runtime/ScriptFunction.h>
  39. #include <LibJS/Runtime/Symbol.h>
  40. #include <LibJS/Runtime/VM.h>
  41. namespace JS {
  42. NonnullRefPtr<VM> VM::create()
  43. {
  44. return adopt(*new VM);
  45. }
  46. VM::VM()
  47. : m_heap(*this)
  48. {
  49. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  50. for (size_t i = 0; i < 128; ++i) {
  51. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  52. }
  53. m_scope_object_shape = m_heap.allocate_without_global_object<Shape>(Shape::ShapeWithoutGlobalObjectTag::Tag);
  54. #define __JS_ENUMERATE(SymbolName, snake_name) \
  55. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  56. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  57. #undef __JS_ENUMERATE
  58. }
  59. VM::~VM()
  60. {
  61. }
  62. Interpreter& VM::interpreter()
  63. {
  64. VERIFY(!m_interpreters.is_empty());
  65. return *m_interpreters.last();
  66. }
  67. Interpreter* VM::interpreter_if_exists()
  68. {
  69. if (m_interpreters.is_empty())
  70. return nullptr;
  71. return m_interpreters.last();
  72. }
  73. void VM::push_interpreter(Interpreter& interpreter)
  74. {
  75. m_interpreters.append(&interpreter);
  76. }
  77. void VM::pop_interpreter(Interpreter& interpreter)
  78. {
  79. VERIFY(!m_interpreters.is_empty());
  80. auto* popped_interpreter = m_interpreters.take_last();
  81. VERIFY(popped_interpreter == &interpreter);
  82. }
  83. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  84. : m_interpreter(interpreter)
  85. {
  86. m_interpreter.vm().push_interpreter(m_interpreter);
  87. }
  88. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  89. {
  90. m_interpreter.vm().pop_interpreter(m_interpreter);
  91. }
  92. void VM::gather_roots(HashTable<Cell*>& roots)
  93. {
  94. roots.set(m_empty_string);
  95. for (auto* string : m_single_ascii_character_strings)
  96. roots.set(string);
  97. roots.set(m_scope_object_shape);
  98. roots.set(m_exception);
  99. if (m_last_value.is_cell())
  100. roots.set(m_last_value.as_cell());
  101. for (auto& call_frame : m_call_stack) {
  102. if (call_frame->this_value.is_cell())
  103. roots.set(call_frame->this_value.as_cell());
  104. roots.set(call_frame->arguments_object);
  105. for (auto& argument : call_frame->arguments) {
  106. if (argument.is_cell())
  107. roots.set(argument.as_cell());
  108. }
  109. roots.set(call_frame->scope);
  110. }
  111. #define __JS_ENUMERATE(SymbolName, snake_name) \
  112. roots.set(well_known_symbol_##snake_name());
  113. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  114. #undef __JS_ENUMERATE
  115. for (auto& symbol : m_global_symbol_map)
  116. roots.set(symbol.value);
  117. for (auto* job : m_promise_jobs)
  118. roots.set(job);
  119. }
  120. Symbol* VM::get_global_symbol(const String& description)
  121. {
  122. auto result = m_global_symbol_map.get(description);
  123. if (result.has_value())
  124. return result.value();
  125. auto new_global_symbol = js_symbol(*this, description, true);
  126. m_global_symbol_map.set(description, new_global_symbol);
  127. return new_global_symbol;
  128. }
  129. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  130. {
  131. if (m_call_stack.size()) {
  132. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  133. auto possible_match = scope->get_from_scope(name);
  134. if (possible_match.has_value()) {
  135. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  136. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  137. return;
  138. }
  139. scope->put_to_scope(name, { value, possible_match.value().declaration_kind });
  140. return;
  141. }
  142. }
  143. }
  144. global_object.put(move(name), move(value));
  145. }
  146. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  147. {
  148. if (!m_call_stack.is_empty()) {
  149. if (name == names.arguments && !call_frame().callee.is_empty()) {
  150. // HACK: Special handling for the name "arguments":
  151. // If the name "arguments" is defined in the current scope, for example via
  152. // a function parameter, or by a local var declaration, we use that.
  153. // Otherwise, we return a lazily constructed Array with all the argument values.
  154. // FIXME: Do something much more spec-compliant.
  155. auto possible_match = current_scope()->get_from_scope(name);
  156. if (possible_match.has_value())
  157. return possible_match.value().value;
  158. if (!call_frame().arguments_object) {
  159. call_frame().arguments_object = Array::create(global_object);
  160. call_frame().arguments_object->put(names.callee, call_frame().callee);
  161. for (auto argument : call_frame().arguments) {
  162. call_frame().arguments_object->indexed_properties().append(argument);
  163. }
  164. }
  165. return call_frame().arguments_object;
  166. }
  167. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  168. auto possible_match = scope->get_from_scope(name);
  169. if (possible_match.has_value())
  170. return possible_match.value().value;
  171. }
  172. }
  173. auto value = global_object.get(name);
  174. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  175. return m_last_value;
  176. return value;
  177. }
  178. Reference VM::get_reference(const FlyString& name)
  179. {
  180. if (m_call_stack.size()) {
  181. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  182. if (is<GlobalObject>(scope))
  183. break;
  184. auto possible_match = scope->get_from_scope(name);
  185. if (possible_match.has_value())
  186. return { Reference::LocalVariable, name };
  187. }
  188. }
  189. return { Reference::GlobalVariable, name };
  190. }
  191. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  192. {
  193. CallFrame call_frame;
  194. call_frame.callee = &function;
  195. if (auto* interpreter = interpreter_if_exists())
  196. call_frame.current_node = interpreter->current_node();
  197. call_frame.is_strict_mode = function.is_strict_mode();
  198. push_call_frame(call_frame, function.global_object());
  199. if (exception())
  200. return {};
  201. ArmedScopeGuard call_frame_popper = [&] {
  202. pop_call_frame();
  203. };
  204. call_frame.function_name = function.name();
  205. call_frame.arguments = function.bound_arguments();
  206. if (arguments.has_value())
  207. call_frame.arguments.append(arguments.value().values());
  208. auto* environment = function.create_environment();
  209. call_frame.scope = environment;
  210. environment->set_new_target(&new_target);
  211. Object* new_object = nullptr;
  212. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  213. new_object = Object::create_empty(global_object);
  214. environment->bind_this_value(global_object, new_object);
  215. if (exception())
  216. return {};
  217. auto prototype = new_target.get(names.prototype);
  218. if (exception())
  219. return {};
  220. if (prototype.is_object()) {
  221. new_object->set_prototype(&prototype.as_object());
  222. if (exception())
  223. return {};
  224. }
  225. }
  226. // If we are a Derived constructor, |this| has not been constructed before super is called.
  227. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  228. call_frame.this_value = this_value;
  229. auto result = function.construct(new_target);
  230. this_value = call_frame.scope->get_this_binding(global_object);
  231. pop_call_frame();
  232. call_frame_popper.disarm();
  233. // If we are constructing an instance of a derived class,
  234. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  235. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  236. VERIFY(is<LexicalEnvironment>(current_scope()));
  237. static_cast<LexicalEnvironment*>(current_scope())->replace_this_binding(result);
  238. auto prototype = new_target.get(names.prototype);
  239. if (exception())
  240. return {};
  241. if (prototype.is_object()) {
  242. result.as_object().set_prototype(&prototype.as_object());
  243. if (exception())
  244. return {};
  245. }
  246. return result;
  247. }
  248. if (exception())
  249. return {};
  250. if (result.is_object())
  251. return result;
  252. return this_value;
  253. }
  254. void VM::throw_exception(Exception& exception)
  255. {
  256. if (should_log_exceptions()) {
  257. auto value = exception.value();
  258. if (value.is_object()) {
  259. auto& object = value.as_object();
  260. auto name = object.get_without_side_effects(names.name).value_or(js_undefined());
  261. auto message = object.get_without_side_effects(names.message).value_or(js_undefined());
  262. if (name.is_accessor() || name.is_native_property() || message.is_accessor() || message.is_native_property()) {
  263. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  264. dbgln("Throwing JavaScript exception: {}", value);
  265. } else {
  266. dbgln("Throwing JavaScript exception: [{}] {}", name, message);
  267. }
  268. } else {
  269. dbgln("Throwing JavaScript exception: {}", value);
  270. }
  271. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  272. const auto& source_range = m_call_stack[i]->current_node->source_range();
  273. auto function_name = m_call_stack[i]->function_name;
  274. if (function_name.is_empty())
  275. function_name = "<anonymous>";
  276. dbgln(" {} at {}:{}:{}", function_name, source_range.filename, source_range.start.line, source_range.start.column);
  277. }
  278. }
  279. set_exception(exception);
  280. unwind(ScopeType::Try);
  281. }
  282. String VM::join_arguments() const
  283. {
  284. StringBuilder joined_arguments;
  285. for (size_t i = 0; i < argument_count(); ++i) {
  286. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  287. if (i != argument_count() - 1)
  288. joined_arguments.append(' ');
  289. }
  290. return joined_arguments.build();
  291. }
  292. Value VM::resolve_this_binding(GlobalObject& global_object) const
  293. {
  294. return find_this_scope()->get_this_binding(global_object);
  295. }
  296. const ScopeObject* VM::find_this_scope() const
  297. {
  298. // We will always return because the Global environment will always be reached, which has a |this| binding.
  299. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  300. if (scope->has_this_binding())
  301. return scope;
  302. }
  303. VERIFY_NOT_REACHED();
  304. }
  305. Value VM::get_new_target() const
  306. {
  307. VERIFY(is<LexicalEnvironment>(find_this_scope()));
  308. return static_cast<const LexicalEnvironment*>(find_this_scope())->new_target();
  309. }
  310. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  311. {
  312. VERIFY(!exception());
  313. VERIFY(!this_value.is_empty());
  314. CallFrame call_frame;
  315. call_frame.callee = &function;
  316. if (auto* interpreter = interpreter_if_exists())
  317. call_frame.current_node = interpreter->current_node();
  318. call_frame.is_strict_mode = function.is_strict_mode();
  319. call_frame.function_name = function.name();
  320. call_frame.this_value = function.bound_this().value_or(this_value);
  321. call_frame.arguments = function.bound_arguments();
  322. if (arguments.has_value())
  323. call_frame.arguments.append(move(arguments.release_value().values()));
  324. auto* environment = function.create_environment();
  325. call_frame.scope = environment;
  326. VERIFY(environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  327. environment->bind_this_value(function.global_object(), call_frame.this_value);
  328. if (exception())
  329. return {};
  330. push_call_frame(call_frame, function.global_object());
  331. if (exception())
  332. return {};
  333. auto result = function.call();
  334. pop_call_frame();
  335. return result;
  336. }
  337. bool VM::in_strict_mode() const
  338. {
  339. if (call_stack().is_empty())
  340. return false;
  341. return call_frame().is_strict_mode;
  342. }
  343. void VM::run_queued_promise_jobs()
  344. {
  345. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  346. // Temporarily get rid of the exception, if any - job functions must be called
  347. // either way, and that can't happen if we already have an exception stored.
  348. TemporaryChange change(m_exception, static_cast<Exception*>(nullptr));
  349. while (!m_promise_jobs.is_empty()) {
  350. auto* job = m_promise_jobs.take_first();
  351. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  352. [[maybe_unused]] auto result = call(*job, js_undefined());
  353. }
  354. // Ensure no job has created a new exception, they must clean up after themselves.
  355. VERIFY(!m_exception);
  356. }
  357. // 9.4.4 HostEnqueuePromiseJob, https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  358. void VM::enqueue_promise_job(NativeFunction& job)
  359. {
  360. m_promise_jobs.append(&job);
  361. }
  362. // 27.2.1.9 HostPromiseRejectionTracker, https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  363. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  364. {
  365. switch (operation) {
  366. case Promise::RejectionOperation::Reject:
  367. // A promise was rejected without any handlers
  368. if (on_promise_unhandled_rejection)
  369. on_promise_unhandled_rejection(promise);
  370. break;
  371. case Promise::RejectionOperation::Handle:
  372. // A handler was added to an already rejected promise
  373. if (on_promise_rejection_handled)
  374. on_promise_rejection_handled(promise);
  375. break;
  376. default:
  377. VERIFY_NOT_REACHED();
  378. }
  379. }
  380. }