VM.h 13 KB

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