ArrayBuffer.h 18 KB

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