VM.h 13 KB

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