VM.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/FlyString.h>
  9. #include <AK/Function.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/StackInfo.h>
  13. #include <AK/Variant.h>
  14. #include <LibJS/Heap/Heap.h>
  15. #include <LibJS/Runtime/CommonPropertyNames.h>
  16. #include <LibJS/Runtime/Error.h>
  17. #include <LibJS/Runtime/ErrorTypes.h>
  18. #include <LibJS/Runtime/Exception.h>
  19. #include <LibJS/Runtime/MarkedValueList.h>
  20. #include <LibJS/Runtime/Promise.h>
  21. #include <LibJS/Runtime/Value.h>
  22. namespace JS {
  23. class Identifier;
  24. struct BindingPattern;
  25. enum class ScopeType {
  26. None,
  27. Function,
  28. Block,
  29. Try,
  30. Breakable,
  31. Continuable,
  32. };
  33. struct ScopeFrame {
  34. ScopeType type;
  35. NonnullRefPtr<ScopeNode> scope_node;
  36. bool pushed_environment { false };
  37. };
  38. struct CallFrame {
  39. const ASTNode* current_node { nullptr };
  40. FlyString function_name;
  41. Value callee;
  42. Value this_value;
  43. Vector<Value> arguments;
  44. Array* arguments_object { nullptr };
  45. ScopeObject* scope { nullptr };
  46. bool is_strict_mode { false };
  47. };
  48. class VM : public RefCounted<VM> {
  49. public:
  50. static NonnullRefPtr<VM> create();
  51. ~VM();
  52. Heap& heap() { return m_heap; }
  53. const Heap& heap() const { return m_heap; }
  54. Interpreter& interpreter();
  55. Interpreter* interpreter_if_exists();
  56. void push_interpreter(Interpreter&);
  57. void pop_interpreter(Interpreter&);
  58. Exception* exception() { return m_exception; }
  59. void set_exception(Exception& exception) { m_exception = &exception; }
  60. void clear_exception() { m_exception = nullptr; }
  61. void dump_backtrace() const;
  62. class InterpreterExecutionScope {
  63. public:
  64. InterpreterExecutionScope(Interpreter&);
  65. ~InterpreterExecutionScope();
  66. private:
  67. Interpreter& m_interpreter;
  68. };
  69. void gather_roots(HashTable<Cell*>&);
  70. #define __JS_ENUMERATE(SymbolName, snake_name) \
  71. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  72. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  73. #undef __JS_ENUMERATE
  74. Symbol* get_global_symbol(const String& description);
  75. PrimitiveString& empty_string() { return *m_empty_string; }
  76. PrimitiveString& single_ascii_character_string(u8 character)
  77. {
  78. VERIFY(character < 0x80);
  79. return *m_single_ascii_character_strings[character];
  80. }
  81. void push_call_frame(CallFrame& call_frame, GlobalObject& global_object)
  82. {
  83. VERIFY(!exception());
  84. // Ensure we got some stack space left, so the next function call doesn't kill us.
  85. // Note: the 32 kiB used to be 16 kiB, but that turned out to not be enough with ASAN enabled.
  86. if (m_stack_info.size_free() < 32 * KiB)
  87. throw_exception<Error>(global_object, "Call stack size limit exceeded");
  88. else
  89. m_call_stack.append(&call_frame);
  90. }
  91. void pop_call_frame()
  92. {
  93. m_call_stack.take_last();
  94. if (m_call_stack.is_empty() && on_call_stack_emptied)
  95. on_call_stack_emptied();
  96. }
  97. CallFrame& call_frame() { return *m_call_stack.last(); }
  98. const CallFrame& call_frame() const { return *m_call_stack.last(); }
  99. const Vector<CallFrame*>& call_stack() const { return m_call_stack; }
  100. Vector<CallFrame*>& call_stack() { return m_call_stack; }
  101. const ScopeObject* current_scope() const { return call_frame().scope; }
  102. ScopeObject* current_scope() { return call_frame().scope; }
  103. bool in_strict_mode() const;
  104. template<typename Callback>
  105. void for_each_argument(Callback callback)
  106. {
  107. if (m_call_stack.is_empty())
  108. return;
  109. for (auto& value : call_frame().arguments)
  110. callback(value);
  111. }
  112. size_t argument_count() const
  113. {
  114. if (m_call_stack.is_empty())
  115. return 0;
  116. return call_frame().arguments.size();
  117. }
  118. Value argument(size_t index) const
  119. {
  120. if (m_call_stack.is_empty())
  121. return {};
  122. auto& arguments = call_frame().arguments;
  123. return index < arguments.size() ? arguments[index] : js_undefined();
  124. }
  125. Value this_value(Object& global_object) const
  126. {
  127. if (m_call_stack.is_empty())
  128. return &global_object;
  129. return call_frame().this_value;
  130. }
  131. Value last_value() const { return m_last_value; }
  132. void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
  133. const StackInfo& stack_info() const { return m_stack_info; };
  134. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  135. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  136. void unwind(ScopeType type, FlyString label = {})
  137. {
  138. m_unwind_until = type;
  139. m_unwind_until_label = move(label);
  140. }
  141. void stop_unwind()
  142. {
  143. m_unwind_until = ScopeType::None;
  144. m_unwind_until_label = {};
  145. }
  146. bool should_unwind_until(ScopeType type, FlyString const& label) const
  147. {
  148. if (m_unwind_until_label.is_null())
  149. return m_unwind_until == type;
  150. return m_unwind_until == type && m_unwind_until_label == label;
  151. }
  152. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  153. ScopeType unwind_until() const { return m_unwind_until; }
  154. Value get_variable(const FlyString& name, GlobalObject&);
  155. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false, ScopeObject* specific_scope = nullptr);
  156. void assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value, GlobalObject&, bool first_assignment = false, ScopeObject* specific_scope = nullptr);
  157. void assign(const FlyString& target, Value, GlobalObject&, bool first_assignment = false, ScopeObject* specific_scope = nullptr);
  158. void assign(const NonnullRefPtr<BindingPattern>& target, Value, GlobalObject&, bool first_assignment = false, ScopeObject* specific_scope = nullptr);
  159. Reference get_reference(const FlyString& name);
  160. template<typename T, typename... Args>
  161. void throw_exception(GlobalObject& global_object, Args&&... args)
  162. {
  163. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  164. }
  165. void throw_exception(Exception&);
  166. void throw_exception(GlobalObject& global_object, Value value)
  167. {
  168. return throw_exception(*heap().allocate<Exception>(global_object, value));
  169. }
  170. template<typename T, typename... Args>
  171. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  172. {
  173. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  174. }
  175. Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject&);
  176. String join_arguments(size_t start_index = 0) const;
  177. Value resolve_this_binding(GlobalObject&) const;
  178. const ScopeObject* find_this_scope() const;
  179. Value get_new_target() const;
  180. template<typename... Args>
  181. [[nodiscard]] ALWAYS_INLINE Value call(Function& function, Value this_value, Args... args)
  182. {
  183. if constexpr (sizeof...(Args) > 0) {
  184. MarkedValueList arglist { heap() };
  185. (..., arglist.append(move(args)));
  186. return call(function, this_value, move(arglist));
  187. }
  188. return call(function, this_value);
  189. }
  190. CommonPropertyNames names;
  191. Shape& scope_object_shape() { return *m_scope_object_shape; }
  192. void run_queued_promise_jobs();
  193. void enqueue_promise_job(NativeFunction&);
  194. void promise_rejection_tracker(const Promise&, Promise::RejectionOperation) const;
  195. AK::Function<void()> on_call_stack_emptied;
  196. AK::Function<void(const Promise&)> on_promise_unhandled_rejection;
  197. AK::Function<void(const Promise&)> on_promise_rejection_handled;
  198. private:
  199. VM();
  200. [[nodiscard]] Value call_internal(Function&, Value this_value, Optional<MarkedValueList> arguments);
  201. Exception* m_exception { nullptr };
  202. Heap m_heap;
  203. Vector<Interpreter*> m_interpreters;
  204. Vector<CallFrame*> m_call_stack;
  205. Value m_last_value;
  206. ScopeType m_unwind_until { ScopeType::None };
  207. FlyString m_unwind_until_label;
  208. StackInfo m_stack_info;
  209. HashMap<String, Symbol*> m_global_symbol_map;
  210. Vector<NativeFunction*> m_promise_jobs;
  211. PrimitiveString* m_empty_string { nullptr };
  212. PrimitiveString* m_single_ascii_character_strings[128] {};
  213. #define __JS_ENUMERATE(SymbolName, snake_name) \
  214. Symbol* m_well_known_symbol_##snake_name { nullptr };
  215. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  216. #undef __JS_ENUMERATE
  217. Shape* m_scope_object_shape { nullptr };
  218. bool m_underscore_is_last_value { false };
  219. };
  220. template<>
  221. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  222. template<>
  223. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  224. template<>
  225. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  226. ALWAYS_INLINE Heap& Cell::heap() const
  227. {
  228. return HeapBlock::from_cell(this)->heap();
  229. }
  230. ALWAYS_INLINE VM& Cell::vm() const
  231. {
  232. return heap().vm();
  233. }
  234. }