WebAssemblyMemoryConstructor.cpp 2.4 KB

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