ArrayBuffer.cpp 11 KB

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