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