VM.h 12 KB

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