AtomicsObject.cpp 18 KB

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