AtomicsObject.cpp 18 KB

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