WebAssemblyObject.h 2.4 KB

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