ArrayBuffer.h 17 KB

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