VM.h 14 KB

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