VM.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/DeprecatedFlyString.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/Heap/MarkedVector.h>
  17. #include <LibJS/Runtime/CommonPropertyNames.h>
  18. #include <LibJS/Runtime/Completion.h>
  19. #include <LibJS/Runtime/Error.h>
  20. #include <LibJS/Runtime/ErrorTypes.h>
  21. #include <LibJS/Runtime/ExecutionContext.h>
  22. #include <LibJS/Runtime/Promise.h>
  23. #include <LibJS/Runtime/Value.h>
  24. namespace JS {
  25. class Identifier;
  26. struct BindingPattern;
  27. class VM : public RefCounted<VM> {
  28. public:
  29. struct CustomData {
  30. virtual ~CustomData() = default;
  31. virtual void spin_event_loop_until(JS::SafeFunction<bool()> goal_condition) = 0;
  32. };
  33. static ErrorOr<NonnullRefPtr<VM>> create(OwnPtr<CustomData> = {});
  34. ~VM();
  35. Heap& heap() { return m_heap; }
  36. Heap const& heap() const { return m_heap; }
  37. Bytecode::Interpreter& bytecode_interpreter();
  38. void dump_backtrace() const;
  39. void gather_roots(HashMap<Cell*, HeapRoot>&);
  40. #define __JS_ENUMERATE(SymbolName, snake_name) \
  41. NonnullGCPtr<Symbol> well_known_symbol_##snake_name() const \
  42. { \
  43. return *m_well_known_symbols.snake_name; \
  44. }
  45. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  46. #undef __JS_ENUMERATE
  47. HashMap<String, GCPtr<PrimitiveString>>& string_cache()
  48. {
  49. return m_string_cache;
  50. }
  51. HashMap<DeprecatedString, GCPtr<PrimitiveString>>& deprecated_string_cache()
  52. {
  53. return m_deprecated_string_cache;
  54. }
  55. PrimitiveString& empty_string() { return *m_empty_string; }
  56. PrimitiveString& single_ascii_character_string(u8 character)
  57. {
  58. VERIFY(character < 0x80);
  59. return *m_single_ascii_character_strings[character];
  60. }
  61. // This represents the list of errors from ErrorTypes.h whose messages are used in contexts which
  62. // must not fail to allocate when they are used. For example, we cannot allocate when we raise an
  63. // out-of-memory error, thus we pre-allocate that error string at VM creation time.
  64. enum class ErrorMessage {
  65. OutOfMemory,
  66. // Keep this last:
  67. __Count,
  68. };
  69. String const& error_message(ErrorMessage) const;
  70. bool did_reach_stack_space_limit() const
  71. {
  72. // Address sanitizer (ASAN) used to check for more space but
  73. // currently we can't detect the stack size with it enabled.
  74. return m_stack_info.size_free() < 32 * KiB;
  75. }
  76. // TODO: Rename this function instead of providing a second argument, now that the global object is no longer passed in.
  77. struct CheckStackSpaceLimitTag { };
  78. ThrowCompletionOr<void> push_execution_context(ExecutionContext& context, CheckStackSpaceLimitTag)
  79. {
  80. // Ensure we got some stack space left, so the next function call doesn't kill us.
  81. if (did_reach_stack_space_limit())
  82. return throw_completion<InternalError>(ErrorType::CallStackSizeExceeded);
  83. push_execution_context(context);
  84. return {};
  85. }
  86. void push_execution_context(ExecutionContext&);
  87. void pop_execution_context();
  88. // https://tc39.es/ecma262/#running-execution-context
  89. // At any point in time, there is at most one execution context per agent that is actually executing code.
  90. // This is known as the agent's running execution context.
  91. ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
  92. ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
  93. // https://tc39.es/ecma262/#execution-context-stack
  94. // The execution context stack is used to track execution contexts.
  95. Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
  96. Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
  97. Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
  98. Environment* lexical_environment() { return running_execution_context().lexical_environment; }
  99. Environment const* variable_environment() const { return running_execution_context().variable_environment; }
  100. Environment* variable_environment() { return running_execution_context().variable_environment; }
  101. // https://tc39.es/ecma262/#current-realm
  102. // The value of the Realm component of the running execution context is also called the current Realm Record.
  103. Realm const* current_realm() const { return running_execution_context().realm; }
  104. Realm* current_realm() { return running_execution_context().realm; }
  105. // https://tc39.es/ecma262/#active-function-object
  106. // The value of the Function component of the running execution context is also called the active function object.
  107. FunctionObject const* active_function_object() const { return running_execution_context().function; }
  108. FunctionObject* active_function_object() { return running_execution_context().function; }
  109. bool in_strict_mode() const;
  110. size_t argument_count() const
  111. {
  112. if (m_execution_context_stack.is_empty())
  113. return 0;
  114. return running_execution_context().arguments.size();
  115. }
  116. Value argument(size_t index) const
  117. {
  118. if (m_execution_context_stack.is_empty())
  119. return {};
  120. auto& arguments = running_execution_context().arguments;
  121. return index < arguments.size() ? arguments[index] : js_undefined();
  122. }
  123. Value this_value() const
  124. {
  125. VERIFY(!m_execution_context_stack.is_empty());
  126. return running_execution_context().this_value;
  127. }
  128. ThrowCompletionOr<Value> resolve_this_binding();
  129. StackInfo const& stack_info() const { return m_stack_info; }
  130. HashMap<String, NonnullGCPtr<Symbol>> const& global_symbol_registry() const { return m_global_symbol_registry; }
  131. HashMap<String, NonnullGCPtr<Symbol>>& global_symbol_registry() { return m_global_symbol_registry; }
  132. u32 execution_generation() const { return m_execution_generation; }
  133. void finish_execution_generation() { ++m_execution_generation; }
  134. ThrowCompletionOr<Reference> resolve_binding(DeprecatedFlyString const&, Environment* = nullptr);
  135. ThrowCompletionOr<Reference> get_identifier_reference(Environment*, DeprecatedFlyString, bool strict, size_t hops = 0);
  136. // 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception
  137. template<typename T, typename... Args>
  138. Completion throw_completion(Args&&... args)
  139. {
  140. auto& realm = *current_realm();
  141. auto completion = T::create(realm, forward<Args>(args)...);
  142. return JS::throw_completion(completion);
  143. }
  144. template<typename T, typename... Args>
  145. Completion throw_completion(ErrorType type, Args&&... args)
  146. {
  147. return throw_completion<T>(DeprecatedString::formatted(type.message(), forward<Args>(args)...));
  148. }
  149. Value get_new_target();
  150. Object* get_import_meta();
  151. Object& get_global_object();
  152. CommonPropertyNames names;
  153. void run_queued_promise_jobs();
  154. void enqueue_promise_job(Function<ThrowCompletionOr<Value>()> job, Realm*);
  155. void run_queued_finalization_registry_cleanup_jobs();
  156. void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
  157. void promise_rejection_tracker(Promise&, Promise::RejectionOperation) const;
  158. Function<void()> on_call_stack_emptied;
  159. Function<void(Promise&)> on_promise_unhandled_rejection;
  160. Function<void(Promise&)> on_promise_rejection_handled;
  161. CustomData* custom_data() { return m_custom_data; }
  162. ThrowCompletionOr<void> binding_initialization(DeprecatedFlyString const& target, Value value, Environment* environment);
  163. ThrowCompletionOr<void> binding_initialization(NonnullRefPtr<BindingPattern const> const& target, Value value, Environment* environment);
  164. ThrowCompletionOr<Value> named_evaluation_if_anonymous_function(ASTNode const& expression, DeprecatedFlyString const& name);
  165. void save_execution_context_stack();
  166. void restore_execution_context_stack();
  167. // Do not call this method unless you are sure this is the only and first module to be loaded in this vm.
  168. ThrowCompletionOr<void> link_and_eval_module(Badge<Bytecode::Interpreter>, SourceTextModule& module);
  169. ScriptOrModule get_active_script_or_module() const;
  170. Function<ThrowCompletionOr<NonnullGCPtr<Module>>(ScriptOrModule, ModuleRequest const&)> host_resolve_imported_module;
  171. Function<ThrowCompletionOr<void>(ScriptOrModule, ModuleRequest, PromiseCapability const&)> host_import_module_dynamically;
  172. Function<void(ScriptOrModule, ModuleRequest const&, PromiseCapability const&, Promise*)> host_finish_dynamic_import;
  173. Function<HashMap<PropertyKey, Value>(SourceTextModule&)> host_get_import_meta_properties;
  174. Function<void(Object*, SourceTextModule const&)> host_finalize_import_meta;
  175. Function<Vector<DeprecatedString>()> host_get_supported_import_assertions;
  176. void enable_default_host_import_module_dynamically_hook();
  177. Function<void(Promise&, Promise::RejectionOperation)> host_promise_rejection_tracker;
  178. Function<ThrowCompletionOr<Value>(JobCallback&, Value, MarkedVector<Value>)> host_call_job_callback;
  179. Function<void(FinalizationRegistry&)> host_enqueue_finalization_registry_cleanup_job;
  180. Function<void(Function<ThrowCompletionOr<Value>()>, Realm*)> host_enqueue_promise_job;
  181. Function<JobCallback(FunctionObject&)> host_make_job_callback;
  182. Function<ThrowCompletionOr<void>(Realm&)> host_ensure_can_compile_strings;
  183. Function<ThrowCompletionOr<void>(Object&)> host_ensure_can_add_private_element;
  184. // Execute a specific AST node either in AST or BC interpreter, depending on which one is enabled by default.
  185. // NOTE: This is meant as a temporary stopgap until everything is bytecode.
  186. ThrowCompletionOr<Value> execute_ast_node(ASTNode const&);
  187. private:
  188. using ErrorMessages = AK::Array<String, to_underlying(ErrorMessage::__Count)>;
  189. struct WellKnownSymbols {
  190. #define __JS_ENUMERATE(SymbolName, snake_name) \
  191. GCPtr<Symbol> snake_name;
  192. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  193. #undef __JS_ENUMERATE
  194. };
  195. VM(OwnPtr<CustomData>, ErrorMessages);
  196. ThrowCompletionOr<void> property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment);
  197. ThrowCompletionOr<void> iterator_binding_initialization(BindingPattern const& binding, IteratorRecord& iterator_record, Environment* environment);
  198. ThrowCompletionOr<NonnullGCPtr<Module>> resolve_imported_module(ScriptOrModule referencing_script_or_module, ModuleRequest const& module_request);
  199. ThrowCompletionOr<void> link_and_eval_module(Module& module);
  200. ThrowCompletionOr<void> import_module_dynamically(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability);
  201. void finish_dynamic_import(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability, Promise* inner_promise);
  202. void set_well_known_symbols(WellKnownSymbols well_known_symbols) { m_well_known_symbols = move(well_known_symbols); }
  203. HashMap<String, GCPtr<PrimitiveString>> m_string_cache;
  204. HashMap<DeprecatedString, GCPtr<PrimitiveString>> m_deprecated_string_cache;
  205. Heap m_heap;
  206. Vector<ExecutionContext*> m_execution_context_stack;
  207. Vector<Vector<ExecutionContext*>> m_saved_execution_context_stacks;
  208. StackInfo m_stack_info;
  209. // GlobalSymbolRegistry, https://tc39.es/ecma262/#table-globalsymbolregistry-record-fields
  210. HashMap<String, NonnullGCPtr<Symbol>> m_global_symbol_registry;
  211. Vector<Function<ThrowCompletionOr<Value>()>> m_promise_jobs;
  212. Vector<GCPtr<FinalizationRegistry>> m_finalization_registry_cleanup_jobs;
  213. GCPtr<PrimitiveString> m_empty_string;
  214. GCPtr<PrimitiveString> m_single_ascii_character_strings[128] {};
  215. ErrorMessages m_error_messages;
  216. struct StoredModule {
  217. ScriptOrModule referencing_script_or_module;
  218. DeprecatedString filename;
  219. DeprecatedString type;
  220. Handle<Module> module;
  221. bool has_once_started_linking { false };
  222. };
  223. StoredModule* get_stored_module(ScriptOrModule const& script_or_module, DeprecatedString const& filename, DeprecatedString const& type);
  224. Vector<StoredModule> m_loaded_modules;
  225. WellKnownSymbols m_well_known_symbols;
  226. u32 m_execution_generation { 0 };
  227. OwnPtr<CustomData> m_custom_data;
  228. OwnPtr<Bytecode::Interpreter> m_bytecode_interpreter;
  229. };
  230. template<typename GlobalObjectType, typename... Args>
  231. [[nodiscard]] static NonnullOwnPtr<ExecutionContext> create_simple_execution_context(VM& vm, Args&&... args)
  232. {
  233. auto root_execution_context = MUST(Realm::initialize_host_defined_realm(
  234. vm,
  235. [&](Realm& realm_) -> GlobalObject* {
  236. return vm.heap().allocate_without_realm<GlobalObjectType>(realm_, forward<Args>(args)...);
  237. },
  238. nullptr));
  239. return root_execution_context;
  240. }
  241. }