VM.h 14 KB

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