WebAssemblyMemoryConstructor.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/Intrinsics.h>
  7. #include <LibWeb/WebAssembly/WebAssemblyMemoryConstructor.h>
  8. #include <LibWeb/WebAssembly/WebAssemblyMemoryPrototype.h>
  9. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  10. namespace Web::Bindings {
  11. WebAssemblyMemoryConstructor::WebAssemblyMemoryConstructor(JS::Realm& realm)
  12. : NativeFunction(*realm.intrinsics().function_prototype())
  13. {
  14. }
  15. WebAssemblyMemoryConstructor::~WebAssemblyMemoryConstructor() = default;
  16. JS::ThrowCompletionOr<JS::Value> WebAssemblyMemoryConstructor::call()
  17. {
  18. return vm().throw_completion<JS::TypeError>(JS::ErrorType::ConstructorWithoutNew, "WebAssembly.Memory");
  19. }
  20. JS::ThrowCompletionOr<JS::Object*> WebAssemblyMemoryConstructor::construct(FunctionObject&)
  21. {
  22. auto& vm = this->vm();
  23. auto& realm = *vm.current_realm();
  24. auto descriptor = TRY(vm.argument(0).to_object(vm));
  25. auto initial_value = TRY(descriptor->get("initial"));
  26. auto maximum_value = TRY(descriptor->get("maximum"));
  27. if (!initial_value.is_number())
  28. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Number");
  29. u32 initial = TRY(initial_value.to_u32(vm));
  30. Optional<u32> maximum;
  31. if (!maximum_value.is_undefined())
  32. maximum = TRY(maximum_value.to_u32(vm));
  33. auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::MemoryType { Wasm::Limits { initial, maximum } });
  34. if (!address.has_value())
  35. return vm.throw_completion<JS::TypeError>("Wasm Memory allocation failed");
  36. return vm.heap().allocate<WebAssemblyMemoryObject>(realm, realm, *address);
  37. }
  38. void WebAssemblyMemoryConstructor::initialize(JS::Realm& realm)
  39. {
  40. auto& vm = this->vm();
  41. NativeFunction::initialize(realm);
  42. define_direct_property(vm.names.prototype, &Bindings::ensure_web_prototype<WebAssemblyMemoryPrototype>(realm, "WebAssemblyMemoryPrototype"), 0);
  43. define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  44. }
  45. }