WebAssemblyMemoryConstructor.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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::NonnullGCPtr<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"sv);
  36. return MUST_OR_THROW_OOM(vm.heap().allocate<WebAssemblyMemoryObject>(realm, realm, *address));
  37. }
  38. JS::ThrowCompletionOr<void> WebAssemblyMemoryConstructor::initialize(JS::Realm& realm)
  39. {
  40. auto& vm = this->vm();
  41. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  42. define_direct_property(vm.names.prototype, &Bindings::ensure_web_prototype<WebAssemblyMemoryPrototype>(realm, "WebAssembly.Memory"), 0);
  43. define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  44. return {};
  45. }
  46. }