WebAssemblyObject.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. JS::ThrowCompletionOr<size_t> parse_module(JS::VM&, JS::Object* buffer);
  12. JS::NativeFunction* create_native_function(JS::VM&, Wasm::FunctionAddress address, DeprecatedString const& name);
  13. JS::Value to_js_value(JS::VM&, Wasm::Value& wasm_value);
  14. JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::VM&, JS::Value value, Wasm::ValueType const& type);
  15. class WebAssemblyObject final : public JS::Object {
  16. JS_OBJECT(WebAssemblyObject, JS::Object);
  17. public:
  18. explicit WebAssemblyObject(JS::Realm&);
  19. virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
  20. virtual ~WebAssemblyObject() override = default;
  21. virtual void visit_edges(Cell::Visitor&) override;
  22. static JS::ThrowCompletionOr<size_t> instantiate_module(JS::VM&, Wasm::Module const&);
  23. struct CompiledWebAssemblyModule {
  24. explicit CompiledWebAssemblyModule(Wasm::Module&& module)
  25. : module(move(module))
  26. {
  27. }
  28. Wasm::Module module;
  29. };
  30. // FIXME: These should just be members of the module (instance) object,
  31. // but the module needs to stick around while its instance is alive
  32. // so ideally this would be a refcounted object, shared between
  33. // WebAssemblyModuleObject's and WebAssemblyInstantiatedModuleObject's.
  34. struct ModuleCache {
  35. HashMap<Wasm::FunctionAddress, JS::GCPtr<JS::FunctionObject>> function_instances;
  36. HashMap<Wasm::MemoryAddress, JS::GCPtr<WebAssembly::Memory>> memory_instances;
  37. HashMap<Wasm::TableAddress, JS::GCPtr<WebAssembly::Table>> table_instances;
  38. };
  39. struct GlobalModuleCache {
  40. HashMap<Wasm::FunctionAddress, JS::GCPtr<JS::NativeFunction>> function_instances;
  41. };
  42. static Vector<NonnullOwnPtr<CompiledWebAssemblyModule>> s_compiled_modules;
  43. static Vector<NonnullOwnPtr<Wasm::ModuleInstance>> s_instantiated_modules;
  44. static Vector<ModuleCache> s_module_caches;
  45. static GlobalModuleCache s_global_cache;
  46. static Wasm::AbstractMachine s_abstract_machine;
  47. private:
  48. JS_DECLARE_NATIVE_FUNCTION(validate);
  49. JS_DECLARE_NATIVE_FUNCTION(compile);
  50. JS_DECLARE_NATIVE_FUNCTION(instantiate);
  51. };
  52. }