VM.h 11 KB

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