WebAssemblyMemoryConstructor.cpp 2.5 KB

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