VM.cpp 13 KB

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