ArrayBuffer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. JS_DEFINE_ALLOCATOR(ArrayBuffer);
  12. ThrowCompletionOr<NonnullGCPtr<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.heap().allocate<ArrayBuffer>(realm, buffer.release_value(), realm.intrinsics().array_buffer_prototype());
  18. }
  19. NonnullGCPtr<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer buffer)
  20. {
  21. return realm.heap().allocate<ArrayBuffer>(realm, move(buffer), realm.intrinsics().array_buffer_prototype());
  22. }
  23. NonnullGCPtr<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer* buffer)
  24. {
  25. return realm.heap().allocate<ArrayBuffer>(realm, 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.4 DetachArrayBuffer ( arrayBuffer [ , key ] ), https://tc39.es/ecma262/#sec-detacharraybuffer
  147. ThrowCompletionOr<void> detach_array_buffer(VM& vm, ArrayBuffer& array_buffer, Optional<Value> key)
  148. {
  149. // 1. Assert: IsSharedArrayBuffer(arrayBuffer) is false.
  150. VERIFY(!array_buffer.is_shared_array_buffer());
  151. // 2. If key is not present, set key to undefined.
  152. if (!key.has_value())
  153. key = js_undefined();
  154. // 3. If SameValue(arrayBuffer.[[ArrayBufferDetachKey]], key) is false, throw a TypeError exception.
  155. if (!same_value(array_buffer.detach_key(), *key))
  156. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, *key, array_buffer.detach_key());
  157. // 4. Set arrayBuffer.[[ArrayBufferData]] to null.
  158. // 5. Set arrayBuffer.[[ArrayBufferByteLength]] to 0.
  159. array_buffer.detach_buffer();
  160. // 6. Return unused.
  161. return {};
  162. }
  163. // 25.1.3.5 CloneArrayBuffer ( srcBuffer, srcByteOffset, srcLength, cloneConstructor ), https://tc39.es/ecma262/#sec-clonearraybuffer
  164. ThrowCompletionOr<ArrayBuffer*> clone_array_buffer(VM& vm, ArrayBuffer& source_buffer, size_t source_byte_offset, size_t source_length)
  165. {
  166. auto& realm = *vm.current_realm();
  167. // 1. Assert: IsDetachedBuffer(srcBuffer) is false.
  168. VERIFY(!source_buffer.is_detached());
  169. // 2. Let targetBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, srcLength).
  170. auto* target_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), source_length));
  171. // 3. Let srcBlock be srcBuffer.[[ArrayBufferData]].
  172. auto& source_block = source_buffer.buffer();
  173. // 4. Let targetBlock be targetBuffer.[[ArrayBufferData]].
  174. auto& target_block = target_buffer->buffer();
  175. // 5. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  176. copy_data_block_bytes(target_block, 0, source_block, source_byte_offset, source_length);
  177. // 6. Return targetBuffer.
  178. return target_buffer;
  179. }
  180. // 25.1.3.6 GetArrayBufferMaxByteLengthOption ( options ), https://tc39.es/ecma262/#sec-getarraybuffermaxbytelengthoption
  181. ThrowCompletionOr<Optional<size_t>> get_array_buffer_max_byte_length_option(VM& vm, Value options)
  182. {
  183. // 1. If options is not an Object, return empty.
  184. if (!options.is_object())
  185. return OptionalNone {};
  186. // 2. Let maxByteLength be ? Get(options, "maxByteLength").
  187. auto max_byte_length = TRY(options.as_object().get(vm.names.maxByteLength));
  188. // 3. If maxByteLength is undefined, return empty.
  189. if (max_byte_length.is_undefined())
  190. return OptionalNone {};
  191. // 4. Return ? ToIndex(maxByteLength).
  192. return TRY(max_byte_length.to_index(vm));
  193. }
  194. // 25.1.2.14 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability ), https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
  195. ThrowCompletionOr<ArrayBuffer*> array_buffer_copy_and_detach(VM& vm, ArrayBuffer& array_buffer, Value new_length, PreserveResizability preserve_resizability)
  196. {
  197. auto& realm = *vm.current_realm();
  198. // 1. Perform ? RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]).
  199. // 2. If IsSharedArrayBuffer(arrayBuffer) is true, throw a TypeError exception.
  200. if (array_buffer.is_shared_array_buffer())
  201. return vm.throw_completion<TypeError>(ErrorType::SharedArrayBuffer);
  202. // 3. If newLength is undefined, then
  203. // a. Let newByteLength be arrayBuffer.[[ArrayBufferByteLength]].
  204. // 4. Else,
  205. // a. Let newByteLength be ? ToIndex(newLength).
  206. auto new_byte_length = new_length.is_undefined() ? array_buffer.byte_length() : TRY(new_length.to_index(vm));
  207. // 5. If IsDetachedBuffer(arrayBuffer) is true, throw a TypeError exception.
  208. if (array_buffer.is_detached())
  209. return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
  210. Optional<size_t> new_max_byte_length;
  211. // 6. If preserveResizability is preserve-resizability and IsResizableArrayBuffer(arrayBuffer) is true, then
  212. // FIXME: The ArrayBuffer transfer spec is a bit out-of-date. IsResizableArrayBuffer no longer exists, we now have IsFixedLengthArrayBuffer.
  213. if (preserve_resizability == PreserveResizability::PreserveResizability && !array_buffer.is_fixed_length()) {
  214. // a. Let newMaxByteLength be arrayBuffer.[[ArrayBufferMaxByteLength]].
  215. new_max_byte_length = array_buffer.max_byte_length();
  216. }
  217. // 7. Else,
  218. else {
  219. // a. Let newMaxByteLength be empty.
  220. }
  221. // 8. If arrayBuffer.[[ArrayBufferDetachKey]] is not undefined, throw a TypeError exception.
  222. if (!array_buffer.detach_key().is_undefined())
  223. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, array_buffer.detach_key(), js_undefined());
  224. // 9. Let newBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength).
  225. auto* new_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), new_byte_length, new_max_byte_length));
  226. // 10. Let copyLength be min(newByteLength, arrayBuffer.[[ArrayBufferByteLength]]).
  227. auto copy_length = min(new_byte_length, array_buffer.byte_length());
  228. // 11. Let fromBlock be arrayBuffer.[[ArrayBufferData]].
  229. // 12. Let toBlock be newBuffer.[[ArrayBufferData]].
  230. // 13. Perform CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength).
  231. // 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.
  232. copy_data_block_bytes(new_buffer->buffer(), 0, array_buffer.buffer(), 0, copy_length);
  233. // 15. Perform ! DetachArrayBuffer(arrayBuffer).
  234. TRY(detach_array_buffer(vm, array_buffer));
  235. // 16. Return newBuffer.
  236. return new_buffer;
  237. }
  238. // 25.2.2.1 AllocateSharedArrayBuffer ( constructor, byteLength [ , maxByteLength ] ), https://tc39.es/ecma262/#sec-allocatesharedarraybuffer
  239. ThrowCompletionOr<NonnullGCPtr<ArrayBuffer>> allocate_shared_array_buffer(VM& vm, FunctionObject& constructor, size_t byte_length)
  240. {
  241. // 1. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%SharedArrayBuffer.prototype%", « [[ArrayBufferData]], [[ArrayBufferByteLength]] »).
  242. auto obj = TRY(ordinary_create_from_constructor<ArrayBuffer>(vm, constructor, &Intrinsics::shared_array_buffer_prototype, nullptr));
  243. // 2. Let block be ? CreateSharedByteDataBlock(byteLength).
  244. auto block = TRY(create_shared_byte_data_block(vm, byte_length));
  245. // 3. Set obj.[[ArrayBufferData]] to block.
  246. // 4. Set obj.[[ArrayBufferByteLength]] to byteLength.
  247. obj->set_data_block(move(block));
  248. // 5. Return obj.
  249. return obj;
  250. }
  251. }