VM.h 12 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/Completion.h>
  17. #include <LibJS/Runtime/Error.h>
  18. #include <LibJS/Runtime/ErrorTypes.h>
  19. #include <LibJS/Runtime/Exception.h>
  20. #include <LibJS/Runtime/ExecutionContext.h>
  21. #include <LibJS/Runtime/MarkedValueList.h>
  22. #include <LibJS/Runtime/Promise.h>
  23. #include <LibJS/Runtime/Value.h>
  24. namespace JS {
  25. class Identifier;
  26. struct BindingPattern;
  27. enum class ScopeType {
  28. None,
  29. Function,
  30. Block,
  31. Try,
  32. Breakable,
  33. Continuable,
  34. };
  35. struct ScopeFrame {
  36. ScopeType type;
  37. NonnullRefPtr<ScopeNode> scope_node;
  38. bool pushed_environment { false };
  39. };
  40. class VM : public RefCounted<VM> {
  41. public:
  42. struct CustomData {
  43. virtual ~CustomData();
  44. };
  45. static NonnullRefPtr<VM> create(OwnPtr<CustomData> = {});
  46. ~VM();
  47. Heap& heap() { return m_heap; }
  48. const Heap& heap() const { return m_heap; }
  49. Interpreter& interpreter();
  50. Interpreter* interpreter_if_exists();
  51. void push_interpreter(Interpreter&);
  52. void pop_interpreter(Interpreter&);
  53. Exception* exception() { return m_exception; }
  54. void set_exception(Exception& exception) { m_exception = &exception; }
  55. void clear_exception() { m_exception = nullptr; }
  56. void dump_backtrace() const;
  57. void dump_environment_chain() const;
  58. class InterpreterExecutionScope {
  59. public:
  60. InterpreterExecutionScope(Interpreter&);
  61. ~InterpreterExecutionScope();
  62. private:
  63. Interpreter& m_interpreter;
  64. };
  65. void gather_roots(HashTable<Cell*>&);
  66. #define __JS_ENUMERATE(SymbolName, snake_name) \
  67. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  68. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  69. #undef __JS_ENUMERATE
  70. Symbol* get_global_symbol(const String& description);
  71. PrimitiveString& empty_string() { return *m_empty_string; }
  72. PrimitiveString& single_ascii_character_string(u8 character)
  73. {
  74. VERIFY(character < 0x80);
  75. return *m_single_ascii_character_strings[character];
  76. }
  77. bool did_reach_stack_space_limit() const
  78. {
  79. #ifdef HAS_ADDRESS_SANITIZER
  80. return m_stack_info.size_free() < 32 * KiB;
  81. #else
  82. return m_stack_info.size_free() < 16 * KiB;
  83. #endif
  84. }
  85. void push_execution_context(ExecutionContext& context, GlobalObject& global_object)
  86. {
  87. VERIFY(!exception());
  88. // Ensure we got some stack space left, so the next function call doesn't kill us.
  89. if (did_reach_stack_space_limit())
  90. throw_exception<Error>(global_object, ErrorType::CallStackSizeExceeded);
  91. else
  92. m_execution_context_stack.append(&context);
  93. }
  94. void pop_execution_context()
  95. {
  96. m_execution_context_stack.take_last();
  97. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  98. on_call_stack_emptied();
  99. }
  100. ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
  101. ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
  102. Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
  103. Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
  104. Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
  105. Environment* lexical_environment() { return running_execution_context().lexical_environment; }
  106. Environment const* variable_environment() const { return running_execution_context().variable_environment; }
  107. Environment* variable_environment() { return running_execution_context().variable_environment; }
  108. // https://tc39.es/ecma262/#current-realm
  109. // The value of the Realm component of the running execution context is also called the current Realm Record.
  110. Realm const* current_realm() const { return running_execution_context().realm; }
  111. Realm* current_realm() { return running_execution_context().realm; }
  112. bool in_strict_mode() const;
  113. template<typename Callback>
  114. void for_each_argument(Callback callback)
  115. {
  116. if (m_execution_context_stack.is_empty())
  117. return;
  118. for (auto& value : running_execution_context().arguments)
  119. callback(value);
  120. }
  121. size_t argument_count() const
  122. {
  123. if (m_execution_context_stack.is_empty())
  124. return 0;
  125. return running_execution_context().arguments.size();
  126. }
  127. Value argument(size_t index) const
  128. {
  129. if (m_execution_context_stack.is_empty())
  130. return {};
  131. auto& arguments = running_execution_context().arguments;
  132. return index < arguments.size() ? arguments[index] : js_undefined();
  133. }
  134. Value this_value(Object& global_object) const
  135. {
  136. if (m_execution_context_stack.is_empty())
  137. return &global_object;
  138. return running_execution_context().this_value;
  139. }
  140. Value resolve_this_binding(GlobalObject&);
  141. Value last_value() const { return m_last_value; }
  142. void set_last_value(Badge<Bytecode::Interpreter>, Value value) { m_last_value = value; }
  143. void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
  144. const StackInfo& stack_info() const { return m_stack_info; };
  145. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  146. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  147. u32 execution_generation() const { return m_execution_generation; }
  148. void finish_execution_generation() { ++m_execution_generation; }
  149. void unwind(ScopeType type, FlyString label = {})
  150. {
  151. m_unwind_until = type;
  152. m_unwind_until_label = move(label);
  153. }
  154. void stop_unwind()
  155. {
  156. m_unwind_until = ScopeType::None;
  157. m_unwind_until_label = {};
  158. }
  159. bool should_unwind_until(ScopeType type, FlyString const& label) const
  160. {
  161. if (m_unwind_until_label.is_null())
  162. return m_unwind_until == type;
  163. return m_unwind_until == type && m_unwind_until_label == label;
  164. }
  165. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  166. ScopeType unwind_until() const { return m_unwind_until; }
  167. FlyString unwind_until_label() const { return m_unwind_until_label; }
  168. Value get_variable(const FlyString& name, GlobalObject&);
  169. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  170. bool delete_variable(FlyString const& name);
  171. void assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  172. void assign(const FlyString& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  173. void assign(const NonnullRefPtr<BindingPattern>& target, Value, GlobalObject&, bool first_assignment = false, Environment* specific_scope = nullptr);
  174. Reference resolve_binding(FlyString const&, Environment* = nullptr);
  175. Reference get_identifier_reference(Environment*, FlyString, bool strict);
  176. template<typename T, typename... Args>
  177. void throw_exception(GlobalObject& global_object, Args&&... args)
  178. {
  179. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  180. }
  181. void throw_exception(Exception&);
  182. void throw_exception(GlobalObject& global_object, Value value)
  183. {
  184. return throw_exception(*heap().allocate<Exception>(global_object, value));
  185. }
  186. template<typename T, typename... Args>
  187. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  188. {
  189. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  190. }
  191. // 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception
  192. template<typename T, typename... Args>
  193. Completion throw_completion(GlobalObject& global_object, ErrorType type, Args&&... args)
  194. {
  195. auto* error = T::create(global_object, String::formatted(type.message(), forward<Args>(args)...));
  196. // NOTE: This is temporary until we remove VM::exception().
  197. throw_exception(global_object, error);
  198. return JS::throw_completion(error);
  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, Object* 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. }