ArrayBuffer.h 16 KB

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