ArrayBuffer.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Function.h>
  9. #include <AK/Variant.h>
  10. #include <LibJS/Runtime/BigInt.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Object.h>
  14. namespace JS {
  15. struct ClampedU8 {
  16. };
  17. // 25.1.1 Notation (read-modify-write modification function), https://tc39.es/ecma262/#sec-arraybuffer-notation
  18. using ReadWriteModifyFunction = Function<ByteBuffer(ByteBuffer, ByteBuffer)>;
  19. enum class PreserveResizability {
  20. FixedLength,
  21. PreserveResizability
  22. };
  23. // 6.2.9 Data Blocks, https://tc39.es/ecma262/#sec-data-blocks
  24. struct DataBlock {
  25. enum class Shared {
  26. No,
  27. Yes,
  28. };
  29. ByteBuffer& buffer()
  30. {
  31. ByteBuffer* ptr { nullptr };
  32. byte_buffer.visit([&](Empty) { VERIFY_NOT_REACHED(); }, [&](auto* pointer) { ptr = pointer; }, [&](auto& value) { ptr = &value; });
  33. return *ptr;
  34. }
  35. ByteBuffer const& buffer() const { return const_cast<DataBlock*>(this)->buffer(); }
  36. size_t size() const
  37. {
  38. return byte_buffer.visit(
  39. [](Empty) -> size_t { return 0u; },
  40. [](ByteBuffer const& buffer) { return buffer.size(); },
  41. [](ByteBuffer const* buffer) { return buffer->size(); });
  42. }
  43. Variant<Empty, ByteBuffer, ByteBuffer*> byte_buffer;
  44. Shared is_shared = { Shared::No };
  45. };
  46. class ArrayBuffer : public Object {
  47. JS_OBJECT(ArrayBuffer, Object);
  48. JS_DECLARE_ALLOCATOR(ArrayBuffer);
  49. public:
  50. static ThrowCompletionOr<NonnullGCPtr<ArrayBuffer>> create(Realm&, size_t);
  51. static NonnullGCPtr<ArrayBuffer> create(Realm&, ByteBuffer);
  52. static NonnullGCPtr<ArrayBuffer> create(Realm&, ByteBuffer*);
  53. virtual ~ArrayBuffer() override = default;
  54. size_t byte_length() const { return m_data_block.size(); }
  55. // [[ArrayBufferData]]
  56. ByteBuffer& buffer() { return m_data_block.buffer(); }
  57. ByteBuffer const& buffer() const { return m_data_block.buffer(); }
  58. // [[ArrayBufferMaxByteLength]]
  59. size_t max_byte_length() const { return m_max_byte_length.value(); }
  60. void set_max_byte_length(size_t max_byte_length) { m_max_byte_length = max_byte_length; }
  61. // Used by allocate_array_buffer() to attach the data block after construction
  62. void set_data_block(DataBlock block) { m_data_block = move(block); }
  63. Value detach_key() const { return m_detach_key; }
  64. void set_detach_key(Value detach_key) { m_detach_key = detach_key; }
  65. void detach_buffer() { m_data_block.byte_buffer = Empty {}; }
  66. // 25.1.3.3 IsDetachedBuffer ( arrayBuffer ), https://tc39.es/ecma262/#sec-isdetachedbuffer
  67. bool is_detached() const
  68. {
  69. // 1. If arrayBuffer.[[ArrayBufferData]] is null, return true.
  70. if (m_data_block.byte_buffer.has<Empty>())
  71. return true;
  72. // 2. Return false.
  73. return false;
  74. }
  75. // 25.1.3.8 IsFixedLengthArrayBuffer ( arrayBuffer ), https://tc39.es/ecma262/#sec-isfixedlengtharraybuffer
  76. bool is_fixed_length() const
  77. {
  78. // 1. If arrayBuffer has an [[ArrayBufferMaxByteLength]] internal slot, return false.
  79. if (m_max_byte_length.has_value())
  80. return false;
  81. // 2. Return true.
  82. return true;
  83. }
  84. // 25.2.2.2 IsSharedArrayBuffer ( obj ), https://tc39.es/ecma262/#sec-issharedarraybuffer
  85. bool is_shared_array_buffer() const
  86. {
  87. // 1. Let bufferData be obj.[[ArrayBufferData]].
  88. // 2. If bufferData is null, return false.
  89. if (m_data_block.byte_buffer.has<Empty>())
  90. return false;
  91. // 3. If bufferData is a Data Block, return false.
  92. if (m_data_block.is_shared == DataBlock::Shared::No)
  93. return false;
  94. // 4. Assert: bufferData is a Shared Data Block.
  95. VERIFY(m_data_block.is_shared == DataBlock::Shared::Yes);
  96. // 5. Return true.
  97. return true;
  98. }
  99. enum Order {
  100. SeqCst,
  101. Unordered
  102. };
  103. template<typename type>
  104. Value get_value(size_t byte_index, bool is_typed_array, Order, bool is_little_endian = true);
  105. template<typename type>
  106. void set_value(size_t byte_index, Value value, bool is_typed_array, Order, bool is_little_endian = true);
  107. template<typename T>
  108. Value get_modify_set_value(size_t byte_index, Value value, ReadWriteModifyFunction operation, bool is_little_endian = true);
  109. private:
  110. ArrayBuffer(ByteBuffer buffer, Object& prototype);
  111. ArrayBuffer(ByteBuffer* buffer, Object& prototype);
  112. virtual void visit_edges(Visitor&) override;
  113. DataBlock m_data_block;
  114. Optional<size_t> m_max_byte_length;
  115. // The various detach related members of ArrayBuffer are not used by any ECMA262 functionality,
  116. // but are required to be available for the use of various harnesses like the Test262 test runner.
  117. Value m_detach_key;
  118. };
  119. ThrowCompletionOr<DataBlock> create_byte_data_block(VM& vm, size_t size);
  120. void copy_data_block_bytes(ByteBuffer& to_block, u64 to_index, ByteBuffer const& from_block, u64 from_index, u64 count);
  121. ThrowCompletionOr<ArrayBuffer*> allocate_array_buffer(VM&, FunctionObject& constructor, size_t byte_length, Optional<size_t> const& max_byte_length = {});
  122. ThrowCompletionOr<void> detach_array_buffer(VM&, ArrayBuffer& array_buffer, Optional<Value> key = {});
  123. ThrowCompletionOr<Optional<size_t>> get_array_buffer_max_byte_length_option(VM&, Value options);
  124. ThrowCompletionOr<ArrayBuffer*> clone_array_buffer(VM&, ArrayBuffer& source_buffer, size_t source_byte_offset, size_t source_length);
  125. ThrowCompletionOr<ArrayBuffer*> array_buffer_copy_and_detach(VM&, ArrayBuffer& array_buffer, Value new_length, PreserveResizability preserve_resizability);
  126. ThrowCompletionOr<NonnullGCPtr<ArrayBuffer>> allocate_shared_array_buffer(VM&, FunctionObject& constructor, size_t byte_length);
  127. // 25.1.3.2 ArrayBufferByteLength ( arrayBuffer, order ), https://tc39.es/ecma262/#sec-arraybufferbytelength
  128. inline size_t array_buffer_byte_length(ArrayBuffer const& array_buffer, ArrayBuffer::Order)
  129. {
  130. // FIXME: 1. If IsSharedArrayBuffer(arrayBuffer) is true and arrayBuffer has an [[ArrayBufferByteLengthData]] internal slot, then
  131. // FIXME: a. Let bufferByteLengthBlock be arrayBuffer.[[ArrayBufferByteLengthData]].
  132. // FIXME: b. Let rawLength be GetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, biguint64, true, order).
  133. // FIXME: c. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  134. // FIXME: d. Return ℝ(RawBytesToNumeric(biguint64, rawLength, isLittleEndian)).
  135. // 2. Assert: IsDetachedBuffer(arrayBuffer) is false.
  136. VERIFY(!array_buffer.is_detached());
  137. // 3. Return arrayBuffer.[[ArrayBufferByteLength]].
  138. return array_buffer.byte_length();
  139. }
  140. // 25.1.3.13 RawBytesToNumeric ( type, rawBytes, isLittleEndian ), https://tc39.es/ecma262/#sec-rawbytestonumeric
  141. template<typename T>
  142. static Value raw_bytes_to_numeric(VM& vm, Bytes raw_value, bool is_little_endian)
  143. {
  144. // 1. Let elementSize be the Element Size value specified in Table 70 for Element Type type.
  145. // NOTE: Used in step 6, but not needed with our implementation of that step.
  146. // 2. If isLittleEndian is false, reverse the order of the elements of rawBytes.
  147. if (!is_little_endian) {
  148. VERIFY(raw_value.size() % 2 == 0);
  149. for (size_t i = 0; i < raw_value.size() / 2; ++i)
  150. swap(raw_value[i], raw_value[raw_value.size() - 1 - i]);
  151. }
  152. // 3. If type is Float32, then
  153. using UnderlyingBufferDataType = Conditional<IsSame<ClampedU8, T>, u8, T>;
  154. if constexpr (IsSame<UnderlyingBufferDataType, float>) {
  155. // a. Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary32 value.
  156. float value;
  157. raw_value.copy_to({ &value, sizeof(float) });
  158. // b. If value is an IEEE 754-2019 binary32 NaN value, return the NaN Number value.
  159. if (isnan(value))
  160. return js_nan();
  161. // c. Return the Number value that corresponds to value.
  162. return Value(value);
  163. }
  164. // 4. If type is Float64, then
  165. if constexpr (IsSame<UnderlyingBufferDataType, double>) {
  166. // a. Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary64 value.
  167. double value;
  168. raw_value.copy_to({ &value, sizeof(double) });
  169. // b. If value is an IEEE 754-2019 binary64 NaN value, return the NaN Number value.
  170. if (isnan(value))
  171. return js_nan();
  172. // c. Return the Number value that corresponds to value.
  173. return Value(value);
  174. }
  175. // NOTE: Not in spec, sanity check for steps below.
  176. if constexpr (!IsIntegral<UnderlyingBufferDataType>)
  177. VERIFY_NOT_REACHED();
  178. // 5. If IsUnsignedElementType(type) is true, then
  179. // a. Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.
  180. // 6. Else,
  181. // a. Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian two's complement number of bit length elementSize × 8.
  182. //
  183. // NOTE: The signed/unsigned logic above is implemented in step 7 by the IsSigned<> check, and in step 8 by JS::Value constructor overloads.
  184. UnderlyingBufferDataType int_value = 0;
  185. raw_value.copy_to({ &int_value, sizeof(UnderlyingBufferDataType) });
  186. // 7. If IsBigIntElementType(type) is true, return the BigInt value that corresponds to intValue.
  187. if constexpr (sizeof(UnderlyingBufferDataType) == 8) {
  188. if constexpr (IsSigned<UnderlyingBufferDataType>) {
  189. static_assert(IsSame<UnderlyingBufferDataType, i64>);
  190. return BigInt::create(vm, Crypto::SignedBigInteger { int_value });
  191. } else {
  192. static_assert(IsOneOf<UnderlyingBufferDataType, u64, double>);
  193. return BigInt::create(vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger { int_value } });
  194. }
  195. }
  196. // 8. Otherwise, return the Number value that corresponds to intValue.
  197. else {
  198. return Value(int_value);
  199. }
  200. }
  201. // 25.1.3.15 GetValueFromBuffer ( arrayBuffer, byteIndex, type, isTypedArray, order [ , isLittleEndian ] ), https://tc39.es/ecma262/#sec-getvaluefrombuffer
  202. template<typename T>
  203. Value ArrayBuffer::get_value(size_t byte_index, [[maybe_unused]] bool is_typed_array, Order, bool is_little_endian)
  204. {
  205. auto& vm = this->vm();
  206. // 1. Assert: IsDetachedBuffer(arrayBuffer) is false.
  207. VERIFY(!is_detached());
  208. // 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
  209. VERIFY(m_data_block.buffer().bytes().slice(byte_index).size() >= sizeof(T));
  210. // 3. Let block be arrayBuffer.[[ArrayBufferData]].
  211. auto& block = m_data_block.buffer();
  212. // 4. Let elementSize be the Element Size value specified in Table 70 for Element Type type.
  213. auto element_size = sizeof(T);
  214. AK::Array<u8, sizeof(T)> raw_value {};
  215. // FIXME: 5. If IsSharedArrayBuffer(arrayBuffer) is true, then
  216. if (false) {
  217. // FIXME: a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  218. // FIXME: b. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  219. // FIXME: c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  220. // FIXME: d. Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.
  221. // FIXME: e. NOTE: In implementations, rawValue is the result of a non-atomic or 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.
  222. // FIXME: f. Let readEvent be ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
  223. // FIXME: g. Append readEvent to eventsRecord.[[EventList]].
  224. // FIXME: h. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
  225. }
  226. // 6. Else,
  227. else {
  228. // a. Let rawValue be a List whose elements are bytes from block at indices in the interval from byteIndex (inclusive) to byteIndex + elementSize (exclusive).
  229. block.bytes().slice(byte_index, element_size).copy_to(raw_value);
  230. }
  231. // 7. Assert: The number of elements in rawValue is elementSize.
  232. VERIFY(raw_value.size() == element_size);
  233. // 8. If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  234. // NOTE: Done by default parameter at declaration of this function.
  235. // 9. Return RawBytesToNumeric(type, rawValue, isLittleEndian).
  236. return raw_bytes_to_numeric<T>(vm, raw_value, is_little_endian);
  237. }
  238. // 25.1.3.16 NumericToRawBytes ( type, value, isLittleEndian ), https://tc39.es/ecma262/#sec-numerictorawbytes
  239. template<typename T>
  240. static void numeric_to_raw_bytes(VM& vm, Value value, bool is_little_endian, Bytes raw_bytes)
  241. {
  242. VERIFY(value.is_number() || value.is_bigint());
  243. using UnderlyingBufferDataType = Conditional<IsSame<ClampedU8, T>, u8, T>;
  244. VERIFY(raw_bytes.size() == sizeof(UnderlyingBufferDataType));
  245. auto flip_if_needed = [&]() {
  246. if (is_little_endian)
  247. return;
  248. VERIFY(sizeof(UnderlyingBufferDataType) % 2 == 0);
  249. for (size_t i = 0; i < sizeof(UnderlyingBufferDataType) / 2; ++i)
  250. swap(raw_bytes[i], raw_bytes[sizeof(UnderlyingBufferDataType) - 1 - i]);
  251. };
  252. if constexpr (IsSame<UnderlyingBufferDataType, float>) {
  253. float raw_value = MUST(value.to_double(vm));
  254. ReadonlyBytes { &raw_value, sizeof(float) }.copy_to(raw_bytes);
  255. flip_if_needed();
  256. return;
  257. }
  258. if constexpr (IsSame<UnderlyingBufferDataType, double>) {
  259. double raw_value = MUST(value.to_double(vm));
  260. ReadonlyBytes { &raw_value, sizeof(double) }.copy_to(raw_bytes);
  261. flip_if_needed();
  262. return;
  263. }
  264. if constexpr (!IsIntegral<UnderlyingBufferDataType>)
  265. VERIFY_NOT_REACHED();
  266. if constexpr (sizeof(UnderlyingBufferDataType) == 8) {
  267. UnderlyingBufferDataType int_value;
  268. if constexpr (IsSigned<UnderlyingBufferDataType>)
  269. int_value = MUST(value.to_bigint_int64(vm));
  270. else
  271. int_value = MUST(value.to_bigint_uint64(vm));
  272. ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes);
  273. flip_if_needed();
  274. return;
  275. } else {
  276. UnderlyingBufferDataType int_value;
  277. if constexpr (IsSigned<UnderlyingBufferDataType>) {
  278. if constexpr (sizeof(UnderlyingBufferDataType) == 4)
  279. int_value = MUST(value.to_i32(vm));
  280. else if constexpr (sizeof(UnderlyingBufferDataType) == 2)
  281. int_value = MUST(value.to_i16(vm));
  282. else
  283. int_value = MUST(value.to_i8(vm));
  284. } else {
  285. if constexpr (sizeof(UnderlyingBufferDataType) == 4)
  286. int_value = MUST(value.to_u32(vm));
  287. else if constexpr (sizeof(UnderlyingBufferDataType) == 2)
  288. int_value = MUST(value.to_u16(vm));
  289. else if constexpr (!IsSame<T, ClampedU8>)
  290. int_value = MUST(value.to_u8(vm));
  291. else
  292. int_value = MUST(value.to_u8_clamp(vm));
  293. }
  294. ReadonlyBytes { &int_value, sizeof(UnderlyingBufferDataType) }.copy_to(raw_bytes);
  295. if constexpr (sizeof(UnderlyingBufferDataType) % 2 == 0)
  296. flip_if_needed();
  297. return;
  298. }
  299. }
  300. // 25.1.3.17 SetValueInBuffer ( arrayBuffer, byteIndex, type, value, isTypedArray, order [ , isLittleEndian ] ), https://tc39.es/ecma262/#sec-setvalueinbuffer
  301. template<typename T>
  302. void ArrayBuffer::set_value(size_t byte_index, Value value, [[maybe_unused]] bool is_typed_array, Order, bool is_little_endian)
  303. {
  304. auto& vm = this->vm();
  305. // 1. Assert: IsDetachedBuffer(arrayBuffer) is false.
  306. VERIFY(!is_detached());
  307. // 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
  308. VERIFY(m_data_block.buffer().bytes().slice(byte_index).size() >= sizeof(T));
  309. // 3. Assert: value is a BigInt if IsBigIntElementType(type) is true; otherwise, value is a Number.
  310. if constexpr (IsIntegral<T> && sizeof(T) == 8)
  311. VERIFY(value.is_bigint());
  312. else
  313. VERIFY(value.is_number());
  314. // 4. Let block be arrayBuffer.[[ArrayBufferData]].
  315. auto& block = m_data_block.buffer();
  316. // FIXME: 5. Let elementSize be the Element Size value specified in Table 70 for Element Type type.
  317. // 6. If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  318. // NOTE: Done by default parameter at declaration of this function.
  319. // 7. Let rawBytes be NumericToRawBytes(type, value, isLittleEndian).
  320. AK::Array<u8, sizeof(T)> raw_bytes;
  321. numeric_to_raw_bytes<T>(vm, value, is_little_endian, raw_bytes);
  322. // FIXME 8. If IsSharedArrayBuffer(arrayBuffer) is true, then
  323. if (false) {
  324. // FIXME: a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  325. // FIXME: b. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  326. // FIXME: c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
  327. // FIXME: d. Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventsRecord.[[EventList]].
  328. }
  329. // 9. Else,
  330. else {
  331. // a. Store the individual bytes of rawBytes into block, starting at block[byteIndex].
  332. raw_bytes.span().copy_to(block.span().slice(byte_index));
  333. }
  334. // 10. Return unused.
  335. }
  336. // 25.1.3.18 GetModifySetValueInBuffer ( arrayBuffer, byteIndex, type, value, op [ , isLittleEndian ] ), https://tc39.es/ecma262/#sec-getmodifysetvalueinbuffer
  337. template<typename T>
  338. Value ArrayBuffer::get_modify_set_value(size_t byte_index, Value value, ReadWriteModifyFunction operation, bool is_little_endian)
  339. {
  340. auto& vm = this->vm();
  341. auto raw_bytes = MUST(ByteBuffer::create_uninitialized(sizeof(T)));
  342. numeric_to_raw_bytes<T>(vm, value, is_little_endian, raw_bytes);
  343. // FIXME: Check for shared buffer
  344. auto raw_bytes_read = MUST(ByteBuffer::create_uninitialized(sizeof(T)));
  345. m_data_block.buffer().bytes().slice(byte_index, sizeof(T)).copy_to(raw_bytes_read);
  346. auto raw_bytes_modified = operation(raw_bytes_read, raw_bytes);
  347. raw_bytes_modified.span().copy_to(m_data_block.buffer().span().slice(byte_index));
  348. return raw_bytes_to_numeric<T>(vm, raw_bytes_read, is_little_endian);
  349. }
  350. }