VM.h 14 KB

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