VM.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 ExecutionContext {
  39. const ASTNode* current_node { nullptr };
  40. FlyString function_name;
  41. FunctionObject* function { nullptr };
  42. Value this_value;
  43. Vector<Value> arguments;
  44. Object* arguments_object { nullptr };
  45. Environment* lexical_environment { nullptr };
  46. Environment* variable_environment { nullptr };
  47. bool is_strict_mode { false };
  48. };
  49. class VM : public RefCounted<VM> {
  50. public:
  51. static NonnullRefPtr<VM> create();
  52. ~VM();
  53. Heap& heap() { return m_heap; }
  54. const Heap& heap() const { return m_heap; }
  55. Interpreter& interpreter();
  56. Interpreter* interpreter_if_exists();
  57. void push_interpreter(Interpreter&);
  58. void pop_interpreter(Interpreter&);
  59. Exception* exception() { return m_exception; }
  60. void set_exception(Exception& exception) { m_exception = &exception; }
  61. void clear_exception() { m_exception = nullptr; }
  62. void dump_backtrace() const;
  63. void dump_environment_chain() const;
  64. class InterpreterExecutionScope {
  65. public:
  66. InterpreterExecutionScope(Interpreter&);
  67. ~InterpreterExecutionScope();
  68. private:
  69. Interpreter& m_interpreter;
  70. };
  71. void gather_roots(HashTable<Cell*>&);
  72. #define __JS_ENUMERATE(SymbolName, snake_name) \
  73. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  74. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  75. #undef __JS_ENUMERATE
  76. Symbol* get_global_symbol(const String& description);
  77. PrimitiveString& empty_string() { return *m_empty_string; }
  78. PrimitiveString& single_ascii_character_string(u8 character)
  79. {
  80. VERIFY(character < 0x80);
  81. return *m_single_ascii_character_strings[character];
  82. }
  83. void push_execution_context(ExecutionContext& context, GlobalObject& global_object)
  84. {
  85. VERIFY(!exception());
  86. // Ensure we got some stack space left, so the next function call doesn't kill us.
  87. // Note: the 32 kiB used to be 16 kiB, but that turned out to not be enough with ASAN enabled.
  88. if (m_stack_info.size_free() < 32 * KiB)
  89. throw_exception<Error>(global_object, "Call stack size limit exceeded");
  90. else
  91. m_execution_context_stack.append(&context);
  92. }
  93. void pop_execution_context()
  94. {
  95. m_execution_context_stack.take_last();
  96. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  97. on_call_stack_emptied();
  98. }
  99. ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
  100. ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
  101. Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
  102. Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
  103. Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
  104. Environment* lexical_environment() { return running_execution_context().lexical_environment; }
  105. Environment const* variable_environment() const { return running_execution_context().variable_environment; }
  106. Environment* variable_environment() { return running_execution_context().variable_environment; }
  107. bool in_strict_mode() const;
  108. template<typename Callback>
  109. void for_each_argument(Callback callback)
  110. {
  111. if (m_execution_context_stack.is_empty())
  112. return;
  113. for (auto& value : running_execution_context().arguments)
  114. callback(value);
  115. }
  116. size_t argument_count() const
  117. {
  118. if (m_execution_context_stack.is_empty())
  119. return 0;
  120. return running_execution_context().arguments.size();
  121. }
  122. Value argument(size_t index) const
  123. {
  124. if (m_execution_context_stack.is_empty())
  125. return {};
  126. auto& arguments = running_execution_context().arguments;
  127. return index < arguments.size() ? arguments[index] : js_undefined();
  128. }
  129. Value this_value(Object& global_object) const
  130. {
  131. if (m_execution_context_stack.is_empty())
  132. return &global_object;
  133. return running_execution_context().this_value;
  134. }
  135. Value resolve_this_binding(GlobalObject&);
  136. Value last_value() const { return m_last_value; }
  137. void set_last_value(Badge<Bytecode::Interpreter>, Value value) { m_last_value = value; }
  138. void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
  139. const StackInfo& stack_info() const { return m_stack_info; };
  140. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  141. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  142. u32 execution_generation() const { return m_execution_generation; }
  143. void finish_execution_generation() { ++m_execution_generation; }
  144. void unwind(ScopeType type, FlyString label = {})
  145. {
  146. m_unwind_until = type;
  147. m_unwind_until_label = move(label);
  148. }
  149. void stop_unwind()
  150. {
  151. m_unwind_until = ScopeType::None;
  152. m_unwind_until_label = {};
  153. }
  154. bool should_unwind_until(ScopeType type, FlyString const& label) const
  155. {
  156. if (m_unwind_until_label.is_null())
  157. return m_unwind_until == type;
  158. return m_unwind_until == type && m_unwind_until_label == label;
  159. }
  160. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  161. ScopeType unwind_until() const { return m_unwind_until; }
  162. FlyString unwind_until_label() const { return m_unwind_until_label; }
  163. Value get_variable(const FlyString& name, GlobalObject&);
  164. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  165. bool delete_variable(FlyString const& name);
  166. void assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  167. void assign(const FlyString& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  168. void assign(const NonnullRefPtr<BindingPattern>& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  169. Reference resolve_binding(FlyString const&, Environment* = nullptr);
  170. Reference get_identifier_reference(Environment*, FlyString const&, bool strict);
  171. template<typename T, typename... Args>
  172. void throw_exception(GlobalObject& global_object, Args&&... args)
  173. {
  174. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  175. }
  176. void throw_exception(Exception&);
  177. void throw_exception(GlobalObject& global_object, Value value)
  178. {
  179. return throw_exception(*heap().allocate<Exception>(global_object, value));
  180. }
  181. template<typename T, typename... Args>
  182. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  183. {
  184. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  185. }
  186. Value construct(FunctionObject&, FunctionObject& new_target, Optional<MarkedValueList> arguments);
  187. String join_arguments(size_t start_index = 0) const;
  188. Value get_new_target();
  189. template<typename... Args>
  190. [[nodiscard]] ALWAYS_INLINE Value call(FunctionObject& function, Value this_value, Args... args)
  191. {
  192. if constexpr (sizeof...(Args) > 0) {
  193. MarkedValueList arglist { heap() };
  194. (..., arglist.append(move(args)));
  195. return call(function, this_value, move(arglist));
  196. }
  197. return call(function, this_value);
  198. }
  199. CommonPropertyNames names;
  200. void run_queued_promise_jobs();
  201. void enqueue_promise_job(NativeFunction&);
  202. void run_queued_finalization_registry_cleanup_jobs();
  203. void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
  204. void promise_rejection_tracker(const Promise&, Promise::RejectionOperation) const;
  205. Function<void()> on_call_stack_emptied;
  206. Function<void(const Promise&)> on_promise_unhandled_rejection;
  207. Function<void(const Promise&)> on_promise_rejection_handled;
  208. private:
  209. VM();
  210. [[nodiscard]] Value call_internal(FunctionObject&, Value this_value, Optional<MarkedValueList> arguments);
  211. void prepare_for_ordinary_call(FunctionObject&, ExecutionContext& callee_context, Value new_target);
  212. Exception* m_exception { nullptr };
  213. Heap m_heap;
  214. Vector<Interpreter*> m_interpreters;
  215. Vector<ExecutionContext*> m_execution_context_stack;
  216. Value m_last_value;
  217. ScopeType m_unwind_until { ScopeType::None };
  218. FlyString m_unwind_until_label;
  219. StackInfo m_stack_info;
  220. HashMap<String, Symbol*> m_global_symbol_map;
  221. Vector<NativeFunction*> m_promise_jobs;
  222. Vector<FinalizationRegistry*> m_finalization_registry_cleanup_jobs;
  223. PrimitiveString* m_empty_string { nullptr };
  224. PrimitiveString* m_single_ascii_character_strings[128] {};
  225. #define __JS_ENUMERATE(SymbolName, snake_name) \
  226. Symbol* m_well_known_symbol_##snake_name { nullptr };
  227. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  228. #undef __JS_ENUMERATE
  229. bool m_underscore_is_last_value { false };
  230. u32 m_execution_generation { 0 };
  231. };
  232. template<>
  233. [[nodiscard]] ALWAYS_INLINE Value VM::call(FunctionObject& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  234. template<>
  235. [[nodiscard]] ALWAYS_INLINE Value VM::call(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  236. template<>
  237. [[nodiscard]] ALWAYS_INLINE Value VM::call(FunctionObject& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  238. ALWAYS_INLINE Heap& Cell::heap() const
  239. {
  240. return HeapBlock::from_cell(this)->heap();
  241. }
  242. ALWAYS_INLINE VM& Cell::vm() const
  243. {
  244. return heap().vm();
  245. }
  246. }