VM.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, 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/FlyString.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/Iterator.h>
  23. #include <LibJS/Runtime/Promise.h>
  24. #include <LibJS/Runtime/Value.h>
  25. namespace JS {
  26. class Identifier;
  27. struct BindingPattern;
  28. class VM : public RefCounted<VM> {
  29. public:
  30. struct CustomData {
  31. virtual ~CustomData();
  32. };
  33. static NonnullRefPtr<VM> create(OwnPtr<CustomData> = {});
  34. ~VM();
  35. Heap& heap() { return m_heap; }
  36. const Heap& heap() const { return m_heap; }
  37. Interpreter& interpreter();
  38. Interpreter* interpreter_if_exists();
  39. void push_interpreter(Interpreter&);
  40. void pop_interpreter(Interpreter&);
  41. void dump_backtrace() const;
  42. class InterpreterExecutionScope {
  43. public:
  44. InterpreterExecutionScope(Interpreter&);
  45. ~InterpreterExecutionScope();
  46. private:
  47. Interpreter& m_interpreter;
  48. };
  49. void gather_roots(HashTable<Cell*>&);
  50. #define __JS_ENUMERATE(SymbolName, snake_name) \
  51. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  52. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  53. #undef __JS_ENUMERATE
  54. Symbol* get_global_symbol(const String& description);
  55. HashMap<String, PrimitiveString*>& string_cache() { return m_string_cache; }
  56. PrimitiveString& empty_string() { return *m_empty_string; }
  57. PrimitiveString& single_ascii_character_string(u8 character)
  58. {
  59. VERIFY(character < 0x80);
  60. return *m_single_ascii_character_strings[character];
  61. }
  62. bool did_reach_stack_space_limit() const
  63. {
  64. // Address sanitizer (ASAN) used to check for more space but
  65. // currently we can't detect the stack size with it enabled.
  66. return m_stack_info.size_free() < 32 * KiB;
  67. }
  68. ThrowCompletionOr<void> push_execution_context(ExecutionContext& context, GlobalObject& global_object)
  69. {
  70. // Ensure we got some stack space left, so the next function call doesn't kill us.
  71. if (did_reach_stack_space_limit())
  72. return throw_completion<InternalError>(global_object, ErrorType::CallStackSizeExceeded);
  73. m_execution_context_stack.append(&context);
  74. return {};
  75. }
  76. void pop_execution_context()
  77. {
  78. m_execution_context_stack.take_last();
  79. if (m_execution_context_stack.is_empty() && on_call_stack_emptied)
  80. on_call_stack_emptied();
  81. }
  82. ExecutionContext& running_execution_context() { return *m_execution_context_stack.last(); }
  83. ExecutionContext const& running_execution_context() const { return *m_execution_context_stack.last(); }
  84. Vector<ExecutionContext*> const& execution_context_stack() const { return m_execution_context_stack; }
  85. Vector<ExecutionContext*>& execution_context_stack() { return m_execution_context_stack; }
  86. Environment const* lexical_environment() const { return running_execution_context().lexical_environment; }
  87. Environment* lexical_environment() { return running_execution_context().lexical_environment; }
  88. Environment const* variable_environment() const { return running_execution_context().variable_environment; }
  89. Environment* variable_environment() { return running_execution_context().variable_environment; }
  90. // https://tc39.es/ecma262/#current-realm
  91. // The value of the Realm component of the running execution context is also called the current Realm Record.
  92. Realm const* current_realm() const { return running_execution_context().realm; }
  93. Realm* current_realm() { return running_execution_context().realm; }
  94. // https://tc39.es/ecma262/#active-function-object
  95. // The value of the Function component of the running execution context is also called the active function object.
  96. FunctionObject const* active_function_object() const { return running_execution_context().function; }
  97. FunctionObject* active_function_object() { return running_execution_context().function; }
  98. bool in_strict_mode() const;
  99. size_t argument_count() const
  100. {
  101. if (m_execution_context_stack.is_empty())
  102. return 0;
  103. return running_execution_context().arguments.size();
  104. }
  105. Value argument(size_t index) const
  106. {
  107. if (m_execution_context_stack.is_empty())
  108. return {};
  109. auto& arguments = running_execution_context().arguments;
  110. return index < arguments.size() ? arguments[index] : js_undefined();
  111. }
  112. Value this_value(Object& global_object) const
  113. {
  114. if (m_execution_context_stack.is_empty())
  115. return &global_object;
  116. return running_execution_context().this_value;
  117. }
  118. ThrowCompletionOr<Value> resolve_this_binding(GlobalObject&);
  119. const StackInfo& stack_info() const { return m_stack_info; };
  120. u32 execution_generation() const { return m_execution_generation; }
  121. void finish_execution_generation() { ++m_execution_generation; }
  122. ThrowCompletionOr<Reference> resolve_binding(FlyString const&, Environment* = nullptr);
  123. ThrowCompletionOr<Reference> get_identifier_reference(Environment*, FlyString, bool strict, size_t hops = 0);
  124. // 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception
  125. template<typename T, typename... Args>
  126. Completion throw_completion(GlobalObject& global_object, Args&&... args)
  127. {
  128. return JS::throw_completion(T::create(global_object, forward<Args>(args)...));
  129. }
  130. template<typename T, typename... Args>
  131. Completion throw_completion(GlobalObject& global_object, ErrorType type, Args&&... args)
  132. {
  133. return throw_completion<T>(global_object, String::formatted(type.message(), forward<Args>(args)...));
  134. }
  135. Value construct(FunctionObject&, FunctionObject& new_target, Optional<MarkedVector<Value>> arguments);
  136. String join_arguments(size_t start_index = 0) const;
  137. Value get_new_target();
  138. CommonPropertyNames names;
  139. void run_queued_promise_jobs();
  140. void enqueue_promise_job(Function<ThrowCompletionOr<Value>()> job, Realm*);
  141. void run_queued_finalization_registry_cleanup_jobs();
  142. void enqueue_finalization_registry_cleanup_job(FinalizationRegistry&);
  143. void promise_rejection_tracker(Promise&, Promise::RejectionOperation) const;
  144. Function<void()> on_call_stack_emptied;
  145. Function<void(Promise&)> on_promise_unhandled_rejection;
  146. Function<void(Promise&)> on_promise_rejection_handled;
  147. ThrowCompletionOr<void> initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor);
  148. CustomData* custom_data() { return m_custom_data; }
  149. ThrowCompletionOr<void> destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object);
  150. ThrowCompletionOr<void> binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object);
  151. ThrowCompletionOr<void> binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object);
  152. ThrowCompletionOr<Value> named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name);
  153. void save_execution_context_stack();
  154. void restore_execution_context_stack();
  155. // Do not call this method unless you are sure this is the only and first module to be loaded in this vm.
  156. ThrowCompletionOr<void> link_and_eval_module(Badge<Interpreter>, SourceTextModule& module);
  157. ScriptOrModule get_active_script_or_module() const;
  158. Function<ThrowCompletionOr<NonnullRefPtr<Module>>(ScriptOrModule, ModuleRequest const&)> host_resolve_imported_module;
  159. Function<void(ScriptOrModule, ModuleRequest, PromiseCapability)> host_import_module_dynamically;
  160. Function<void(ScriptOrModule, ModuleRequest const&, PromiseCapability, Promise*)> host_finish_dynamic_import;
  161. Function<HashMap<PropertyKey, Value>(SourceTextModule const&)> host_get_import_meta_properties;
  162. Function<void(Object*, SourceTextModule const&)> host_finalize_import_meta;
  163. Function<Vector<String>()> host_get_supported_import_assertions;
  164. void enable_default_host_import_module_dynamically_hook();
  165. Function<void(Promise&, Promise::RejectionOperation)> host_promise_rejection_tracker;
  166. Function<ThrowCompletionOr<Value>(GlobalObject&, JobCallback&, Value, MarkedVector<Value>)> host_call_job_callback;
  167. Function<void(FinalizationRegistry&)> host_enqueue_finalization_registry_cleanup_job;
  168. Function<void(Function<ThrowCompletionOr<Value>()>, Realm*)> host_enqueue_promise_job;
  169. Function<JobCallback(FunctionObject&)> host_make_job_callback;
  170. private:
  171. explicit VM(OwnPtr<CustomData>);
  172. ThrowCompletionOr<void> property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object);
  173. ThrowCompletionOr<void> iterator_binding_initialization(BindingPattern const& binding, Iterator& iterator_record, Environment* environment, GlobalObject& global_object);
  174. ThrowCompletionOr<NonnullRefPtr<Module>> resolve_imported_module(ScriptOrModule referencing_script_or_module, ModuleRequest const& module_request);
  175. ThrowCompletionOr<void> link_and_eval_module(Module& module);
  176. void import_module_dynamically(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability promise_capability);
  177. void finish_dynamic_import(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability promise_capability, Promise* inner_promise);
  178. HashMap<String, PrimitiveString*> m_string_cache;
  179. Heap m_heap;
  180. Vector<Interpreter*> m_interpreters;
  181. Vector<ExecutionContext*> m_execution_context_stack;
  182. Vector<Vector<ExecutionContext*>> m_saved_execution_context_stacks;
  183. StackInfo m_stack_info;
  184. HashMap<String, Symbol*> m_global_symbol_map;
  185. Vector<Function<ThrowCompletionOr<Value>()>> m_promise_jobs;
  186. Vector<FinalizationRegistry*> m_finalization_registry_cleanup_jobs;
  187. PrimitiveString* m_empty_string { nullptr };
  188. PrimitiveString* m_single_ascii_character_strings[128] {};
  189. struct StoredModule {
  190. ScriptOrModule referencing_script_or_module;
  191. String filepath;
  192. String type;
  193. NonnullRefPtr<Module> module;
  194. bool has_once_started_linking { false };
  195. };
  196. StoredModule* get_stored_module(ScriptOrModule const& script_or_module, String const& filepath, String const& type);
  197. Vector<StoredModule> m_loaded_modules;
  198. #define __JS_ENUMERATE(SymbolName, snake_name) \
  199. Symbol* m_well_known_symbol_##snake_name { nullptr };
  200. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  201. #undef __JS_ENUMERATE
  202. u32 m_execution_generation { 0 };
  203. OwnPtr<CustomData> m_custom_data;
  204. };
  205. ALWAYS_INLINE Heap& Cell::heap() const
  206. {
  207. return HeapBlock::from_cell(this)->heap();
  208. }
  209. ALWAYS_INLINE VM& Cell::vm() const
  210. {
  211. return heap().vm();
  212. }
  213. }