VM.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/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. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  116. {
  117. if (m_call_stack.size()) {
  118. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  119. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  120. break;
  121. auto possible_match = environment->get(name);
  122. if (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. environment->set(global_object, name, { value, possible_match.value().declaration_kind });
  128. return;
  129. }
  130. }
  131. }
  132. global_object.put(move(name), move(value));
  133. }
  134. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  135. {
  136. if (m_call_stack.size()) {
  137. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  138. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  139. break;
  140. auto possible_match = environment->get(name);
  141. if (possible_match.has_value())
  142. return possible_match.value().value;
  143. }
  144. }
  145. auto value = global_object.get(name);
  146. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  147. return m_last_value;
  148. return value;
  149. }
  150. Reference VM::get_reference(const FlyString& name)
  151. {
  152. if (m_call_stack.size()) {
  153. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  154. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  155. break;
  156. auto possible_match = environment->get(name);
  157. if (possible_match.has_value())
  158. return { Reference::LocalVariable, name };
  159. }
  160. }
  161. return { Reference::GlobalVariable, name };
  162. }
  163. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  164. {
  165. auto& call_frame = push_call_frame(function.is_strict_mode());
  166. ArmedScopeGuard call_frame_popper = [&] {
  167. pop_call_frame();
  168. };
  169. call_frame.function_name = function.name();
  170. call_frame.arguments = function.bound_arguments();
  171. if (arguments.has_value())
  172. call_frame.arguments.append(arguments.value().values());
  173. call_frame.environment = function.create_environment();
  174. current_environment()->set_new_target(&new_target);
  175. Object* new_object = nullptr;
  176. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  177. new_object = Object::create_empty(global_object);
  178. current_environment()->bind_this_value(global_object, new_object);
  179. if (exception())
  180. return {};
  181. auto prototype = new_target.get("prototype");
  182. if (exception())
  183. return {};
  184. if (prototype.is_object()) {
  185. new_object->set_prototype(&prototype.as_object());
  186. if (exception())
  187. return {};
  188. }
  189. }
  190. // If we are a Derived constructor, |this| has not been constructed before super is called.
  191. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  192. call_frame.this_value = this_value;
  193. auto result = function.construct(new_target);
  194. this_value = current_environment()->get_this_binding(global_object);
  195. pop_call_frame();
  196. call_frame_popper.disarm();
  197. // If we are constructing an instance of a derived class,
  198. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  199. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  200. current_environment()->replace_this_binding(result);
  201. auto prototype = new_target.get("prototype");
  202. if (exception())
  203. return {};
  204. if (prototype.is_object()) {
  205. result.as_object().set_prototype(&prototype.as_object());
  206. if (exception())
  207. return {};
  208. }
  209. return result;
  210. }
  211. if (exception())
  212. return {};
  213. if (result.is_object())
  214. return result;
  215. return this_value;
  216. }
  217. void VM::throw_exception(Exception* exception)
  218. {
  219. #ifdef VM_DEBUG
  220. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  221. auto& error = static_cast<Error&>(exception->value().as_object());
  222. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  223. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  224. auto function_name = m_call_stack[i].function_name;
  225. if (function_name.is_empty())
  226. function_name = "<anonymous>";
  227. dbg() << " " << function_name;
  228. }
  229. }
  230. #endif
  231. m_exception = exception;
  232. unwind(ScopeType::Try);
  233. }
  234. String VM::join_arguments() const
  235. {
  236. StringBuilder joined_arguments;
  237. for (size_t i = 0; i < argument_count(); ++i) {
  238. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  239. if (i != argument_count() - 1)
  240. joined_arguments.append(' ');
  241. }
  242. return joined_arguments.build();
  243. }
  244. Value VM::resolve_this_binding(GlobalObject& global_object) const
  245. {
  246. return get_this_environment()->get_this_binding(global_object);
  247. }
  248. const LexicalEnvironment* VM::get_this_environment() const
  249. {
  250. // We will always return because the Global environment will always be reached, which has a |this| binding.
  251. for (const LexicalEnvironment* environment = current_environment(); environment; environment = environment->parent()) {
  252. if (environment->has_this_binding())
  253. return environment;
  254. }
  255. ASSERT_NOT_REACHED();
  256. }
  257. Value VM::get_new_target() const
  258. {
  259. return get_this_environment()->new_target();
  260. }
  261. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  262. {
  263. ASSERT(!exception());
  264. auto& call_frame = push_call_frame(function.is_strict_mode());
  265. call_frame.function_name = function.name();
  266. call_frame.this_value = function.bound_this().value_or(this_value);
  267. call_frame.arguments = function.bound_arguments();
  268. if (arguments.has_value())
  269. call_frame.arguments.append(arguments.value().values());
  270. call_frame.environment = function.create_environment();
  271. ASSERT(call_frame.environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  272. call_frame.environment->bind_this_value(function.global_object(), call_frame.this_value);
  273. auto result = function.call();
  274. pop_call_frame();
  275. return result;
  276. }
  277. bool VM::in_strict_mode() const
  278. {
  279. if (call_stack().is_empty())
  280. return false;
  281. return call_frame().is_strict_mode;
  282. }
  283. }