WebAssemblyMemoryConstructor.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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()
  17. {
  18. }
  19. JS::ThrowCompletionOr<JS::Value> WebAssemblyMemoryConstructor::call()
  20. {
  21. return vm().throw_completion<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "WebAssembly.Memory");
  22. }
  23. JS::ThrowCompletionOr<JS::Object*> WebAssemblyMemoryConstructor::construct(FunctionObject&)
  24. {
  25. auto& vm = this->vm();
  26. auto& global_object = this->global_object();
  27. auto descriptor = TRY(vm.argument(0).to_object(global_object));
  28. auto initial_value = TRY(descriptor->get("initial"));
  29. auto maximum_value = TRY(descriptor->get("maximum"));
  30. if (!initial_value.is_number())
  31. return vm.throw_completion<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "Number");
  32. u32 initial = TRY(initial_value.to_u32(global_object));
  33. Optional<u32> maximum;
  34. if (!maximum_value.is_undefined())
  35. maximum = TRY(maximum_value.to_u32(global_object));
  36. auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::MemoryType { Wasm::Limits { initial, maximum } });
  37. if (!address.has_value())
  38. return vm.throw_completion<JS::TypeError>(global_object, "Wasm Memory allocation failed");
  39. if (!WebAssemblyObject::s_abstract_machine.store().get(*address)->grow(initial))
  40. return vm.throw_completion<JS::TypeError>(global_object, String::formatted("Wasm Memory grow failed: {}", initial));
  41. return vm.heap().allocate<WebAssemblyMemoryObject>(global_object, global_object, *address);
  42. }
  43. void WebAssemblyMemoryConstructor::initialize(JS::GlobalObject& global_object)
  44. {
  45. auto& vm = this->vm();
  46. auto& window = static_cast<WindowObject&>(global_object);
  47. NativeFunction::initialize(global_object);
  48. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<WebAssemblyMemoryPrototype>("WebAssemblyMemoryPrototype"), 0);
  49. define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
  50. }
  51. }