ArrayBuffer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. ThrowCompletionOr<NonnullGCPtr<ArrayBuffer>> ArrayBuffer::create(Realm& realm, size_t byte_length)
  12. {
  13. auto buffer = ByteBuffer::create_zeroed(byte_length);
  14. if (buffer.is_error())
  15. return realm.vm().throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, byte_length);
  16. return realm.heap().allocate<ArrayBuffer>(realm, buffer.release_value(), realm.intrinsics().array_buffer_prototype());
  17. }
  18. NonnullGCPtr<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer buffer)
  19. {
  20. return realm.heap().allocate<ArrayBuffer>(realm, move(buffer), realm.intrinsics().array_buffer_prototype());
  21. }
  22. NonnullGCPtr<ArrayBuffer> ArrayBuffer::create(Realm& realm, ByteBuffer* buffer)
  23. {
  24. return realm.heap().allocate<ArrayBuffer>(realm, buffer, realm.intrinsics().array_buffer_prototype());
  25. }
  26. ArrayBuffer::ArrayBuffer(ByteBuffer buffer, Object& prototype)
  27. : Object(ConstructWithPrototypeTag::Tag, prototype)
  28. , m_data_block(DataBlock { move(buffer), DataBlock::Shared::No })
  29. , m_detach_key(js_undefined())
  30. {
  31. }
  32. ArrayBuffer::ArrayBuffer(ByteBuffer* buffer, Object& prototype)
  33. : Object(ConstructWithPrototypeTag::Tag, prototype)
  34. , m_data_block(DataBlock { buffer, DataBlock::Shared::No })
  35. , m_detach_key(js_undefined())
  36. {
  37. }
  38. void ArrayBuffer::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. visitor.visit(m_detach_key);
  42. }
  43. // 6.2.9.1 CreateByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createbytedatablock
  44. ThrowCompletionOr<DataBlock> create_byte_data_block(VM& vm, size_t size)
  45. {
  46. // 1. If size > 2^53 - 1, throw a RangeError exception.
  47. if (size > MAX_ARRAY_LIKE_INDEX)
  48. return vm.throw_completion<RangeError>(ErrorType::InvalidLength, "array buffer");
  49. // 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.
  50. // 3. Set all of the bytes of db to 0.
  51. auto data_block = ByteBuffer::create_zeroed(size);
  52. if (data_block.is_error())
  53. return vm.throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, size);
  54. // 4. Return db.
  55. return DataBlock { data_block.release_value(), DataBlock::Shared::No };
  56. }
  57. // FIXME: The returned DataBlock is not shared in the sense that the standard specifies it.
  58. // 6.2.9.2 CreateSharedByteDataBlock ( size ), https://tc39.es/ecma262/#sec-createsharedbytedatablock
  59. static ThrowCompletionOr<DataBlock> create_shared_byte_data_block(VM& vm, size_t size)
  60. {
  61. // 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.
  62. auto data_block = ByteBuffer::create_zeroed(size);
  63. if (data_block.is_error())
  64. return vm.throw_completion<RangeError>(ErrorType::NotEnoughMemoryToAllocate, size);
  65. // 2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  66. // 3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  67. // 4. Let zero be « 0 ».
  68. // 5. For each index i of db, do
  69. // a. Append WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero } to eventsRecord.[[EventList]].
  70. // 6. Return db.
  71. return DataBlock { data_block.release_value(), DataBlock::Shared::Yes };
  72. }
  73. // 6.2.9.3 CopyDataBlockBytes ( toBlock, toIndex, fromBlock, fromIndex, count ), https://tc39.es/ecma262/#sec-copydatablockbytes
  74. void copy_data_block_bytes(ByteBuffer& to_block, u64 to_index, ByteBuffer const& from_block, u64 from_index, u64 count)
  75. {
  76. // 1. Assert: fromBlock and toBlock are distinct values.
  77. VERIFY(&to_block != &from_block);
  78. // 2. Let fromSize be the number of bytes in fromBlock.
  79. auto from_size = from_block.size();
  80. // 3. Assert: fromIndex + count ≤ fromSize.
  81. VERIFY(from_index + count <= from_size);
  82. // 4. Let toSize be the number of bytes in toBlock.
  83. auto to_size = to_block.size();
  84. // 5. Assert: toIndex + count ≤ toSize.
  85. VERIFY(to_index + count <= to_size);
  86. // 6. Repeat, while count > 0,
  87. while (count > 0) {
  88. // FIXME: a. If fromBlock is a Shared Data Block, then
  89. // FIXME: i. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  90. // FIXME: ii. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  91. // FIXME: iii. Let bytes be a List whose sole element is a nondeterministically chosen byte value.
  92. // 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.
  93. // FIXME: v. Let readEvent be ReadSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }.
  94. // FIXME: vi. Append readEvent to eventsRecord.[[EventList]].
  95. // FIXME: vii. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes } to execution.[[ChosenValues]].
  96. // FIXME: viii. If toBlock is a Shared Data Block, then
  97. // FIXME: 1. Append WriteSharedMemory { [[Order]]: Unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes } to eventsRecord.[[EventList]].
  98. // FIXME: ix. Else,
  99. // FIXME: 1. Set toBlock[toIndex] to bytes[0].
  100. // FIXME: b. Else,
  101. // FIXME: i. Assert: toBlock is not a Shared Data Block.
  102. // ii. Set toBlock[toIndex] to fromBlock[fromIndex].
  103. to_block[to_index] = from_block[from_index];
  104. // c. Set toIndex to toIndex + 1.
  105. ++to_index;
  106. // d. Set fromIndex to fromIndex + 1.
  107. ++from_index;
  108. // e. Set count to count - 1.
  109. --count;
  110. }
  111. // 7. Return unused.
  112. }
  113. // 25.1.2.1 AllocateArrayBuffer ( constructor, byteLength ), https://tc39.es/ecma262/#sec-allocatearraybuffer
  114. ThrowCompletionOr<ArrayBuffer*> allocate_array_buffer(VM& vm, FunctionObject& constructor, size_t byte_length)
  115. {
  116. // 1. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%ArrayBuffer.prototype%", « [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] »).
  117. auto obj = TRY(ordinary_create_from_constructor<ArrayBuffer>(vm, constructor, &Intrinsics::array_buffer_prototype, nullptr));
  118. // 2. Let block be ? CreateByteDataBlock(byteLength).
  119. auto block = TRY(create_byte_data_block(vm, byte_length));
  120. // 3. Set obj.[[ArrayBufferData]] to block.
  121. obj->set_data_block(move(block));
  122. // 4. Set obj.[[ArrayBufferByteLength]] to byteLength.
  123. // 5. Return obj.
  124. return obj.ptr();
  125. }
  126. // 25.1.2.3 DetachArrayBuffer ( arrayBuffer [ , key ] ), https://tc39.es/ecma262/#sec-detacharraybuffer
  127. ThrowCompletionOr<void> detach_array_buffer(VM& vm, ArrayBuffer& array_buffer, Optional<Value> key)
  128. {
  129. // 1. Assert: IsSharedArrayBuffer(arrayBuffer) is false.
  130. // FIXME: Check for shared buffer
  131. // 2. If key is not present, set key to undefined.
  132. if (!key.has_value())
  133. key = js_undefined();
  134. // 3. If SameValue(arrayBuffer.[[ArrayBufferDetachKey]], key) is false, throw a TypeError exception.
  135. if (!same_value(array_buffer.detach_key(), *key))
  136. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, *key, array_buffer.detach_key());
  137. // 4. Set arrayBuffer.[[ArrayBufferData]] to null.
  138. // 5. Set arrayBuffer.[[ArrayBufferByteLength]] to 0.
  139. array_buffer.detach_buffer();
  140. // 6. Return unused.
  141. return {};
  142. }
  143. // 25.1.2.4 CloneArrayBuffer ( srcBuffer, srcByteOffset, srcLength, cloneConstructor ), https://tc39.es/ecma262/#sec-clonearraybuffer
  144. ThrowCompletionOr<ArrayBuffer*> clone_array_buffer(VM& vm, ArrayBuffer& source_buffer, size_t source_byte_offset, size_t source_length)
  145. {
  146. auto& realm = *vm.current_realm();
  147. // 1. Assert: IsDetachedBuffer(srcBuffer) is false.
  148. VERIFY(!source_buffer.is_detached());
  149. // 2. Let targetBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, srcLength).
  150. auto* target_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), source_length));
  151. // 3. Let srcBlock be srcBuffer.[[ArrayBufferData]].
  152. auto& source_block = source_buffer.buffer();
  153. // 4. Let targetBlock be targetBuffer.[[ArrayBufferData]].
  154. auto& target_block = target_buffer->buffer();
  155. // 5. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  156. copy_data_block_bytes(target_block, 0, source_block, source_byte_offset, source_length);
  157. // 6. Return targetBuffer.
  158. return target_buffer;
  159. }
  160. // 25.1.2.14 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability ), https://tc39.es/proposal-arraybuffer-transfer/#sec-arraybuffer.prototype.transfertofixedlength
  161. ThrowCompletionOr<ArrayBuffer*> array_buffer_copy_and_detach(VM& vm, ArrayBuffer& array_buffer, Value new_length, PreserveResizability)
  162. {
  163. auto& realm = *vm.current_realm();
  164. // 1. Perform ? RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]).
  165. // FIXME: 2. If IsSharedArrayBuffer(arrayBuffer) is true, throw a TypeError exception.
  166. // 3. If newLength is undefined, then
  167. // a. Let newByteLength be arrayBuffer.[[ArrayBufferByteLength]].
  168. // 4. Else,
  169. // a. Let newByteLength be ? ToIndex(newLength).
  170. auto new_byte_length = new_length.is_undefined() ? array_buffer.byte_length() : TRY(new_length.to_index(vm));
  171. // 5. If IsDetachedBuffer(arrayBuffer) is true, throw a TypeError exception.
  172. if (array_buffer.is_detached())
  173. return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
  174. // FIXME: 6. If preserveResizability is preserve-resizability and IsResizableArrayBuffer(arrayBuffer) is true, then
  175. // a. Let newMaxByteLength be arrayBuffer.[[ArrayBufferMaxByteLength]].
  176. // 7. Else,
  177. // a. Let newMaxByteLength be empty.
  178. // 8. If arrayBuffer.[[ArrayBufferDetachKey]] is not undefined, throw a TypeError exception.
  179. if (!array_buffer.detach_key().is_undefined())
  180. return vm.throw_completion<TypeError>(ErrorType::DetachKeyMismatch, array_buffer.detach_key(), js_undefined());
  181. // 9. Let newBuffer be ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, FIXME: newMaxByteLength).
  182. auto* new_buffer = TRY(allocate_array_buffer(vm, realm.intrinsics().array_buffer_constructor(), new_byte_length));
  183. // 10. Let copyLength be min(newByteLength, arrayBuffer.[[ArrayBufferByteLength]]).
  184. auto copy_length = min(new_byte_length, array_buffer.byte_length());
  185. // 11. Let fromBlock be arrayBuffer.[[ArrayBufferData]].
  186. // 12. Let toBlock be newBuffer.[[ArrayBufferData]].
  187. // 13. Perform CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength).
  188. // 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.
  189. copy_data_block_bytes(new_buffer->buffer(), 0, array_buffer.buffer(), 0, copy_length);
  190. // 15. Perform ! DetachArrayBuffer(arrayBuffer).
  191. TRY(detach_array_buffer(vm, array_buffer));
  192. // 16. Return newBuffer.
  193. return new_buffer;
  194. }
  195. // 25.2.1.1 AllocateSharedArrayBuffer ( constructor, byteLength ), https://tc39.es/ecma262/#sec-allocatesharedarraybuffer
  196. ThrowCompletionOr<NonnullGCPtr<ArrayBuffer>> allocate_shared_array_buffer(VM& vm, FunctionObject& constructor, size_t byte_length)
  197. {
  198. // 1. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%SharedArrayBuffer.prototype%", « [[ArrayBufferData]], [[ArrayBufferByteLength]] »).
  199. auto obj = TRY(ordinary_create_from_constructor<ArrayBuffer>(vm, constructor, &Intrinsics::shared_array_buffer_prototype, nullptr));
  200. // 2. Let block be ? CreateSharedByteDataBlock(byteLength).
  201. auto block = TRY(create_shared_byte_data_block(vm, byte_length));
  202. // 3. Set obj.[[ArrayBufferData]] to block.
  203. // 4. Set obj.[[ArrayBufferByteLength]] to byteLength.
  204. obj->set_data_block(move(block));
  205. // 5. Return obj.
  206. return obj;
  207. }
  208. }