AtomicsObject.cpp 18 KB

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