WebAssemblyMemoryConstructor.cpp 2.3 KB

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