AtomicsObject.cpp 18 KB

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