AtomicsObject.cpp 18 KB

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