Serenity Operating System
at master 83 lines 2.9 kB view raw
1/* 2 * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#pragma once 8 9#include <LibJS/Runtime/Object.h> 10#include <LibWasm/AbstractMachine/AbstractMachine.h> 11#include <LibWeb/Forward.h> 12#include <LibWeb/WebAssembly/WebAssemblyInstanceObjectPrototype.h> 13 14namespace Web::Bindings { 15 16class WebAssemblyMemoryObject; 17class WebAssemblyTableObject; 18JS::ThrowCompletionOr<size_t> parse_module(JS::VM&, JS::Object* buffer); 19JS::NativeFunction* create_native_function(JS::VM&, Wasm::FunctionAddress address, DeprecatedString const& name); 20JS::Value to_js_value(JS::VM&, Wasm::Value& wasm_value); 21JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::VM&, JS::Value value, Wasm::ValueType const& type); 22 23class WebAssemblyObject final : public JS::Object { 24 JS_OBJECT(WebAssemblyObject, JS::Object); 25 26public: 27 explicit WebAssemblyObject(JS::Realm&); 28 virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; 29 virtual ~WebAssemblyObject() override = default; 30 31 virtual void visit_edges(Cell::Visitor&) override; 32 33 static JS::ThrowCompletionOr<size_t> instantiate_module(JS::VM&, Wasm::Module const&); 34 35 struct CompiledWebAssemblyModule { 36 explicit CompiledWebAssemblyModule(Wasm::Module&& module) 37 : module(move(module)) 38 { 39 } 40 41 Wasm::Module module; 42 }; 43 44 // FIXME: These should just be members of the module (instance) object, 45 // but the module needs to stick around while its instance is alive 46 // so ideally this would be a refcounted object, shared between 47 // WebAssemblyModuleObject's and WebAssemblyInstantiatedModuleObject's. 48 struct ModuleCache { 49 HashMap<Wasm::FunctionAddress, JS::FunctionObject*> function_instances; 50 HashMap<Wasm::MemoryAddress, WebAssemblyMemoryObject*> memory_instances; 51 HashMap<Wasm::TableAddress, WebAssemblyTableObject*> table_instances; 52 }; 53 struct GlobalModuleCache { 54 HashMap<Wasm::FunctionAddress, JS::NativeFunction*> function_instances; 55 }; 56 57 static Vector<NonnullOwnPtr<CompiledWebAssemblyModule>> s_compiled_modules; 58 static Vector<NonnullOwnPtr<Wasm::ModuleInstance>> s_instantiated_modules; 59 static Vector<ModuleCache> s_module_caches; 60 static GlobalModuleCache s_global_cache; 61 62 static Wasm::AbstractMachine s_abstract_machine; 63 64private: 65 JS_DECLARE_NATIVE_FUNCTION(validate); 66 JS_DECLARE_NATIVE_FUNCTION(compile); 67 JS_DECLARE_NATIVE_FUNCTION(instantiate); 68}; 69 70class WebAssemblyMemoryObject final : public JS::Object { 71 JS_OBJECT(WebAssemblyMemoryObject, JS::Object); 72 73public: 74 WebAssemblyMemoryObject(JS::Realm&, Wasm::MemoryAddress); 75 virtual ~WebAssemblyMemoryObject() override = default; 76 77 auto address() const { return m_address; } 78 79private: 80 Wasm::MemoryAddress m_address; 81}; 82 83}