WebAssemblyMemoryConstructor.cpp 2.4 KB

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