AtomicsObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Atomic.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Endian.h>
  9. #include <LibJS/Runtime/AtomicsObject.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. #include <LibJS/Runtime/TypedArray.h>
  12. #include <LibJS/Runtime/Value.h>
  13. namespace JS {
  14. // 25.4.2.1 ValidateIntegerTypedArray ( typedArray [ , waitable ] ), https://tc39.es/ecma262/#sec-validateintegertypedarray
  15. static ThrowCompletionOr<ArrayBuffer*> validate_integer_typed_array(GlobalObject& global_object, TypedArrayBase& typed_array, bool waitable = false)
  16. {
  17. auto& vm = global_object.vm();
  18. // 1. If waitable is not present, set waitable to false.
  19. // 2. Perform ? ValidateTypedArray(typedArray).
  20. TRY(validate_typed_array(global_object, typed_array));
  21. // 3. Let buffer be typedArray.[[ViewedArrayBuffer]].
  22. auto* buffer = typed_array.viewed_array_buffer();
  23. // 4. Let typeName be typedArray.[[TypedArrayName]].
  24. auto type_name = typed_array.element_name();
  25. // 5. Let type be the Element Type value in Table 72 for typeName.
  26. // 6. If waitable is true, then
  27. if (waitable) {
  28. // a. If typeName is not "Int32Array" or "BigInt64Array", throw a TypeError exception.
  29. if ((type_name != "Int32Array"sv) && (type_name != "BigInt64Array"sv))
  30. return vm.throw_completion<TypeError>(global_object, ErrorType::TypedArrayTypeIsNot, type_name, "Int32 or BigInt64"sv);
  31. }
  32. // 7. Else,
  33. else {
  34. // a. If ! IsUnclampedIntegerElementType(type) is false and ! IsBigIntElementType(type) is false, throw a TypeError exception.
  35. if (!typed_array.is_unclamped_integer_element_type() && !typed_array.is_bigint_element_type())
  36. return vm.throw_completion<TypeError>(global_object, ErrorType::TypedArrayTypeIsNot, type_name, "an unclamped integer or BigInt"sv);
  37. }
  38. // 8. Return buffer.
  39. return buffer;
  40. }
  41. // 25.4.2.2 ValidateAtomicAccess ( typedArray, requestIndex ), https://tc39.es/ecma262/#sec-validateatomicaccess
  42. static ThrowCompletionOr<size_t> validate_atomic_access(GlobalObject& global_object, TypedArrayBase& typed_array, Value request_index)
  43. {
  44. auto& vm = global_object.vm();
  45. // 1. Let length be typedArray.[[ArrayLength]].
  46. auto length = typed_array.array_length();
  47. // 2. Let accessIndex be ? ToIndex(requestIndex).
  48. auto access_index = TRY(request_index.to_index(global_object));
  49. // 3. Assert: accessIndex ≥ 0.
  50. // 4. If accessIndex ≥ length, throw a RangeError exception.
  51. if (access_index >= length)
  52. return vm.throw_completion<RangeError>(global_object, ErrorType::IndexOutOfRange, access_index, typed_array.array_length());
  53. // 5. Let arrayTypeName be typedArray.[[TypedArrayName]].
  54. // 6. Let elementSize be the Element Size value specified in Table 72 for arrayTypeName.
  55. auto element_size = typed_array.element_size();
  56. // 7. Let offset be typedArray.[[ByteOffset]].
  57. auto offset = typed_array.byte_offset();
  58. // 8. Return (accessIndex × elementSize) + offset.
  59. return (access_index * element_size) + offset;
  60. }
  61. // 25.4.2.11 AtomicReadModifyWrite ( typedArray, index, value, op ), https://tc39.es/ecma262/#sec-atomicreadmodifywrite
  62. static ThrowCompletionOr<Value> atomic_read_modify_write(GlobalObject& global_object, TypedArrayBase& typed_array, Value index, Value value, ReadWriteModifyFunction operation)
  63. {
  64. auto& vm = global_object.vm();
  65. // 1. Let buffer be ? ValidateIntegerTypedArray(typedArray).
  66. auto* buffer = TRY(validate_integer_typed_array(global_object, typed_array));
  67. // 2. Let indexedPosition be ? ValidateAtomicAccess(typedArray, index).
  68. auto indexed_position = TRY(validate_atomic_access(global_object, typed_array, index));
  69. // 3. Let arrayTypeName be typedArray.[[TypedArrayName]].
  70. Value value_to_set;
  71. // 4. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value).
  72. if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt)
  73. value_to_set = TRY(value.to_bigint(global_object));
  74. // 5. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
  75. else
  76. value_to_set = Value(TRY(value.to_integer_or_infinity(global_object)));
  77. // 6. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  78. if (buffer->is_detached())
  79. return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
  80. // 7. NOTE: The above check is not redundant with the check in ValidateIntegerTypedArray because the call to ToBigInt or ToIntegerOrInfinity on the preceding lines can have arbitrary side effects, which could cause the buffer to become detached.
  81. // 8. Let elementType be the Element Type value in Table 72 for arrayTypeName.
  82. // 9. Return GetModifySetValueInBuffer(buffer, indexedPosition, elementType, v, op).
  83. return typed_array.get_modify_set_value_in_buffer(indexed_position, value_to_set, move(operation));
  84. }
  85. template<typename T, typename AtomicFunction>
  86. static ThrowCompletionOr<Value> perform_atomic_operation(GlobalObject& global_object, TypedArrayBase& typed_array, AtomicFunction&& operation)
  87. {
  88. auto& vm = global_object.vm();
  89. auto index = vm.argument(1);
  90. auto value = vm.argument(2);
  91. auto operation_wrapper = [&, operation = forward<AtomicFunction>(operation)](ByteBuffer x_bytes, ByteBuffer y_bytes) -> ByteBuffer {
  92. if constexpr (IsFloatingPoint<T>) {
  93. VERIFY_NOT_REACHED();
  94. } else {
  95. using U = Conditional<IsSame<ClampedU8, T>, u8, T>;
  96. auto* x = reinterpret_cast<U*>(x_bytes.data());
  97. auto* y = reinterpret_cast<U*>(y_bytes.data());
  98. operation(x, *y);
  99. return x_bytes;
  100. }
  101. };
  102. return atomic_read_modify_write(global_object, typed_array, index, value, move(operation_wrapper));
  103. }
  104. AtomicsObject::AtomicsObject(GlobalObject& global_object)
  105. : Object(*global_object.object_prototype())
  106. {
  107. }
  108. void AtomicsObject::initialize(GlobalObject& global_object)
  109. {
  110. Object::initialize(global_object);
  111. auto& vm = this->vm();
  112. u8 attr = Attribute::Writable | Attribute::Configurable;
  113. define_native_function(vm.names.add, add, 3, attr);
  114. define_native_function(vm.names.and_, and_, 3, attr);
  115. define_native_function(vm.names.compareExchange, compare_exchange, 4, attr);
  116. define_native_function(vm.names.exchange, exchange, 3, attr);
  117. define_native_function(vm.names.isLockFree, is_lock_free, 1, attr);
  118. define_native_function(vm.names.load, load, 2, attr);
  119. define_native_function(vm.names.or_, or_, 3, attr);
  120. define_native_function(vm.names.store, store, 3, attr);
  121. define_native_function(vm.names.sub, sub, 3, attr);
  122. define_native_function(vm.names.xor_, xor_, 3, attr);
  123. // 25.4.15 Atomics [ @@toStringTag ], https://tc39.es/ecma262/#sec-atomics-@@tostringtag
  124. define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(global_object.heap(), "Atomics"), Attribute::Configurable);
  125. }
  126. // 25.4.3 Atomics.add ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.add
  127. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::add)
  128. {
  129. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  130. if (!typed_array)
  131. return {};
  132. auto atomic_add = [](auto* storage, auto value) { return AK::atomic_fetch_add(storage, value); };
  133. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  134. if (is<ClassName>(typed_array)) \
  135. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_add)));
  136. JS_ENUMERATE_TYPED_ARRAYS
  137. #undef __JS_ENUMERATE
  138. VERIFY_NOT_REACHED();
  139. }
  140. // 25.4.4 Atomics.and ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.and
  141. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::and_)
  142. {
  143. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  144. if (!typed_array)
  145. return {};
  146. auto atomic_and = [](auto* storage, auto value) { return AK::atomic_fetch_and(storage, value); };
  147. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  148. if (is<ClassName>(typed_array)) \
  149. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_and)));
  150. JS_ENUMERATE_TYPED_ARRAYS
  151. #undef __JS_ENUMERATE
  152. VERIFY_NOT_REACHED();
  153. }
  154. // Implementation of 25.4.5 Atomics.compareExchange ( typedArray, index, expectedValue, replacementValue ), https://tc39.es/ecma262/#sec-atomics.compareexchange
  155. template<typename T>
  156. static ThrowCompletionOr<Value> atomic_compare_exchange_impl(GlobalObject& global_object, TypedArrayBase& typed_array)
  157. {
  158. auto& vm = global_object.vm();
  159. // 1. Let buffer be ? ValidateIntegerTypedArray(typedArray).
  160. auto* buffer = TRY(validate_integer_typed_array(global_object, typed_array));
  161. // 2. Let block be buffer.[[ArrayBufferData]].
  162. auto& block = buffer->buffer();
  163. // 3. Let indexedPosition be ? ValidateAtomicAccess(typedArray, index).
  164. auto indexed_position = TRY(validate_atomic_access(global_object, typed_array, vm.argument(1)));
  165. // 4. Let arrayTypeName be typedArray.[[TypedArrayName]].
  166. Value expected;
  167. Value replacement;
  168. // 5. If typedArray.[[ContentType]] is BigInt, then
  169. if (typed_array.content_type() == TypedArrayBase::ContentType::BigInt) {
  170. // a. Let expected be ? ToBigInt(expectedValue).
  171. expected = TRY(vm.argument(2).to_bigint(global_object));
  172. // b. Let replacement be ? ToBigInt(replacementValue).
  173. replacement = TRY(vm.argument(3).to_bigint(global_object));
  174. }
  175. // 6. Else,
  176. else {
  177. // a. Let expected be 𝔽(? ToIntegerOrInfinity(expectedValue)).
  178. expected = Value(TRY(vm.argument(2).to_integer_or_infinity(global_object)));
  179. // b. Let replacement be 𝔽(? ToIntegerOrInfinity(replacementValue)).
  180. replacement = Value(TRY(vm.argument(3).to_integer_or_infinity(global_object)));
  181. }
  182. // 7. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  183. if (buffer->is_detached())
  184. return vm.template throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
  185. // 8. NOTE: The above check is not redundant with the check in ValidateIntegerTypedArray because the call to ToBigInt or ToIntegerOrInfinity on the preceding lines can have arbitrary side effects, which could cause the buffer to become detached.
  186. // 9. Let elementType be the Element Type value in Table 72 for arrayTypeName.
  187. // 10. Let elementSize be the Element Size value specified in Table 72 for Element Type elementType.
  188. // 11. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  189. constexpr bool is_little_endian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__;
  190. // 12. Let expectedBytes be NumericToRawBytes(elementType, expected, isLittleEndian).
  191. auto expected_bytes = numeric_to_raw_bytes<T>(global_object, expected, is_little_endian);
  192. // 13. Let replacementBytes be NumericToRawBytes(elementType, replacement, isLittleEndian).
  193. auto replacement_bytes = numeric_to_raw_bytes<T>(global_object, replacement, is_little_endian);
  194. // FIXME: Implement SharedArrayBuffer case.
  195. // 14. If IsSharedArrayBuffer(buffer) is true, then
  196. // a-i.
  197. // 15. Else,
  198. // a. Let rawBytesRead be a List of length elementSize whose elements are the sequence of elementSize bytes starting with block[indexedPosition].
  199. auto raw_bytes_read = block.slice(indexed_position, sizeof(T));
  200. // b. If ByteListEqual(rawBytesRead, expectedBytes) is true, then
  201. // i. Store the individual bytes of replacementBytes into block, starting at block[indexedPosition].
  202. if constexpr (IsFloatingPoint<T>) {
  203. VERIFY_NOT_REACHED();
  204. } else {
  205. using U = Conditional<IsSame<ClampedU8, T>, u8, T>;
  206. auto* v = reinterpret_cast<U*>(block.span().slice(indexed_position).data());
  207. auto* e = reinterpret_cast<U*>(expected_bytes.data());
  208. auto* r = reinterpret_cast<U*>(replacement_bytes.data());
  209. (void)AK::atomic_compare_exchange_strong(v, *e, *r);
  210. }
  211. // 16. Return RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian).
  212. return raw_bytes_to_numeric<T>(global_object, raw_bytes_read, is_little_endian);
  213. }
  214. // 25.4.5 Atomics.compareExchange ( typedArray, index, expectedValue, replacementValue ), https://tc39.es/ecma262/#sec-atomics.compareexchange
  215. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::compare_exchange)
  216. {
  217. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  218. if (!typed_array)
  219. return {};
  220. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  221. if (is<ClassName>(typed_array)) \
  222. return TRY_OR_DISCARD(atomic_compare_exchange_impl<Type>(global_object, *typed_array));
  223. JS_ENUMERATE_TYPED_ARRAYS
  224. #undef __JS_ENUMERATE
  225. VERIFY_NOT_REACHED();
  226. }
  227. // 25.4.6 Atomics.exchange ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.exchange
  228. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::exchange)
  229. {
  230. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  231. if (!typed_array)
  232. return {};
  233. auto atomic_exchange = [](auto* storage, auto value) { return AK::atomic_exchange(storage, value); };
  234. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  235. if (is<ClassName>(typed_array)) \
  236. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_exchange)));
  237. JS_ENUMERATE_TYPED_ARRAYS
  238. #undef __JS_ENUMERATE
  239. VERIFY_NOT_REACHED();
  240. }
  241. // 25.4.7 Atomics.isLockFree ( size ), https://tc39.es/ecma262/#sec-atomics.islockfree
  242. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::is_lock_free)
  243. {
  244. auto size = TRY_OR_DISCARD(vm.argument(0).to_integer_or_infinity(global_object));
  245. if (size == 1)
  246. return Value(AK::atomic_is_lock_free<u8>());
  247. if (size == 2)
  248. return Value(AK::atomic_is_lock_free<u16>());
  249. if (size == 4)
  250. return Value(true);
  251. if (size == 8)
  252. return Value(AK::atomic_is_lock_free<u64>());
  253. return Value(false);
  254. }
  255. // 25.4.8 Atomics.load ( typedArray, index ), https://tc39.es/ecma262/#sec-atomics.load
  256. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::load)
  257. {
  258. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  259. if (!typed_array)
  260. return {};
  261. TRY_OR_DISCARD(validate_integer_typed_array(global_object, *typed_array));
  262. auto indexed_position = TRY_OR_DISCARD(validate_atomic_access(global_object, *typed_array, vm.argument(1)));
  263. if (typed_array->viewed_array_buffer()->is_detached()) {
  264. vm.throw_exception<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
  265. return {};
  266. }
  267. return typed_array->get_value_from_buffer(indexed_position, ArrayBuffer::Order::SeqCst, true);
  268. }
  269. // 25.4.9 Atomics.or ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.or
  270. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::or_)
  271. {
  272. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  273. if (!typed_array)
  274. return {};
  275. auto atomic_or = [](auto* storage, auto value) { return AK::atomic_fetch_or(storage, value); };
  276. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  277. if (is<ClassName>(typed_array)) \
  278. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_or)));
  279. JS_ENUMERATE_TYPED_ARRAYS
  280. #undef __JS_ENUMERATE
  281. VERIFY_NOT_REACHED();
  282. }
  283. // 25.4.10 Atomics.store ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.store
  284. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::store)
  285. {
  286. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  287. if (!typed_array)
  288. return {};
  289. TRY_OR_DISCARD(validate_integer_typed_array(global_object, *typed_array));
  290. auto indexed_position = TRY_OR_DISCARD(validate_atomic_access(global_object, *typed_array, vm.argument(1)));
  291. auto value = vm.argument(2);
  292. Value value_to_set;
  293. if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt)
  294. value_to_set = TRY_OR_DISCARD(value.to_bigint(global_object));
  295. else
  296. value_to_set = Value(TRY_OR_DISCARD(value.to_integer_or_infinity(global_object)));
  297. if (typed_array->viewed_array_buffer()->is_detached()) {
  298. vm.throw_exception<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
  299. return {};
  300. }
  301. typed_array->set_value_in_buffer(indexed_position, value_to_set, ArrayBuffer::Order::SeqCst, true);
  302. return value_to_set;
  303. }
  304. // 25.4.11 Atomics.sub ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.sub
  305. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::sub)
  306. {
  307. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  308. if (!typed_array)
  309. return {};
  310. auto atomic_sub = [](auto* storage, auto value) { return AK::atomic_fetch_sub(storage, value); };
  311. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  312. if (is<ClassName>(typed_array)) \
  313. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_sub)));
  314. JS_ENUMERATE_TYPED_ARRAYS
  315. #undef __JS_ENUMERATE
  316. VERIFY_NOT_REACHED();
  317. }
  318. // 25.4.14 Atomics.xor ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.xor
  319. JS_DEFINE_OLD_NATIVE_FUNCTION(AtomicsObject::xor_)
  320. {
  321. auto* typed_array = typed_array_from(global_object, vm.argument(0));
  322. if (!typed_array)
  323. return {};
  324. auto atomic_xor = [](auto* storage, auto value) { return AK::atomic_fetch_xor(storage, value); };
  325. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  326. if (is<ClassName>(typed_array)) \
  327. return TRY_OR_DISCARD(perform_atomic_operation<Type>(global_object, *typed_array, move(atomic_xor)));
  328. JS_ENUMERATE_TYPED_ARRAYS
  329. #undef __JS_ENUMERATE
  330. VERIFY_NOT_REACHED();
  331. }
  332. }