ArrayBuffer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*
  2. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. GC_DEFINE_ALLOCATOR(ArrayBuffer);
  12. ThrowCompletionOr<GC::Ref<ArrayBuffer>> ArrayBuffer::create(Realm& realm, size_t byte_length)
  13. {
  14. auto buffer = ByteBuffer::create_zeroed(byte_length);
  15. if (buffer.is_error())
  16. return realm.vm().throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, byte_length);
  17. return realm.create<ArrayBuffer>(buffer.release_value(), realm.intrinsics().array_buffer_prototype());
  18. }
  19. GC::Ref<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer buffer)
  20. {
  21. return realm.create<ArrayBuffer>(move(buffer), realm.intrinsics().array_buffer_prototype());
  22. }
  23. GC::Ref<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer* buffer)
  24. {
  25. return realm.create<ArrayBuffer>(buffer, realm.intrinsics().array_buffer_prototype());
  26. }
  27. ArrayBuffer::ArrayBuffer(ByteBuffer buffer, Object& prototype)
  28. : Object(ConstructWithPrototypeTag::Tag, prototype)
  29. , m_data_block(DataBlock { move(buffer), DataBlock::Shared::No })
  30. , m_detach_key(js_undefined())
  31. {
  32. }
  33. ArrayBuffer::ArrayBuffer(ByteBuffer* buffer, Object& prototype)
  34. : Object(ConstructWithPrototypeTag::Tag, prototype)
  35. , m_data_block(DataBlock { buffer, DataBlock::Shared::No })
  36. , m_detach_key(js_undefined())
  37. {
  38. }
  39. void ArrayBuffer::visit_edges(Cell::Visitor& visitor)
  40. {
  41. Base::visit_edges(visitor);
  42. visitor.visit(m_detach_key);
  43. }
  44. // 6.2.9.1 CreateByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createbytedatablock
  45. ThrowCompletionOr<DataBlock> create_byte_data_block(VM& vm, size_t size)
  46. {
  47. // 1. If size > 2^53 - 1, throw a RangeError exception.
  48. if (size > MAX_ARRAY_LIKE_INDEX)
  49. return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array buffer");
  50. // 2. Let db be a new Data Block value consisting of size bytes. If it is impossible to create such a Data Block, throw a RangeError exception.
  51. // 3. Set all of the bytes of db to 0.
  52. auto data_block = ByteBuffer::create_zeroed(size);
  53. if (data_block.is_error())
  54. return vm.throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, size);
  55. // 4. Return db.
  56. return DataBlock { data_block.release_value(), DataBlock::Shared::No };
  57. }
  58. // FIXME: The returned DataBlock is not shared in the sense that the standard specifies it.
  59. // 6.2.9.2 CreateSharedByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createsharedbytedatablock
  60. static ThrowCompletionOr<DataBlock> create_shared_byte_data_block(VM& vm, size_t size)
  61. {
  62. // 1. Let db be a new Shared Data Block value consisting of size bytes. If it is impossible to create such a Shared Data Block, throw a RangeError exception.
  63. auto data_block = ByteBuffer::create_zeroed(size);
  64. if (data_block.is_error())
  65. return vm.throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, size);
  66. // 2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  67. // 3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  68. // 4. Let zero be « 0 ».
  69. // 5. For each index i of db, do
  70. // a. Append WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero } to eventsRecord.[[EventList]].
  71. // 6. Return db.
  72. return DataBlock { data_block.release_value(), DataBlock::Shared::Yes };
  73. }
  74. // 6.2.9.3 CopyDataBlockBytes ( toBlock, toIndex, fromBlock, fromIndex, count ), https://tc39.es/ecma262/#sec-copydatablockbytes
  75. void copy_data_block_bytes(ByteBuffer& to_block, u64 to_index, ByteBuffer const& from_block, u64 from_index, u64 count)
  76. {
  77. // 1. Assert: fromBlock and toBlock are distinct values.
  78. VERIFY(&to_block != &from_block);
  79. // 2. Let fromSize be the number of bytes in fromBlock.
  80. auto from_size = from_block.size();
  81. // 3. Assert: fromIndex + count ≤ fromSize.
  82. VERIFY(from_index + count <= from_size);
  83. // 4. Let toSize be the number of bytes in toBlock.
  84. auto to_size = to_block.size();
  85. // 5. Assert: toIndex + count ≤ toSize.
  86. VERIFY(to_index + count <= to_size);
  87. // 6. Repeat, while count > 0,
  88. while (count > 0) {
  89. // FIXME: a. If fromBlock is a Shared Data Block, then
  90. // FIXME: i. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  91. // FIXME: ii. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  92. // FIXME: iii. Let bytes be a List whose sole element is a nondeterministically chosen byte value.
  93. // FIXME: iv. NOTE: In implementations, bytes is the result of a non-atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
  94. // FIXME: v. Let readEvent be ReadSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }.
  95. // FIXME: vi. Append readEvent to eventsRecord.[[EventList]].
  96. // FIXME: vii. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes } to execution.[[ChosenValues]].
  97. // FIXME: viii. If toBlock is a Shared Data Block, then
  98. // FIXME: 1. Append WriteSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes } to eventsRecord.[[EventList]].
  99. // FIXME: ix. Else,
  100. // FIXME: 1. Set toBlock[toIndex] to bytes[0].
  101. // FIXME: b. Else,
  102. // FIXME: i. Assert: toBlock is not a Shared Data Block.
  103. // ii. Set toBlock[toIndex] to fromBlock[fromIndex].
  104. to_block[to_index] = from_block[from_index];
  105. // c. Set toIndex to toIndex + 1.
  106. ++to_index;
  107. // d. Set fromIndex to fromIndex + 1.
  108. ++from_index;
  109. // e. Set count to count - 1.
  110. --count;
  111. }
  112. // 7. Return unused.
  113. }
  114. // 25.1.3.1 AllocateArrayBuffer ( constructor, byteLength [ , maxByteLength ] ), https://tc39.es/ecma262/#sec-allocatearraybuffer
  115. ThrowCompletionOr<ArrayBuffer*> allocate_array_buffer(VM& vm, FunctionObject& constructor, size_t byte_length, Optional<size_t> const& max_byte_length)
  116. {
  117. // 1. Let slots be « [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] ».
  118. // 2. If maxByteLength is present and maxByteLength is not empty, let allocatingResizableBuffer be true; otherwise let allocatingResizableBuffer be false.
  119. auto allocating_resizable_buffer = max_byte_length.has_value();
  120. // 3. If allocatingResizableBuffer is true, then
  121. if (allocating_resizable_buffer) {
  122. // a. If byteLength > maxByteLength, throw a RangeError exception.
  123. if (byte_length > *max_byte_length)
  124. return vm.throw_completion<RangeError>(ErrorType::ByteLengthExceedsMaxByteLength, byte_length, *max_byte_length);
  125. // b. Append [[ArrayBufferMaxByteLength]] to slots.
  126. }
  127. // 4. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%ArrayBuffer.prototype%", slots).
  128. auto obj = TRY(ordinary_create_from_constructor<ArrayBuffer>(vm, constructor, &Intrinsics::array_buffer_prototype, nullptr));
  129. // 5. Let block be ? CreateByteDataBlock(byteLength).
  130. auto block = TRY(create_byte_data_block(vm, byte_length));
  131. // 6. Set obj.[[ArrayBufferData]] to block.
  132. obj->set_data_block(move(block));
  133. // 7. Set obj.[[ArrayBufferByteLength]] to byteLength.
  134. // 8. If allocatingResizableBuffer is true, then
  135. if (allocating_resizable_buffer) {
  136. // a. If it is not possible to create a Data Block block consisting of maxByteLength bytes, throw a RangeError exception.
  137. // b. NOTE: Resizable ArrayBuffers are designed to be implementable with in-place growth. Implementations may throw if, for example, virtual memory cannot be reserved up front.
  138. if (auto result = obj->buffer().try_ensure_capacity(*max_byte_length); result.is_error())
  139. return vm.throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, *max_byte_length);
  140. // c. Set obj.[[ArrayBufferMaxByteLength]] to maxByteLength.
  141. obj->set_max_byte_length(*max_byte_length);
  142. }
  143. // 9. Return obj.
  144. return obj.ptr();
  145. }
  146. // 25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability ), https://tc39.es/ecma262/#sec-arraybuffercopyanddetach
  147. ThrowCompletionOr<ArrayBuffer*> array_buffer_copy_and_detach(VM& vm, ArrayBuffer& array_buffer, Value new_length, PreserveResizability preserve_resizability)
  148. {
  149. auto& realm = *vm.current_realm();
  150. // 1. Perform ? RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]).
  151. // 2. If IsSharedArrayBuffer(arrayBuffer) is true, throw a TypeError exception.
  152. if (array_buffer.is_shared_array_buffer())
  153. return vm.throw_completion<TypeError>(ErrorType::SharedArrayBuffer);
  154. // 3. If newLength is undefined, then
  155. // a. Let newByteLength be arrayBuffer.[[ArrayBufferByteLength]].
  156. // 4. Else,
  157. // a. Let newByteLength be ? ToIndex(newLength).
  158. auto new_byte_length = new_length.is_undefined() ? array_buffer.byte_length() : TRY(new_length.to_index(vm));
  159. // 5. If IsDetachedBuffer(arrayBuffer) is true, throw a TypeError exception.
  160. if (array_buffer.is_detached())
  161. return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
  162. Optional<size_t> new_max_byte_length;
  163. // 6. If preserveResizability is PRESERVE-RESIZABILITY and IsFixedLengthArrayBuffer(arrayBuffer) is false, then
  164. if (preserve_resizability == PreserveResizability::PreserveResizability && !array_buffer.is_fixed_length()) {
  165. // a. Let newMaxByteLength be arrayBuffer.[[ArrayBufferMaxByteLength]].
  166. new_max_byte_length = array_buffer.max_byte_length();
  167. }
  168. // 7. Else,
  169. else {
  170. // a. Let newMaxByteLength be EMPTY.
  171. }
  172. // 8. If arrayBuffer.[[ArrayBufferDetachKey]] is not undefined, throw a TypeError exception.
  173. if (!array_buffer.detach_key().is_undefined())
  174. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, array_buffer.detach_key(), js_undefined());
  175. // 9. Let newBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength).
  176. auto* new_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), new_byte_length, new_max_byte_length));
  177. // 10. Let copyLength be min(newByteLength, arrayBuffer.[[ArrayBufferByteLength]]).
  178. auto copy_length = min(new_byte_length, array_buffer.byte_length());
  179. // 11. Let fromBlock be arrayBuffer.[[ArrayBufferData]].
  180. // 12. Let toBlock be newBuffer.[[ArrayBufferData]].
  181. // 13. Perform CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength).
  182. // 14. NOTE: Neither creation of the new Data Block nor copying from the old Data Block are observable. Implementations may implement this method as a zero-copy move or a realloc.
  183. copy_data_block_bytes(new_buffer->buffer(), 0, array_buffer.buffer(), 0, copy_length);
  184. // 15. Perform ! DetachArrayBuffer(arrayBuffer).
  185. MUST(detach_array_buffer(vm, array_buffer));
  186. // 16. Return newBuffer.
  187. return new_buffer;
  188. }
  189. // 25.1.3.5 DetachArrayBuffer ( arrayBuffer [ , key ] ), https://tc39.es/ecma262/#sec-detacharraybuffer
  190. ThrowCompletionOr<void> detach_array_buffer(VM& vm, ArrayBuffer& array_buffer, Optional<Value> key)
  191. {
  192. // 1. Assert: IsSharedArrayBuffer(arrayBuffer) is false.
  193. VERIFY(!array_buffer.is_shared_array_buffer());
  194. // 2. If key is not present, set key to undefined.
  195. if (!key.has_value())
  196. key = js_undefined();
  197. // 3. If SameValue(arrayBuffer.[[ArrayBufferDetachKey]], key) is false, throw a TypeError exception.
  198. if (!same_value(array_buffer.detach_key(), *key))
  199. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, *key, array_buffer.detach_key());
  200. // 4. Set arrayBuffer.[[ArrayBufferData]] to null.
  201. // 5. Set arrayBuffer.[[ArrayBufferByteLength]] to 0.
  202. array_buffer.detach_buffer();
  203. // 6. Return unused.
  204. return {};
  205. }
  206. // 25.1.3.6 CloneArrayBuffer ( srcBuffer, srcByteOffset, srcLength, cloneConstructor ), https://tc39.es/ecma262/#sec-clonearraybuffer
  207. ThrowCompletionOr<ArrayBuffer*> clone_array_buffer(VM& vm, ArrayBuffer& source_buffer, size_t source_byte_offset, size_t source_length)
  208. {
  209. auto& realm = *vm.current_realm();
  210. // 1. Assert: IsDetachedBuffer(srcBuffer) is false.
  211. VERIFY(!source_buffer.is_detached());
  212. // 2. Let targetBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, srcLength).
  213. auto* target_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), source_length));
  214. // 3. Let srcBlock be srcBuffer.[[ArrayBufferData]].
  215. auto& source_block = source_buffer.buffer();
  216. // 4. Let targetBlock be targetBuffer.[[ArrayBufferData]].
  217. auto& target_block = target_buffer->buffer();
  218. // 5. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  219. copy_data_block_bytes(target_block, 0, source_block, source_byte_offset, source_length);
  220. // 6. Return targetBuffer.
  221. return target_buffer;
  222. }
  223. // 25.1.3.7 GetArrayBufferMaxByteLengthOption ( options ), https://tc39.es/ecma262/#sec-getarraybuffermaxbytelengthoption
  224. ThrowCompletionOr<Optional<size_t>> get_array_buffer_max_byte_length_option(VM& vm, Value options)
  225. {
  226. // 1. If options is not an Object, return empty.
  227. if (!options.is_object())
  228. return OptionalNone {};
  229. // 2. Let maxByteLength be ? Get(options, "maxByteLength").
  230. auto max_byte_length = TRY(options.as_object().get(vm.names.maxByteLength));
  231. // 3. If maxByteLength is undefined, return empty.
  232. if (max_byte_length.is_undefined())
  233. return OptionalNone {};
  234. // 4. Return ? ToIndex(maxByteLength).
  235. return TRY(max_byte_length.to_index(vm));
  236. }
  237. // 25.2.2.1 AllocateSharedArrayBuffer ( constructor, byteLength [ , maxByteLength ] ), https://tc39.es/ecma262/#sec-allocatesharedarraybuffer
  238. ThrowCompletionOr<GC::Ref<ArrayBuffer>> allocate_shared_array_buffer(VM& vm, FunctionObject& constructor, size_t byte_length)
  239. {
  240. // 1. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%SharedArrayBuffer.prototype%", « [[ArrayBufferData]], [[ArrayBufferByteLength]] »).
  241. auto obj = TRY(ordinary_create_from_constructor<ArrayBuffer>(vm, constructor, &Intrinsics::shared_array_buffer_prototype, nullptr));
  242. // 2. Let block be ? CreateSharedByteDataBlock(byteLength).
  243. auto block = TRY(create_shared_byte_data_block(vm, byte_length));
  244. // 3. Set obj.[[ArrayBufferData]] to block.
  245. // 4. Set obj.[[ArrayBufferByteLength]] to byteLength.
  246. obj->set_data_block(move(block));
  247. // 5. Return obj.
  248. return obj;
  249. }
  250. }