VM.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/FlyString.h>
  10. #include <AK/Function.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/RefCounted.h>
  13. #include <AK/StackInfo.h>
  14. #include <AK/Variant.h>
  15. #include <LibJS/Heap/Heap.h>
  16. #include <LibJS/Runtime/CommonPropertyNames.h>
  17. #include <LibJS/Runtime/Completion.h>
  18. #include <LibJS/Runtime/Error.h>
  19. #include <LibJS/Runtime/ErrorTypes.h>
  20. #include <LibJS/Runtime/Exception.h>
  21. #include <LibJS/Runtime/ExecutionContext.h>
  22. #include <LibJS/Runtime/Iterator.h>
  23. #include <LibJS/Runtime/MarkedValueList.h>
  24. #include <LibJS/Runtime/Promise.h>
  25. #include <LibJS/Runtime/Value.h>
  26. namespace JS {
  27. class Identifier;
  28. struct BindingPattern;
  29. class VM : public RefCounted<VM> {
  30. public:
  31. struct CustomData {
  32. virtual ~CustomData();
  33. };
  34. static NonnullRefPtr<VM> create(OwnPtr<CustomData> = {});
  35. ~VM();
  36. Heap& heap() { return m_heap; }
  37. const Heap& heap() const { return m_heap; }
  38. Interpreter& interpreter();
  39. Interpreter* interpreter_if_exists();
  40. void push_interpreter(Interpreter&);
  41. void pop_interpreter(Interpreter&);
  42. Exception* exception() { return m_exception; }
  43. void set_exception(Exception& exception) { m_exception = &exception; }
  44. void clear_exception() { m_exception = nullptr; }
  45. void dump_backtrace() const;
  46. class InterpreterExecutionScope {
  47. public:
  48. InterpreterExecutionScope(Interpreter&);
  49. ~InterpreterExecutionScope();
  50. private:
  51. Interpreter& m_interpreter;
  52. };
  53. void gather_roots(HashTable<Cell*>&);
  54. #define __JS_ENUMERATE(SymbolName, snake_name) \
  55. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  56. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  57. #undef __JS_ENUMERATE
  58. Symbol* get_global_symbol(const String& description);
  59. HashMap<String, PrimitiveString*>& string_cache() { return m_string_cache; }
  60. PrimitiveString& empty_string() { return *m_empty_string; }
  61. PrimitiveString& single_ascii_character_string(u8 character)
  62. {
  63. VERIFY(character < 0x80);
  64. return *m_single_ascii_character_strings[character];
  65. }
  66. bool did_reach_stack_space_limit() const
  67. {
  68. #ifdef HAS_ADDRESS_SANITIZER
  69. return m_stack_info.size_free() < 32 * KiB;
  70. #else
  71. return m_stack_info.size_free() < 16 * KiB;
  72. #endif
  73. }
  74. ThrowCompletionOr<void> push_execution_context(ExecutionContext& context, GlobalObject& global_object)
  75. {
  76. VERIFY(!exception());
  77. // Ensure we got some stack space left, so the next function call doesn't kill us.
  78. if (did_reach_stack_space_limit())
  79. return throw_completion<InternalError>(global_object, ErrorType::CallStackSizeExceeded);
  80. m_execution_context_stack.append(&context);
  81. return {};
  82. }
  83. void pop_execution_context()
  84. {
  85. m_execution_context_stack.take_last();
  86. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  87. on_call_stack_emptied();
  88. }
  89. ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
  90. ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
  91. Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
  92. Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
  93. Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
  94. Environment* lexical_environment() { return running_execution_context().lexical_environment; }
  95. Environment const* variable_environment() const { return running_execution_context().variable_environment; }
  96. Environment* variable_environment() { return running_execution_context().variable_environment; }
  97. // https://tc39.es/ecma262/#current-realm
  98. // The value of the Realm component of the running execution context is also called the current Realm Record.
  99. Realm const* current_realm() const { return running_execution_context().realm; }
  100. Realm* current_realm() { return running_execution_context().realm; }
  101. // https://tc39.es/ecma262/#active-function-object
  102. // The value of the Function component of the running execution context is also called the active function object.
  103. FunctionObject const* active_function_object() const { return running_execution_context().function; }
  104. FunctionObject* active_function_object() { return running_execution_context().function; }
  105. bool in_strict_mode() const;
  106. size_t argument_count() const
  107. {
  108. if (m_execution_context_stack.is_empty())
  109. return 0;
  110. return running_execution_context().arguments.size();
  111. }
  112. Value argument(size_t index) const
  113. {
  114. if (m_execution_context_stack.is_empty())
  115. return {};
  116. auto& arguments = running_execution_context().arguments;
  117. return index < arguments.size() ? arguments[index] : js_undefined();
  118. }
  119. Value this_value(Object& global_object) const
  120. {
  121. if (m_execution_context_stack.is_empty())
  122. return &global_object;
  123. return running_execution_context().this_value;
  124. }
  125. ThrowCompletionOr<Value> resolve_this_binding(GlobalObject&);
  126. const StackInfo& stack_info() const { return m_stack_info; };
  127. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  128. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  129. u32 execution_generation() const { return m_execution_generation; }
  130. void finish_execution_generation() { ++m_execution_generation; }
  131. ThrowCompletionOr<Reference> resolve_binding(FlyString const&, Environment* = nullptr);
  132. ThrowCompletionOr<Reference> get_identifier_reference(Environment*, FlyString, bool strict, size_t hops = 0);
  133. template<typename T, typename... Args>
  134. void throw_exception(GlobalObject& global_object, Args&&... args)
  135. {
  136. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  137. }
  138. void throw_exception(Exception&);
  139. void throw_exception(GlobalObject& global_object, Value value)
  140. {
  141. return throw_exception(*heap().allocate<Exception>(global_object, value));
  142. }
  143. template<typename T, typename... Args>
  144. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  145. {
  146. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  147. }
  148. // 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception
  149. template<typename T, typename... Args>
  150. Completion throw_completion(GlobalObject& global_object, Args&&... args)
  151. {
  152. auto* error = T::create(global_object, forward<Args>(args)...);
  153. // NOTE: This is temporary until we remove VM::exception().
  154. throw_exception(global_object, error);
  155. return JS::throw_completion(error);
  156. }
  157. template<typename T, typename... Args>
  158. Completion throw_completion(GlobalObject& global_object, ErrorType type, Args&&... args)
  159. {
  160. return throw_completion<T>(global_object, String::formatted(type.message(), forward<Args>(args)...));
  161. }
  162. Value construct(FunctionObject&, FunctionObject& new_target, Optional<MarkedValueList> arguments);
  163. String join_arguments(size_t start_index = 0) const;
  164. Value get_new_target();
  165. template<typename... Args>
  166. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> call(FunctionObject& function, Value this_value, Args... args)
  167. {
  168. if constexpr (sizeof...(Args) > 0) {
  169. MarkedValueList arguments_list { heap() };
  170. (..., arguments_list.append(move(args)));
  171. return call(function, this_value, move(arguments_list));
  172. }
  173. return call(function, this_value);
  174. }
  175. CommonPropertyNames names;
  176. void run_queued_promise_jobs();
  177. void enqueue_promise_job(NativeFunction&);
  178. void run_queued_finalization_registry_cleanup_jobs();
  179. void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
  180. void promise_rejection_tracker(const Promise&, Promise::RejectionOperation) const;
  181. Function<void()> on_call_stack_emptied;
  182. Function<void(const Promise&)> on_promise_unhandled_rejection;
  183. Function<void(const Promise&)> on_promise_rejection_handled;
  184. ThrowCompletionOr<void> initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor);
  185. CustomData* custom_data() { return m_custom_data; }
  186. ThrowCompletionOr<void> destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object);
  187. ThrowCompletionOr<void> binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object);
  188. ThrowCompletionOr<void> binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object);
  189. ThrowCompletionOr<Value> named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name);
  190. void save_execution_context_stack();
  191. void restore_execution_context_stack();
  192. private:
  193. explicit VM(OwnPtr<CustomData>);
  194. [[nodiscard]] ThrowCompletionOr<Value> call_internal(FunctionObject&, Value this_value, Optional<MarkedValueList> arguments);
  195. ThrowCompletionOr<void> property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object);
  196. ThrowCompletionOr<void> iterator_binding_initialization(BindingPattern const& binding, Iterator& iterator_record, Environment* environment, GlobalObject& global_object);
  197. Exception* m_exception { nullptr };
  198. HashMap<String, PrimitiveString*> m_string_cache;
  199. Heap m_heap;
  200. Vector<Interpreter*> m_interpreters;
  201. Vector<ExecutionContext*> m_execution_context_stack;
  202. Vector<Vector<ExecutionContext*>> m_saved_execution_context_stacks;
  203. StackInfo m_stack_info;
  204. HashMap<String, Symbol*> m_global_symbol_map;
  205. Vector<NativeFunction*> m_promise_jobs;
  206. Vector<FinalizationRegistry*> m_finalization_registry_cleanup_jobs;
  207. PrimitiveString* m_empty_string { nullptr };
  208. PrimitiveString* m_single_ascii_character_strings[128] {};
  209. #define __JS_ENUMERATE(SymbolName, snake_name) \
  210. Symbol* m_well_known_symbol_##snake_name { nullptr };
  211. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  212. #undef __JS_ENUMERATE
  213. bool m_underscore_is_last_value { false };
  214. u32 m_execution_generation { 0 };
  215. OwnPtr<CustomData> m_custom_data;
  216. };
  217. template<>
  218. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  219. template<>
  220. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  221. template<>
  222. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> VM::call(FunctionObject& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  223. ALWAYS_INLINE Heap& Cell::heap() const
  224. {
  225. return HeapBlock::from_cell(this)->heap();
  226. }
  227. ALWAYS_INLINE VM& Cell::vm() const
  228. {
  229. return heap().vm();
  230. }
  231. }