VM.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. for (size_t i = 0; i < 128; ++i) {
  46. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::format("%c", i));
  47. }
  48. #define __JS_ENUMERATE(SymbolName, snake_name) \
  49. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  50. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  51. #undef __JS_ENUMERATE
  52. }
  53. VM::~VM()
  54. {
  55. }
  56. Interpreter& VM::interpreter()
  57. {
  58. ASSERT(!m_interpreters.is_empty());
  59. return *m_interpreters.last();
  60. }
  61. Interpreter* VM::interpreter_if_exists()
  62. {
  63. if (m_interpreters.is_empty())
  64. return nullptr;
  65. return m_interpreters.last();
  66. }
  67. void VM::push_interpreter(Interpreter& interpreter)
  68. {
  69. m_interpreters.append(&interpreter);
  70. }
  71. void VM::pop_interpreter(Interpreter& interpreter)
  72. {
  73. ASSERT(!m_interpreters.is_empty());
  74. auto* popped_interpreter = m_interpreters.take_last();
  75. ASSERT(popped_interpreter == &interpreter);
  76. }
  77. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  78. : m_interpreter(interpreter)
  79. {
  80. m_interpreter.vm().push_interpreter(m_interpreter);
  81. }
  82. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  83. {
  84. m_interpreter.vm().pop_interpreter(m_interpreter);
  85. }
  86. void VM::gather_roots(HashTable<Cell*>& roots)
  87. {
  88. roots.set(m_empty_string);
  89. for (auto* string : m_single_ascii_character_strings)
  90. roots.set(string);
  91. if (m_exception)
  92. roots.set(m_exception);
  93. if (m_last_value.is_cell())
  94. roots.set(m_last_value.as_cell());
  95. for (auto& call_frame : m_call_stack) {
  96. if (call_frame->this_value.is_cell())
  97. roots.set(call_frame->this_value.as_cell());
  98. for (auto& argument : call_frame->arguments) {
  99. if (argument.is_cell())
  100. roots.set(argument.as_cell());
  101. }
  102. roots.set(call_frame->environment);
  103. }
  104. #define __JS_ENUMERATE(SymbolName, snake_name) \
  105. roots.set(well_known_symbol_##snake_name());
  106. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  107. #undef __JS_ENUMERATE
  108. for (auto& symbol : m_global_symbol_map)
  109. roots.set(symbol.value);
  110. }
  111. Symbol* VM::get_global_symbol(const String& description)
  112. {
  113. auto result = m_global_symbol_map.get(description);
  114. if (result.has_value())
  115. return result.value();
  116. auto new_global_symbol = js_symbol(*this, description, true);
  117. m_global_symbol_map.set(description, new_global_symbol);
  118. return new_global_symbol;
  119. }
  120. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  121. {
  122. if (m_call_stack.size()) {
  123. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  124. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  125. break;
  126. auto possible_match = environment->get(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. environment->set(global_object, 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.size()) {
  142. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  143. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  144. break;
  145. auto possible_match = environment->get(name);
  146. if (possible_match.has_value())
  147. return possible_match.value().value;
  148. }
  149. }
  150. auto value = global_object.get(name);
  151. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  152. return m_last_value;
  153. return value;
  154. }
  155. Reference VM::get_reference(const FlyString& name)
  156. {
  157. if (m_call_stack.size()) {
  158. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  159. if (environment->type() == LexicalEnvironment::EnvironmentRecordType::Global)
  160. break;
  161. auto possible_match = environment->get(name);
  162. if (possible_match.has_value())
  163. return { Reference::LocalVariable, name };
  164. }
  165. }
  166. return { Reference::GlobalVariable, name };
  167. }
  168. Value VM::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  169. {
  170. CallFrame call_frame;
  171. call_frame.is_strict_mode = function.is_strict_mode();
  172. push_call_frame(call_frame, function.global_object());
  173. if (exception())
  174. return {};
  175. ArmedScopeGuard call_frame_popper = [&] {
  176. pop_call_frame();
  177. };
  178. call_frame.function_name = function.name();
  179. call_frame.arguments = function.bound_arguments();
  180. if (arguments.has_value())
  181. call_frame.arguments.append(arguments.value().values());
  182. call_frame.environment = function.create_environment();
  183. call_frame.environment->set_new_target(&new_target);
  184. Object* new_object = nullptr;
  185. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  186. new_object = Object::create_empty(global_object);
  187. call_frame.environment->bind_this_value(global_object, new_object);
  188. if (exception())
  189. return {};
  190. auto prototype = new_target.get(names.prototype);
  191. if (exception())
  192. return {};
  193. if (prototype.is_object()) {
  194. new_object->set_prototype(&prototype.as_object());
  195. if (exception())
  196. return {};
  197. }
  198. }
  199. // If we are a Derived constructor, |this| has not been constructed before super is called.
  200. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  201. call_frame.this_value = this_value;
  202. auto result = function.construct(new_target);
  203. this_value = call_frame.environment->get_this_binding(global_object);
  204. pop_call_frame();
  205. call_frame_popper.disarm();
  206. // If we are constructing an instance of a derived class,
  207. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  208. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  209. current_environment()->replace_this_binding(result);
  210. auto prototype = new_target.get(names.prototype);
  211. if (exception())
  212. return {};
  213. if (prototype.is_object()) {
  214. result.as_object().set_prototype(&prototype.as_object());
  215. if (exception())
  216. return {};
  217. }
  218. return result;
  219. }
  220. if (exception())
  221. return {};
  222. if (result.is_object())
  223. return result;
  224. return this_value;
  225. }
  226. void VM::throw_exception(Exception* exception)
  227. {
  228. #ifdef VM_DEBUG
  229. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  230. auto& error = static_cast<Error&>(exception->value().as_object());
  231. dbgln("Throwing JavaScript Error: {}, {}", error.name(), error.message());
  232. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  233. auto function_name = m_call_stack[i]->function_name;
  234. if (function_name.is_empty())
  235. function_name = "<anonymous>";
  236. dbgln(" {}", function_name);
  237. }
  238. }
  239. #endif
  240. m_exception = exception;
  241. unwind(ScopeType::Try);
  242. }
  243. String VM::join_arguments() const
  244. {
  245. StringBuilder joined_arguments;
  246. for (size_t i = 0; i < argument_count(); ++i) {
  247. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  248. if (i != argument_count() - 1)
  249. joined_arguments.append(' ');
  250. }
  251. return joined_arguments.build();
  252. }
  253. Value VM::resolve_this_binding(GlobalObject& global_object) const
  254. {
  255. return get_this_environment()->get_this_binding(global_object);
  256. }
  257. const LexicalEnvironment* VM::get_this_environment() const
  258. {
  259. // We will always return because the Global environment will always be reached, which has a |this| binding.
  260. for (const LexicalEnvironment* environment = current_environment(); environment; environment = environment->parent()) {
  261. if (environment->has_this_binding())
  262. return environment;
  263. }
  264. ASSERT_NOT_REACHED();
  265. }
  266. Value VM::get_new_target() const
  267. {
  268. return get_this_environment()->new_target();
  269. }
  270. Value VM::call_internal(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  271. {
  272. ASSERT(!exception());
  273. CallFrame call_frame;
  274. call_frame.is_strict_mode = function.is_strict_mode();
  275. call_frame.function_name = function.name();
  276. call_frame.this_value = function.bound_this().value_or(this_value);
  277. call_frame.arguments = function.bound_arguments();
  278. if (arguments.has_value())
  279. call_frame.arguments.append(move(arguments.release_value().values()));
  280. call_frame.environment = function.create_environment();
  281. ASSERT(call_frame.environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  282. call_frame.environment->bind_this_value(function.global_object(), call_frame.this_value);
  283. if (exception())
  284. return {};
  285. push_call_frame(call_frame, function.global_object());
  286. if (exception())
  287. return {};
  288. auto result = function.call();
  289. pop_call_frame();
  290. return result;
  291. }
  292. bool VM::in_strict_mode() const
  293. {
  294. if (call_stack().is_empty())
  295. return false;
  296. return call_frame().is_strict_mode;
  297. }
  298. }