VM.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. //#define VM_DEBUG
  37. namespace JS {
  38. NonnullRefPtr<VM> VM::create()
  39. {
  40. return adopt(*new VM);
  41. }
  42. VM::VM()
  43. : m_heap(*this)
  44. {
  45. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  46. for (size_t i = 0; i < 128; ++i) {
  47. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::format("%c", i));
  48. }
  49. m_scope_object_shape = m_heap.allocate_without_global_object<Shape>(Shape::ShapeWithoutGlobalObjectTag::Tag);
  50. #define __JS_ENUMERATE(SymbolName, snake_name) \
  51. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  52. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  53. #undef __JS_ENUMERATE
  54. }
  55. VM::~VM()
  56. {
  57. }
  58. Interpreter& VM::interpreter()
  59. {
  60. ASSERT(!m_interpreters.is_empty());
  61. return *m_interpreters.last();
  62. }
  63. Interpreter* VM::interpreter_if_exists()
  64. {
  65. if (m_interpreters.is_empty())
  66. return nullptr;
  67. return m_interpreters.last();
  68. }
  69. void VM::push_interpreter(Interpreter& interpreter)
  70. {
  71. m_interpreters.append(&interpreter);
  72. }
  73. void VM::pop_interpreter(Interpreter& interpreter)
  74. {
  75. ASSERT(!m_interpreters.is_empty());
  76. auto* popped_interpreter = m_interpreters.take_last();
  77. ASSERT(popped_interpreter == &interpreter);
  78. }
  79. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  80. : m_interpreter(interpreter)
  81. {
  82. m_interpreter.vm().push_interpreter(m_interpreter);
  83. }
  84. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  85. {
  86. m_interpreter.vm().pop_interpreter(m_interpreter);
  87. }
  88. void VM::gather_roots(HashTable<Cell*>& roots)
  89. {
  90. roots.set(m_empty_string);
  91. for (auto* string : m_single_ascii_character_strings)
  92. roots.set(string);
  93. roots.set(m_scope_object_shape);
  94. if (m_exception)
  95. roots.set(m_exception);
  96. if (m_last_value.is_cell())
  97. roots.set(m_last_value.as_cell());
  98. for (auto& call_frame : m_call_stack) {
  99. if (call_frame->this_value.is_cell())
  100. roots.set(call_frame->this_value.as_cell());
  101. if (call_frame->arguments_object)
  102. roots.set(call_frame->arguments_object);
  103. for (auto& argument : call_frame->arguments) {
  104. if (argument.is_cell())
  105. roots.set(argument.as_cell());
  106. }
  107. roots.set(call_frame->scope);
  108. }
  109. #define __JS_ENUMERATE(SymbolName, snake_name) \
  110. roots.set(well_known_symbol_##snake_name());
  111. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  112. #undef __JS_ENUMERATE
  113. for (auto& symbol : m_global_symbol_map)
  114. roots.set(symbol.value);
  115. }
  116. Symbol* VM::get_global_symbol(const String& description)
  117. {
  118. auto result = m_global_symbol_map.get(description);
  119. if (result.has_value())
  120. return result.value();
  121. auto new_global_symbol = js_symbol(*this, description, true);
  122. m_global_symbol_map.set(description, new_global_symbol);
  123. return new_global_symbol;
  124. }
  125. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  126. {
  127. if (m_call_stack.size()) {
  128. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  129. auto possible_match = scope->get_from_scope(name);
  130. if (possible_match.has_value()) {
  131. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  132. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  133. return;
  134. }
  135. scope->put_to_scope(name, { value, possible_match.value().declaration_kind });
  136. return;
  137. }
  138. }
  139. }
  140. global_object.put(move(name), move(value));
  141. }
  142. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  143. {
  144. if (m_call_stack.size()) {
  145. if (name == names.arguments) {
  146. // HACK: Special handling for the name "arguments":
  147. // If the name "arguments" is defined in the current scope, for example via
  148. // a function parameter, or by a local var declaration, we use that.
  149. // Otherwise, we return a lazily constructed Array with all the argument values.
  150. // FIXME: Do something much more spec-compliant.
  151. auto possible_match = current_scope()->get_from_scope(name);
  152. if (possible_match.has_value())
  153. return possible_match.value().value;
  154. if (!call_frame().arguments_object) {
  155. call_frame().arguments_object = Array::create(global_object);
  156. for (auto argument : call_frame().arguments) {
  157. call_frame().arguments_object->indexed_properties().append(argument);
  158. }
  159. }
  160. return call_frame().arguments_object;
  161. }
  162. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  163. auto possible_match = scope->get_from_scope(name);
  164. if (possible_match.has_value())
  165. return possible_match.value().value;
  166. }
  167. }
  168. auto value = global_object.get(name);
  169. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  170. return m_last_value;
  171. return value;
  172. }
  173. Reference VM::get_reference(const FlyString& name)
  174. {
  175. if (m_call_stack.size()) {
  176. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  177. if (scope->is_global_object())
  178. break;
  179. auto possible_match = scope->get_from_scope(name);
  180. if (possible_match.has_value())
  181. return { Reference::LocalVariable, name };
  182. }
  183. }
  184. return { Reference::GlobalVariable, name };
  185. }
  186. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  187. {
  188. CallFrame call_frame;
  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. ASSERT(current_scope()->is_lexical_environment());
  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() && exception->value().as_object().is_error()) {
  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. auto function_name = m_call_stack[i]->function_name;
  253. if (function_name.is_empty())
  254. function_name = "<anonymous>";
  255. dbgln(" {}", function_name);
  256. }
  257. }
  258. m_exception = exception;
  259. unwind(ScopeType::Try);
  260. }
  261. String VM::join_arguments() const
  262. {
  263. StringBuilder joined_arguments;
  264. for (size_t i = 0; i < argument_count(); ++i) {
  265. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  266. if (i != argument_count() - 1)
  267. joined_arguments.append(' ');
  268. }
  269. return joined_arguments.build();
  270. }
  271. Value VM::resolve_this_binding(GlobalObject& global_object) const
  272. {
  273. return find_this_scope()->get_this_binding(global_object);
  274. }
  275. const ScopeObject* VM::find_this_scope() const
  276. {
  277. // We will always return because the Global environment will always be reached, which has a |this| binding.
  278. for (auto* scope = current_scope(); scope; scope = scope->parent()) {
  279. if (scope->has_this_binding())
  280. return scope;
  281. }
  282. ASSERT_NOT_REACHED();
  283. }
  284. Value VM::get_new_target() const
  285. {
  286. ASSERT(find_this_scope()->is_lexical_environment());
  287. return static_cast<const LexicalEnvironment*>(find_this_scope())->new_target();
  288. }
  289. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  290. {
  291. ASSERT(!exception());
  292. CallFrame call_frame;
  293. call_frame.is_strict_mode = function.is_strict_mode();
  294. call_frame.function_name = function.name();
  295. call_frame.this_value = function.bound_this().value_or(this_value);
  296. call_frame.arguments = function.bound_arguments();
  297. if (arguments.has_value())
  298. call_frame.arguments.append(move(arguments.release_value().values()));
  299. auto* environment = function.create_environment();
  300. call_frame.scope = environment;
  301. ASSERT(environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  302. environment->bind_this_value(function.global_object(), call_frame.this_value);
  303. if (exception())
  304. return {};
  305. push_call_frame(call_frame, function.global_object());
  306. if (exception())
  307. return {};
  308. auto result = function.call();
  309. pop_call_frame();
  310. return result;
  311. }
  312. bool VM::in_strict_mode() const
  313. {
  314. if (call_stack().is_empty())
  315. return false;
  316. return call_frame().is_strict_mode;
  317. }
  318. }