AtomicsObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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(), MUST(PrimitiveString::create(vm, "Atomics"sv)), 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 = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__;
  179. // 11. Let expectedBytes be NumericToRawBytes(elementType, expected, isLittleEndian).
  180. auto expected_bytes = MUST_OR_THROW_OOM(numeric_to_raw_bytes<T>(vm, expected, is_little_endian));
  181. // 12. Let replacementBytes be NumericToRawBytes(elementType, replacement, isLittleEndian).
  182. auto replacement_bytes = MUST_OR_THROW_OOM(numeric_to_raw_bytes<T>(vm, replacement, is_little_endian));
  183. // FIXME: Implement SharedArrayBuffer case.
  184. // 13. If IsSharedArrayBuffer(buffer) is true, then
  185. // a-i.
  186. // 14. Else,
  187. // a. Let rawBytesRead be a List of length elementSize whose elements are the sequence of elementSize bytes starting with block[indexedPosition].
  188. // FIXME: Propagate errors.
  189. auto raw_bytes_read = MUST(block.slice(indexed_position, sizeof(T)));
  190. // b. If ByteListEqual(rawBytesRead, expectedBytes) is true, then
  191. // i. Store the individual bytes of replacementBytes into block, starting at block[indexedPosition].
  192. if constexpr (IsFloatingPoint<T>) {
  193. VERIFY_NOT_REACHED();
  194. } else {
  195. using U = Conditional<IsSame<ClampedU8, T>, u8, T>;
  196. auto* v = reinterpret_cast<U*>(block.span().slice(indexed_position).data());
  197. auto* e = reinterpret_cast<U*>(expected_bytes.data());
  198. auto* r = reinterpret_cast<U*>(replacement_bytes.data());
  199. (void)AK::atomic_compare_exchange_strong(v, *e, *r);
  200. }
  201. // 15. Return RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian).
  202. return raw_bytes_to_numeric<T>(vm, raw_bytes_read, is_little_endian);
  203. }
  204. // 25.4.5 Atomics.compareExchange ( typedArray, index, expectedValue, replacementValue ), https://tc39.es/ecma262/#sec-atomics.compareexchange
  205. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::compare_exchange)
  206. {
  207. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  208. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  209. if (is<ClassName>(typed_array)) \
  210. return TRY(atomic_compare_exchange_impl<Type>(vm, *typed_array));
  211. JS_ENUMERATE_TYPED_ARRAYS
  212. #undef __JS_ENUMERATE
  213. VERIFY_NOT_REACHED();
  214. }
  215. // 25.4.6 Atomics.exchange ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.exchange
  216. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::exchange)
  217. {
  218. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  219. auto atomic_exchange = [](auto* storage, auto value) { return AK::atomic_exchange(storage, value); };
  220. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  221. if (is<ClassName>(typed_array)) \
  222. return TRY(perform_atomic_operation<Type>(vm, *typed_array, move(atomic_exchange)));
  223. JS_ENUMERATE_TYPED_ARRAYS
  224. #undef __JS_ENUMERATE
  225. VERIFY_NOT_REACHED();
  226. }
  227. // 25.4.7 Atomics.isLockFree ( size ), https://tc39.es/ecma262/#sec-atomics.islockfree
  228. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::is_lock_free)
  229. {
  230. auto size = TRY(vm.argument(0).to_integer_or_infinity(vm));
  231. if (size == 1)
  232. return Value(AK::atomic_is_lock_free<u8>());
  233. if (size == 2)
  234. return Value(AK::atomic_is_lock_free<u16>());
  235. if (size == 4)
  236. return Value(true);
  237. if (size == 8)
  238. return Value(AK::atomic_is_lock_free<u64>());
  239. return Value(false);
  240. }
  241. // 25.4.8 Atomics.load ( typedArray, index ), https://tc39.es/ecma262/#sec-atomics.load
  242. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::load)
  243. {
  244. // 1. Let buffer be ? ValidateIntegerTypedArray(typedArray).
  245. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  246. TRY(validate_integer_typed_array(vm, *typed_array));
  247. // 2. Let indexedPosition be ? ValidateAtomicAccess(typedArray, index).
  248. auto indexed_position = TRY(validate_atomic_access(vm, *typed_array, vm.argument(1)));
  249. // 3. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  250. if (typed_array->viewed_array_buffer()->is_detached())
  251. return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
  252. // 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.
  253. // 5. Let elementType be TypedArrayElementType(typedArray).
  254. // 6. Return GetValueFromBuffer(buffer, indexedPosition, elementType, true, SeqCst).
  255. return typed_array->get_value_from_buffer(indexed_position, ArrayBuffer::Order::SeqCst, true);
  256. }
  257. // 25.4.9 Atomics.or ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.or
  258. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::or_)
  259. {
  260. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  261. auto atomic_or = [](auto* storage, auto value) { return AK::atomic_fetch_or(storage, value); };
  262. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  263. if (is<ClassName>(typed_array)) \
  264. return TRY(perform_atomic_operation<Type>(vm, *typed_array, move(atomic_or)));
  265. JS_ENUMERATE_TYPED_ARRAYS
  266. #undef __JS_ENUMERATE
  267. VERIFY_NOT_REACHED();
  268. }
  269. // 25.4.10 Atomics.store ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.store
  270. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::store)
  271. {
  272. // 1. Let buffer be ? ValidateIntegerTypedArray(typedArray).
  273. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  274. TRY(validate_integer_typed_array(vm, *typed_array));
  275. // 2. Let indexedPosition be ? ValidateAtomicAccess(typedArray, index).
  276. auto indexed_position = TRY(validate_atomic_access(vm, *typed_array, vm.argument(1)));
  277. auto value = vm.argument(2);
  278. Value value_to_set;
  279. // 3. If typedArray.[[ContentType]] is BigInt, let v be ? ToBigInt(value).
  280. if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt)
  281. value_to_set = TRY(value.to_bigint(vm));
  282. // 4. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
  283. else
  284. value_to_set = Value(TRY(value.to_integer_or_infinity(vm)));
  285. // 5. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
  286. if (typed_array->viewed_array_buffer()->is_detached())
  287. return vm.throw_completion<TypeError>(ErrorType::DetachedArrayBuffer);
  288. // 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.
  289. // 7. Let elementType be TypedArrayElementType(typedArray).
  290. // 8. Perform SetValueInBuffer(buffer, indexedPosition, elementType, v, true, SeqCst).
  291. MUST_OR_THROW_OOM(typed_array->set_value_in_buffer(indexed_position, value_to_set, ArrayBuffer::Order::SeqCst, true));
  292. // 9. Return v.
  293. return value_to_set;
  294. }
  295. // 25.4.11 Atomics.sub ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.sub
  296. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::sub)
  297. {
  298. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  299. auto atomic_sub = [](auto* storage, auto value) { return AK::atomic_fetch_sub(storage, value); };
  300. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  301. if (is<ClassName>(typed_array)) \
  302. return TRY(perform_atomic_operation<Type>(vm, *typed_array, move(atomic_sub)));
  303. JS_ENUMERATE_TYPED_ARRAYS
  304. #undef __JS_ENUMERATE
  305. VERIFY_NOT_REACHED();
  306. }
  307. // 25.4.14 Atomics.xor ( typedArray, index, value ), https://tc39.es/ecma262/#sec-atomics.xor
  308. JS_DEFINE_NATIVE_FUNCTION(AtomicsObject::xor_)
  309. {
  310. auto* typed_array = TRY(typed_array_from(vm, vm.argument(0)));
  311. auto atomic_xor = [](auto* storage, auto value) { return AK::atomic_fetch_xor(storage, value); };
  312. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  313. if (is<ClassName>(typed_array)) \
  314. return TRY(perform_atomic_operation<Type>(vm, *typed_array, move(atomic_xor)));
  315. JS_ENUMERATE_TYPED_ARRAYS
  316. #undef __JS_ENUMERATE
  317. VERIFY_NOT_REACHED();
  318. }
  319. }