VM.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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/StringBuilder.h>
  27. #include <AK/ScopeGuard.h>
  28. #include <LibJS/Interpreter.h>
  29. #include <LibJS/Runtime/Error.h>
  30. #include <LibJS/Runtime/GlobalObject.h>
  31. #include <LibJS/Runtime/Reference.h>
  32. #include <LibJS/Runtime/ScriptFunction.h>
  33. #include <LibJS/Runtime/Symbol.h>
  34. #include <LibJS/Runtime/VM.h>
  35. //#define VM_DEBUG
  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. #define __JS_ENUMERATE(SymbolName, snake_name) \
  46. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  47. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  48. #undef __JS_ENUMERATE
  49. }
  50. VM::~VM()
  51. {
  52. }
  53. Interpreter& VM::interpreter()
  54. {
  55. ASSERT(!m_interpreters.is_empty());
  56. return *m_interpreters.last();
  57. }
  58. Interpreter* VM::interpreter_if_exists()
  59. {
  60. if (m_interpreters.is_empty())
  61. return nullptr;
  62. return m_interpreters.last();
  63. }
  64. void VM::push_interpreter(Interpreter& interpreter)
  65. {
  66. m_interpreters.append(&interpreter);
  67. }
  68. void VM::pop_interpreter(Interpreter& interpreter)
  69. {
  70. ASSERT(!m_interpreters.is_empty());
  71. auto* popped_interpreter = m_interpreters.take_last();
  72. ASSERT(popped_interpreter == &interpreter);
  73. }
  74. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  75. : m_interpreter(interpreter)
  76. {
  77. m_interpreter.vm().push_interpreter(m_interpreter);
  78. }
  79. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  80. {
  81. m_interpreter.vm().pop_interpreter(m_interpreter);
  82. }
  83. void VM::gather_roots(HashTable<Cell*>& roots)
  84. {
  85. roots.set(m_empty_string);
  86. if (m_exception)
  87. roots.set(m_exception);
  88. if (m_last_value.is_cell())
  89. roots.set(m_last_value.as_cell());
  90. for (auto& call_frame : m_call_stack) {
  91. if (call_frame.this_value.is_cell())
  92. roots.set(call_frame.this_value.as_cell());
  93. for (auto& argument : call_frame.arguments) {
  94. if (argument.is_cell())
  95. roots.set(argument.as_cell());
  96. }
  97. roots.set(call_frame.environment);
  98. }
  99. #define __JS_ENUMERATE(SymbolName, snake_name) \
  100. roots.set(well_known_symbol_##snake_name());
  101. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  102. #undef __JS_ENUMERATE
  103. for (auto& symbol : m_global_symbol_map)
  104. roots.set(symbol.value);
  105. }
  106. Symbol* VM::get_global_symbol(const String& description)
  107. {
  108. auto result = m_global_symbol_map.get(description);
  109. if (result.has_value())
  110. return result.value();
  111. auto new_global_symbol = js_symbol(*this, description, true);
  112. m_global_symbol_map.set(description, new_global_symbol);
  113. return new_global_symbol;
  114. }
  115. bool VM::in_strict_mode() const
  116. {
  117. if (m_scope_stack.is_empty())
  118. return true;
  119. return m_scope_stack.last().scope_node->in_strict_mode();
  120. }
  121. void VM::enter_scope(const ScopeNode& scope_node, ArgumentVector arguments, ScopeType scope_type, GlobalObject& global_object)
  122. {
  123. for (auto& declaration : scope_node.functions()) {
  124. auto* function = ScriptFunction::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), current_environment());
  125. set_variable(declaration.name(), function, global_object);
  126. }
  127. if (scope_type == ScopeType::Function) {
  128. m_scope_stack.append({ scope_type, scope_node, false });
  129. return;
  130. }
  131. HashMap<FlyString, Variable> scope_variables_with_declaration_kind;
  132. scope_variables_with_declaration_kind.ensure_capacity(16);
  133. for (auto& declaration : scope_node.variables()) {
  134. for (auto& declarator : declaration.declarations()) {
  135. if (scope_node.is_program()) {
  136. global_object.put(declarator.id().string(), js_undefined());
  137. if (exception())
  138. return;
  139. } else {
  140. scope_variables_with_declaration_kind.set(declarator.id().string(), { js_undefined(), declaration.declaration_kind() });
  141. }
  142. }
  143. }
  144. for (auto& argument : arguments) {
  145. scope_variables_with_declaration_kind.set(argument.name, { argument.value, DeclarationKind::Var });
  146. }
  147. bool pushed_lexical_environment = false;
  148. if (!scope_variables_with_declaration_kind.is_empty()) {
  149. auto* block_lexical_environment = heap().allocate<LexicalEnvironment>(global_object, move(scope_variables_with_declaration_kind), current_environment());
  150. m_call_stack.last().environment = block_lexical_environment;
  151. pushed_lexical_environment = true;
  152. }
  153. m_scope_stack.append({ scope_type, scope_node, pushed_lexical_environment });
  154. }
  155. void VM::exit_scope(const ScopeNode& scope_node)
  156. {
  157. while (!m_scope_stack.is_empty()) {
  158. auto popped_scope = m_scope_stack.take_last();
  159. if (popped_scope.pushed_environment)
  160. m_call_stack.last().environment = m_call_stack.last().environment->parent();
  161. if (popped_scope.scope_node.ptr() == &scope_node)
  162. break;
  163. }
  164. // If we unwind all the way, just reset m_unwind_until so that future "return" doesn't break.
  165. if (m_scope_stack.is_empty())
  166. m_unwind_until = ScopeType::None;
  167. }
  168. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  169. {
  170. if (m_call_stack.size()) {
  171. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  172. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  173. break;
  174. auto possible_match = environment->get(name);
  175. if (possible_match.has_value()) {
  176. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  177. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  178. return;
  179. }
  180. environment->set(name, { value, possible_match.value().declaration_kind });
  181. return;
  182. }
  183. }
  184. }
  185. global_object.put(move(name), move(value));
  186. }
  187. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  188. {
  189. if (m_call_stack.size()) {
  190. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  191. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  192. break;
  193. auto possible_match = environment->get(name);
  194. if (possible_match.has_value())
  195. return possible_match.value().value;
  196. }
  197. }
  198. auto value = global_object.get(name);
  199. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  200. return m_last_value;
  201. return value;
  202. }
  203. Reference VM::get_reference(const FlyString& name)
  204. {
  205. if (m_call_stack.size()) {
  206. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  207. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  208. break;
  209. auto possible_match = environment->get(name);
  210. if (possible_match.has_value())
  211. return { Reference::LocalVariable, name };
  212. }
  213. }
  214. return { Reference::GlobalVariable, name };
  215. }
  216. Value VM::execute_statement(GlobalObject& global_object, const Statement& statement, ArgumentVector arguments, ScopeType scope_type)
  217. {
  218. if (!statement.is_scope_node())
  219. return statement.execute(interpreter(), global_object);
  220. auto& block = static_cast<const ScopeNode&>(statement);
  221. enter_scope(block, move(arguments), scope_type, global_object);
  222. if (block.children().is_empty())
  223. m_last_value = js_undefined();
  224. for (auto& node : block.children()) {
  225. m_last_value = node.execute(interpreter(), global_object);
  226. if (should_unwind()) {
  227. if (!block.label().is_null() && should_unwind_until(ScopeType::Breakable, block.label()))
  228. stop_unwind();
  229. break;
  230. }
  231. }
  232. bool did_return = m_unwind_until == ScopeType::Function;
  233. if (m_unwind_until == scope_type)
  234. m_unwind_until = ScopeType::None;
  235. exit_scope(block);
  236. return did_return ? m_last_value : js_undefined();
  237. }
  238. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  239. {
  240. auto& call_frame = push_call_frame();
  241. ArmedScopeGuard call_frame_popper = [&] {
  242. pop_call_frame();
  243. };
  244. call_frame.function_name = function.name();
  245. call_frame.arguments = function.bound_arguments();
  246. if (arguments.has_value())
  247. call_frame.arguments.append(arguments.value().values());
  248. call_frame.environment = function.create_environment();
  249. current_environment()->set_new_target(&new_target);
  250. Object* new_object = nullptr;
  251. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  252. new_object = Object::create_empty(global_object);
  253. current_environment()->bind_this_value(new_object);
  254. if (exception())
  255. return {};
  256. auto prototype = new_target.get("prototype");
  257. if (exception())
  258. return {};
  259. if (prototype.is_object()) {
  260. new_object->set_prototype(&prototype.as_object());
  261. if (exception())
  262. return {};
  263. }
  264. }
  265. // If we are a Derived constructor, |this| has not been constructed before super is called.
  266. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  267. call_frame.this_value = this_value;
  268. auto result = function.construct(interpreter(), new_target);
  269. this_value = current_environment()->get_this_binding();
  270. pop_call_frame();
  271. call_frame_popper.disarm();
  272. // If we are constructing an instance of a derived class,
  273. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  274. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  275. current_environment()->replace_this_binding(result);
  276. auto prototype = new_target.get("prototype");
  277. if (exception())
  278. return {};
  279. if (prototype.is_object()) {
  280. result.as_object().set_prototype(&prototype.as_object());
  281. if (exception())
  282. return {};
  283. }
  284. return result;
  285. }
  286. if (exception())
  287. return {};
  288. if (result.is_object())
  289. return result;
  290. return this_value;
  291. }
  292. void VM::throw_exception(Exception* exception)
  293. {
  294. #ifdef VM_DEBUG
  295. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  296. auto& error = static_cast<Error&>(exception->value().as_object());
  297. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  298. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  299. auto function_name = m_call_stack[i].function_name;
  300. if (function_name.is_empty())
  301. function_name = "<anonymous>";
  302. dbg() << " " << function_name;
  303. }
  304. }
  305. #endif
  306. m_exception = exception;
  307. unwind(ScopeType::Try);
  308. }
  309. String VM::join_arguments() const
  310. {
  311. StringBuilder joined_arguments;
  312. for (size_t i = 0; i < argument_count(); ++i) {
  313. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  314. if (i != argument_count() - 1)
  315. joined_arguments.append(' ');
  316. }
  317. return joined_arguments.build();
  318. }
  319. Value VM::resolve_this_binding() const
  320. {
  321. return get_this_environment()->get_this_binding();
  322. }
  323. const LexicalEnvironment* VM::get_this_environment() const
  324. {
  325. // We will always return because the Global environment will always be reached, which has a |this| binding.
  326. for (const LexicalEnvironment* environment = current_environment(); environment; environment = environment->parent()) {
  327. if (environment->has_this_binding())
  328. return environment;
  329. }
  330. ASSERT_NOT_REACHED();
  331. }
  332. Value VM::get_new_target() const
  333. {
  334. return get_this_environment()->new_target();
  335. }
  336. }