| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* |
| 8 |
* JS Atomics pseudo-module. |
| 9 |
* |
| 10 |
* See chapter 24.4 "The Atomics Object" and chapter 27 "Memory Model" in |
| 11 |
* ECMAScript 2021 for the full specification. |
| 12 |
*/ |
| 13 |
|
| 14 |
#include "builtin/AtomicsObject.h" |
| 15 |
|
| 16 |
#include "mozilla/Atomics.h" |
| 17 |
#include "mozilla/DebugOnly.h" |
| 18 |
#include "mozilla/FloatingPoint.h" |
| 19 |
#include "mozilla/Maybe.h" |
| 20 |
#include "mozilla/ScopeExit.h" |
| 21 |
|
| 22 |
#include "jsnum.h" |
| 23 |
|
| 24 |
#include "builtin/Promise.h" |
| 25 |
#include "jit/AtomicOperations.h" |
| 26 |
#include "jit/InlinableNatives.h" |
| 27 |
#include "js/Class.h" |
| 28 |
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* |
| 29 |
#include "js/PropertySpec.h" |
| 30 |
#include "js/Result.h" |
| 31 |
#include "js/WaitCallbacks.h" |
| 32 |
#include "vm/GlobalObject.h" |
| 33 |
#include "vm/HelperThreads.h" // AutoLockHelperThreadState |
| 34 |
#include "vm/OffThreadPromiseRuntimeState.h" // OffthreadPromiseTask |
| 35 |
#include "vm/TypedArrayObject.h" |
| 36 |
|
| 37 |
#include "vm/Compartment-inl.h" |
| 38 |
#include "vm/JSObject-inl.h" |
| 39 |
#include "vm/Realm-inl.h" |
| 40 |
|
| 41 |
using namespace js; |
| 42 |
|
| 43 |
static bool ReportBadArrayType(JSContext* cx) { |
| 44 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 45 |
JSMSG_ATOMICS_BAD_ARRAY); |
| 46 |
return false; |
| 47 |
} |
| 48 |
|
| 49 |
static bool ReportDetachedArrayBuffer(JSContext* cx) { |
| 50 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 51 |
JSMSG_TYPED_ARRAY_DETACHED); |
| 52 |
return false; |
| 53 |
} |
| 54 |
|
| 55 |
static bool ReportResizedArrayBuffer(JSContext* cx) { |
| 56 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 57 |
JSMSG_TYPED_ARRAY_RESIZED_BOUNDS); |
| 58 |
return false; |
| 59 |
} |
| 60 |
|
| 61 |
static bool ReportOutOfRange(JSContext* cx) { |
| 62 |
// Use JSMSG_BAD_INDEX here, it is what ToIndex uses for some cases that it |
| 63 |
// reports directly. |
| 64 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX); |
| 65 |
return false; |
| 66 |
} |
| 67 |
|
| 68 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 69 |
// Plus: https://github.com/tc39/ecma262/pull/1908 |
| 70 |
// 24.4.1.1 ValidateIntegerTypedArray ( typedArray [ , waitable ] ) |
| 71 |
static bool ValidateIntegerTypedArray( |
| 72 |
JSContext* cx, HandleValue typedArray, bool waitable, |
| 73 |
MutableHandle<TypedArrayObject*> unwrappedTypedArray) { |
| 74 |
// Step 1 (implicit). |
| 75 |
|
| 76 |
// Step 2. |
| 77 |
auto* unwrapped = UnwrapAndTypeCheckValue<TypedArrayObject>( |
| 78 |
cx, typedArray, [cx]() { ReportBadArrayType(cx); }); |
| 79 |
if (!unwrapped) { |
| 80 |
return false; |
| 81 |
} |
| 82 |
|
| 83 |
if (unwrapped->hasDetachedBuffer()) { |
| 84 |
return ReportDetachedArrayBuffer(cx); |
| 85 |
} |
| 86 |
|
| 87 |
// Steps 3-6. |
| 88 |
if (waitable) { |
| 89 |
switch (unwrapped->type()) { |
| 90 |
case Scalar::Int32: |
| 91 |
case Scalar::BigInt64: |
| 92 |
break; |
| 93 |
default: |
| 94 |
return ReportBadArrayType(cx); |
| 95 |
} |
| 96 |
} else { |
| 97 |
switch (unwrapped->type()) { |
| 98 |
case Scalar::Int8: |
| 99 |
case Scalar::Uint8: |
| 100 |
case Scalar::Int16: |
| 101 |
case Scalar::Uint16: |
| 102 |
case Scalar::Int32: |
| 103 |
case Scalar::Uint32: |
| 104 |
case Scalar::BigInt64: |
| 105 |
case Scalar::BigUint64: |
| 106 |
break; |
| 107 |
default: |
| 108 |
return ReportBadArrayType(cx); |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
// Steps 7-9 (modified to return the TypedArray). |
| 113 |
unwrappedTypedArray.set(unwrapped); |
| 114 |
return true; |
| 115 |
} |
| 116 |
|
| 117 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 118 |
// 24.4.1.2 ValidateAtomicAccess ( typedArray, requestIndex ) |
| 119 |
static bool ValidateAtomicAccess(JSContext* cx, |
| 120 |
Handle<TypedArrayObject*> typedArray, |
| 121 |
HandleValue requestIndex, size_t* index) { |
| 122 |
MOZ_ASSERT(!typedArray->hasDetachedBuffer()); |
| 123 |
|
| 124 |
// Steps 1-2. |
| 125 |
mozilla::Maybe<size_t> length = typedArray->length(); |
| 126 |
if (!length) { |
| 127 |
// ValidateIntegerTypedArray doesn't check for out-of-bounds in our |
| 128 |
// implementation, so we have to handle this case here. |
| 129 |
return ReportResizedArrayBuffer(cx); |
| 130 |
} |
| 131 |
|
| 132 |
// Steps 3-4. |
| 133 |
uint64_t accessIndex; |
| 134 |
if (!ToIndex(cx, requestIndex, &accessIndex)) { |
| 135 |
return false; |
| 136 |
} |
| 137 |
|
| 138 |
// Step 5. |
| 139 |
if (accessIndex >= *length) { |
| 140 |
return ReportOutOfRange(cx); |
| 141 |
} |
| 142 |
|
| 143 |
// Steps 6-9. |
| 144 |
*index = size_t(accessIndex); |
| 145 |
return true; |
| 146 |
} |
| 147 |
|
| 148 |
template <typename T> |
| 149 |
struct ArrayOps { |
| 150 |
using Type = T; |
| 151 |
|
| 152 |
static JS::Result<T> convertValue(JSContext* cx, HandleValue v) { |
| 153 |
int32_t n; |
| 154 |
if (!ToInt32(cx, v, &n)) { |
| 155 |
return cx->alreadyReportedError(); |
| 156 |
} |
| 157 |
return static_cast<T>(n); |
| 158 |
} |
| 159 |
|
| 160 |
static JS::Result<T> convertValue(JSContext* cx, HandleValue v, |
| 161 |
MutableHandleValue result) { |
| 162 |
double d; |
| 163 |
if (!ToInteger(cx, v, &d)) { |
| 164 |
return cx->alreadyReportedError(); |
| 165 |
} |
| 166 |
result.setNumber(d); |
| 167 |
return static_cast<T>(JS::ToInt32(d)); |
| 168 |
} |
| 169 |
|
| 170 |
static JS::Result<> storeResult(JSContext* cx, T v, |
| 171 |
MutableHandleValue result) { |
| 172 |
result.setInt32(v); |
| 173 |
return Ok(); |
| 174 |
} |
| 175 |
}; |
| 176 |
|
| 177 |
template <> |
| 178 |
JS::Result<> ArrayOps<uint32_t>::storeResult(JSContext* cx, uint32_t v, |
| 179 |
MutableHandleValue result) { |
| 180 |
// Always double typed so that the JITs can assume the types are stable. |
| 181 |
result.setDouble(v); |
| 182 |
return Ok(); |
| 183 |
} |
| 184 |
|
| 185 |
template <> |
| 186 |
struct ArrayOps<int64_t> { |
| 187 |
using Type = int64_t; |
| 188 |
|
| 189 |
static JS::Result<int64_t> convertValue(JSContext* cx, HandleValue v) { |
| 190 |
BigInt* bi = ToBigInt(cx, v); |
| 191 |
if (!bi) { |
| 192 |
return cx->alreadyReportedError(); |
| 193 |
} |
| 194 |
return BigInt::toInt64(bi); |
| 195 |
} |
| 196 |
|
| 197 |
static JS::Result<int64_t> convertValue(JSContext* cx, HandleValue v, |
| 198 |
MutableHandleValue result) { |
| 199 |
BigInt* bi = ToBigInt(cx, v); |
| 200 |
if (!bi) { |
| 201 |
return cx->alreadyReportedError(); |
| 202 |
} |
| 203 |
result.setBigInt(bi); |
| 204 |
return BigInt::toInt64(bi); |
| 205 |
} |
| 206 |
|
| 207 |
static JS::Result<> storeResult(JSContext* cx, int64_t v, |
| 208 |
MutableHandleValue result) { |
| 209 |
BigInt* bi = BigInt::createFromInt64(cx, v); |
| 210 |
if (!bi) { |
| 211 |
return cx->alreadyReportedError(); |
| 212 |
} |
| 213 |
result.setBigInt(bi); |
| 214 |
return Ok(); |
| 215 |
} |
| 216 |
}; |
| 217 |
|
| 218 |
template <> |
| 219 |
struct ArrayOps<uint64_t> { |
| 220 |
using Type = uint64_t; |
| 221 |
|
| 222 |
static JS::Result<uint64_t> convertValue(JSContext* cx, HandleValue v) { |
| 223 |
BigInt* bi = ToBigInt(cx, v); |
| 224 |
if (!bi) { |
| 225 |
return cx->alreadyReportedError(); |
| 226 |
} |
| 227 |
return BigInt::toUint64(bi); |
| 228 |
} |
| 229 |
|
| 230 |
static JS::Result<uint64_t> convertValue(JSContext* cx, HandleValue v, |
| 231 |
MutableHandleValue result) { |
| 232 |
BigInt* bi = ToBigInt(cx, v); |
| 233 |
if (!bi) { |
| 234 |
return cx->alreadyReportedError(); |
| 235 |
} |
| 236 |
result.setBigInt(bi); |
| 237 |
return BigInt::toUint64(bi); |
| 238 |
} |
| 239 |
|
| 240 |
static JS::Result<> storeResult(JSContext* cx, uint64_t v, |
| 241 |
MutableHandleValue result) { |
| 242 |
BigInt* bi = BigInt::createFromUint64(cx, v); |
| 243 |
if (!bi) { |
| 244 |
return cx->alreadyReportedError(); |
| 245 |
} |
| 246 |
result.setBigInt(bi); |
| 247 |
return Ok(); |
| 248 |
} |
| 249 |
}; |
| 250 |
|
| 251 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 252 |
// 24.4.1.11 AtomicReadModifyWrite ( typedArray, index, value, op ), steps 1-2. |
| 253 |
// 24.4.1.12 AtomicLoad ( typedArray, index ), steps 1-2. |
| 254 |
// 24.4.4 Atomics.compareExchange ( typedArray, index, ... ), steps 1-2. |
| 255 |
// 24.4.9 Atomics.store ( typedArray, index, value ), steps 1-2. |
| 256 |
template <typename Op> |
| 257 |
bool AtomicAccess(JSContext* cx, HandleValue obj, HandleValue index, Op op) { |
| 258 |
// Step 1. |
| 259 |
Rooted<TypedArrayObject*> unwrappedTypedArray(cx); |
| 260 |
if (!ValidateIntegerTypedArray(cx, obj, false, &unwrappedTypedArray)) { |
| 261 |
return false; |
| 262 |
} |
| 263 |
|
| 264 |
// Step 2. |
| 265 |
size_t intIndex; |
| 266 |
if (!ValidateAtomicAccess(cx, unwrappedTypedArray, index, &intIndex)) { |
| 267 |
return false; |
| 268 |
} |
| 269 |
|
| 270 |
switch (unwrappedTypedArray->type()) { |
| 271 |
case Scalar::Int8: |
| 272 |
return op(ArrayOps<int8_t>{}, unwrappedTypedArray, intIndex); |
| 273 |
case Scalar::Uint8: |
| 274 |
return op(ArrayOps<uint8_t>{}, unwrappedTypedArray, intIndex); |
| 275 |
case Scalar::Int16: |
| 276 |
return op(ArrayOps<int16_t>{}, unwrappedTypedArray, intIndex); |
| 277 |
case Scalar::Uint16: |
| 278 |
return op(ArrayOps<uint16_t>{}, unwrappedTypedArray, intIndex); |
| 279 |
case Scalar::Int32: |
| 280 |
return op(ArrayOps<int32_t>{}, unwrappedTypedArray, intIndex); |
| 281 |
case Scalar::Uint32: |
| 282 |
return op(ArrayOps<uint32_t>{}, unwrappedTypedArray, intIndex); |
| 283 |
case Scalar::BigInt64: |
| 284 |
return op(ArrayOps<int64_t>{}, unwrappedTypedArray, intIndex); |
| 285 |
case Scalar::BigUint64: |
| 286 |
return op(ArrayOps<uint64_t>{}, unwrappedTypedArray, intIndex); |
| 287 |
case Scalar::Float16: |
| 288 |
case Scalar::Float32: |
| 289 |
case Scalar::Float64: |
| 290 |
case Scalar::Uint8Clamped: |
| 291 |
case Scalar::MaxTypedArrayViewType: |
| 292 |
case Scalar::Int64: |
| 293 |
case Scalar::Simd128: |
| 294 |
break; |
| 295 |
} |
| 296 |
MOZ_CRASH("Unsupported TypedArray type"); |
| 297 |
} |
| 298 |
|
| 299 |
template <typename T> |
| 300 |
static SharedMem<T*> TypedArrayData(JSContext* cx, TypedArrayObject* typedArray, |
| 301 |
size_t index) { |
| 302 |
// RevalidateAtomicAccess, steps 1-3. |
| 303 |
mozilla::Maybe<size_t> length = typedArray->length(); |
| 304 |
|
| 305 |
// RevalidateAtomicAccess, step 4. |
| 306 |
if (!length) { |
| 307 |
ReportDetachedArrayBuffer(cx); |
| 308 |
return {}; |
| 309 |
} |
| 310 |
|
| 311 |
// RevalidateAtomicAccess, step 5. |
| 312 |
if (index >= *length) { |
| 313 |
ReportOutOfRange(cx); |
| 314 |
return {}; |
| 315 |
} |
| 316 |
|
| 317 |
SharedMem<void*> typedArrayData = typedArray->dataPointerEither(); |
| 318 |
return typedArrayData.cast<T*>() + index; |
| 319 |
} |
| 320 |
|
| 321 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 322 |
// 24.4.4 Atomics.compareExchange ( typedArray, index, expectedValue, |
| 323 |
// replacementValue ) |
| 324 |
static bool atomics_compareExchange(JSContext* cx, unsigned argc, Value* vp) { |
| 325 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 326 |
HandleValue typedArray = args.get(0); |
| 327 |
HandleValue index = args.get(1); |
| 328 |
|
| 329 |
return AtomicAccess( |
| 330 |
cx, typedArray, index, |
| 331 |
[cx, &args](auto ops, Handle<TypedArrayObject*> unwrappedTypedArray, |
| 332 |
size_t index) { |
| 333 |
using T = typename decltype(ops)::Type; |
| 334 |
|
| 335 |
HandleValue expectedValue = args.get(2); |
| 336 |
HandleValue replacementValue = args.get(3); |
| 337 |
|
| 338 |
T oldval; |
| 339 |
JS_TRY_VAR_OR_RETURN_FALSE(cx, oldval, |
| 340 |
ops.convertValue(cx, expectedValue)); |
| 341 |
|
| 342 |
T newval; |
| 343 |
JS_TRY_VAR_OR_RETURN_FALSE(cx, newval, |
| 344 |
ops.convertValue(cx, replacementValue)); |
| 345 |
|
| 346 |
SharedMem<T*> addr = TypedArrayData<T>(cx, unwrappedTypedArray, index); |
| 347 |
if (!addr) { |
| 348 |
return false; |
| 349 |
} |
| 350 |
|
| 351 |
oldval = |
| 352 |
jit::AtomicOperations::compareExchangeSeqCst(addr, oldval, newval); |
| 353 |
|
| 354 |
JS_TRY_OR_RETURN_FALSE(cx, ops.storeResult(cx, oldval, args.rval())); |
| 355 |
return true; |
| 356 |
}); |
| 357 |
} |
| 358 |
|
| 359 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 360 |
// 24.4.7 Atomics.load ( typedArray, index ) |
| 361 |
static bool atomics_load(JSContext* cx, unsigned argc, Value* vp) { |
| 362 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 363 |
HandleValue typedArray = args.get(0); |
| 364 |
HandleValue index = args.get(1); |
| 365 |
|
| 366 |
return AtomicAccess( |
| 367 |
cx, typedArray, index, |
| 368 |
[cx, &args](auto ops, Handle<TypedArrayObject*> unwrappedTypedArray, |
| 369 |
size_t index) { |
| 370 |
using T = typename decltype(ops)::Type; |
| 371 |
|
| 372 |
SharedMem<T*> addr = TypedArrayData<T>(cx, unwrappedTypedArray, index); |
| 373 |
if (!addr) { |
| 374 |
return false; |
| 375 |
} |
| 376 |
|
| 377 |
T v = jit::AtomicOperations::loadSeqCst(addr); |
| 378 |
|
| 379 |
JS_TRY_OR_RETURN_FALSE(cx, ops.storeResult(cx, v, args.rval())); |
| 380 |
return true; |
| 381 |
}); |
| 382 |
} |
| 383 |
|
| 384 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 385 |
// 24.4.9 Atomics.store ( typedArray, index, value ) |
| 386 |
static bool atomics_store(JSContext* cx, unsigned argc, Value* vp) { |
| 387 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 388 |
HandleValue typedArray = args.get(0); |
| 389 |
HandleValue index = args.get(1); |
| 390 |
|
| 391 |
return AtomicAccess( |
| 392 |
cx, typedArray, index, |
| 393 |
[cx, &args](auto ops, Handle<TypedArrayObject*> unwrappedTypedArray, |
| 394 |
size_t index) { |
| 395 |
using T = typename decltype(ops)::Type; |
| 396 |
|
| 397 |
HandleValue value = args.get(2); |
| 398 |
|
| 399 |
T v; |
| 400 |
JS_TRY_VAR_OR_RETURN_FALSE(cx, v, |
| 401 |
ops.convertValue(cx, value, args.rval())); |
| 402 |
|
| 403 |
SharedMem<T*> addr = TypedArrayData<T>(cx, unwrappedTypedArray, index); |
| 404 |
if (!addr) { |
| 405 |
return false; |
| 406 |
} |
| 407 |
|
| 408 |
jit::AtomicOperations::storeSeqCst(addr, v); |
| 409 |
return true; |
| 410 |
}); |
| 411 |
} |
| 412 |
|
| 413 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 414 |
// 24.4.1.11 AtomicReadModifyWrite ( typedArray, index, value, op ) |
| 415 |
template <typename AtomicOp> |
| 416 |
static bool AtomicReadModifyWrite(JSContext* cx, const CallArgs& args, |
| 417 |
AtomicOp op) { |
| 418 |
HandleValue typedArray = args.get(0); |
| 419 |
HandleValue index = args.get(1); |
| 420 |
|
| 421 |
return AtomicAccess( |
| 422 |
cx, typedArray, index, |
| 423 |
[cx, &args, op](auto ops, Handle<TypedArrayObject*> unwrappedTypedArray, |
| 424 |
size_t index) { |
| 425 |
using T = typename decltype(ops)::Type; |
| 426 |
|
| 427 |
HandleValue value = args.get(2); |
| 428 |
|
| 429 |
T v; |
| 430 |
JS_TRY_VAR_OR_RETURN_FALSE(cx, v, ops.convertValue(cx, value)); |
| 431 |
|
| 432 |
SharedMem<T*> addr = TypedArrayData<T>(cx, unwrappedTypedArray, index); |
| 433 |
if (!addr) { |
| 434 |
return false; |
| 435 |
} |
| 436 |
|
| 437 |
v = op(addr, v); |
| 438 |
|
| 439 |
JS_TRY_OR_RETURN_FALSE(cx, ops.storeResult(cx, v, args.rval())); |
| 440 |
return true; |
| 441 |
}); |
| 442 |
} |
| 443 |
|
| 444 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 445 |
// 24.4.5 Atomics.exchange ( typedArray, index, value ) |
| 446 |
static bool atomics_exchange(JSContext* cx, unsigned argc, Value* vp) { |
| 447 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 448 |
|
| 449 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 450 |
return jit::AtomicOperations::exchangeSeqCst(addr, val); |
| 451 |
}); |
| 452 |
} |
| 453 |
|
| 454 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 455 |
// 24.4.2 Atomics.add ( typedArray, index, value ) |
| 456 |
static bool atomics_add(JSContext* cx, unsigned argc, Value* vp) { |
| 457 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 458 |
|
| 459 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 460 |
return jit::AtomicOperations::fetchAddSeqCst(addr, val); |
| 461 |
}); |
| 462 |
} |
| 463 |
|
| 464 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 465 |
// 24.4.10 Atomics.sub ( typedArray, index, value ) |
| 466 |
static bool atomics_sub(JSContext* cx, unsigned argc, Value* vp) { |
| 467 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 468 |
|
| 469 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 470 |
return jit::AtomicOperations::fetchSubSeqCst(addr, val); |
| 471 |
}); |
| 472 |
} |
| 473 |
|
| 474 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 475 |
// 24.4.3 Atomics.and ( typedArray, index, value ) |
| 476 |
static bool atomics_and(JSContext* cx, unsigned argc, Value* vp) { |
| 477 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 478 |
|
| 479 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 480 |
return jit::AtomicOperations::fetchAndSeqCst(addr, val); |
| 481 |
}); |
| 482 |
} |
| 483 |
|
| 484 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 485 |
// 24.4.8 Atomics.or ( typedArray, index, value ) |
| 486 |
static bool atomics_or(JSContext* cx, unsigned argc, Value* vp) { |
| 487 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 488 |
|
| 489 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 490 |
return jit::AtomicOperations::fetchOrSeqCst(addr, val); |
| 491 |
}); |
| 492 |
} |
| 493 |
|
| 494 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 495 |
// 24.4.13 Atomics.xor ( typedArray, index, value ) |
| 496 |
static bool atomics_xor(JSContext* cx, unsigned argc, Value* vp) { |
| 497 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 498 |
|
| 499 |
return AtomicReadModifyWrite(cx, args, [](auto addr, auto val) { |
| 500 |
return jit::AtomicOperations::fetchXorSeqCst(addr, val); |
| 501 |
}); |
| 502 |
} |
| 503 |
|
| 504 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 505 |
// 24.4.6 Atomics.isLockFree ( size ) |
| 506 |
static bool atomics_isLockFree(JSContext* cx, unsigned argc, Value* vp) { |
| 507 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 508 |
HandleValue v = args.get(0); |
| 509 |
|
| 510 |
// Step 1. |
| 511 |
int32_t size; |
| 512 |
if (v.isInt32()) { |
| 513 |
size = v.toInt32(); |
| 514 |
} else { |
| 515 |
double dsize; |
| 516 |
if (!ToInteger(cx, v, &dsize)) { |
| 517 |
return false; |
| 518 |
} |
| 519 |
|
| 520 |
// Step 7 (non-integer case only). |
| 521 |
if (!mozilla::NumberEqualsInt32(dsize, &size)) { |
| 522 |
args.rval().setBoolean(false); |
| 523 |
return true; |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
// Steps 2-7. |
| 528 |
args.rval().setBoolean(jit::AtomicOperations::isLockfreeJS(size)); |
| 529 |
return true; |
| 530 |
} |
| 531 |
|
| 532 |
namespace js { |
| 533 |
|
| 534 |
/* |
| 535 |
* [SMDOC] Atomics.wait, Atomics.waitAsync, and Atomics.notify |
| 536 |
* |
| 537 |
* `wait`, `waitAsync`, and `notify` are provided as low-level primitives for |
| 538 |
* thread synchronization. The primary use case is to take code that looks like |
| 539 |
* this: |
| 540 |
* |
| 541 |
* const ValueIndex = 0; |
| 542 |
* const FlagIndex = 1; |
| 543 |
* |
| 544 |
* THREAD A: |
| 545 |
* // Write a value. |
| 546 |
* Atomics.store(sharedBuffer, ValueIndex, value); |
| 547 |
* // Update a flag to indicate that the value was written. |
| 548 |
* Atomics.store(sharedBuffer, FlagIndex, 1); |
| 549 |
* |
| 550 |
* THREAD B: |
| 551 |
* // Busy-wait for the flag to be updated. |
| 552 |
* while (Atomics.load(sharedBuffer, FlagIndex) == 0) {} |
| 553 |
* // Load the value. |
| 554 |
* let value = Atomics.load(sharedBuffer, ValueIndex); |
| 555 |
* |
| 556 |
* ...and replace the busy-wait: |
| 557 |
* |
| 558 |
* THREAD A': |
| 559 |
* // Write the value and update the flag. |
| 560 |
* Atomics.store(sharedBuffer, ValueIndex, value); |
| 561 |
* Atomics.store(sharedBuffer, FlagIndex, 1); |
| 562 |
* // Notify that the flag has been written. |
| 563 |
* Atomics.notify(sharedBuffer, FlagIndex); |
| 564 |
* |
| 565 |
* THREAD B': |
| 566 |
* // Wait until the flag is notified. |
| 567 |
* // If it's already non-zero, no wait occurs. |
| 568 |
* Atomics.wait(sharedBuffer, FlagIndex, 0); |
| 569 |
* // Load the value. |
| 570 |
* let value = Atomics.load(sharedBuffer, ValueIndex); |
| 571 |
* |
| 572 |
* `wait` puts the calling thread to sleep until it is notified (or an optional |
| 573 |
* timeout expires). This can't be used on the main thread. |
| 574 |
* |
| 575 |
* `waitAsync` instead creates a Promise which will be resolved when the |
| 576 |
* position is notified (or an optional timeout expires). |
| 577 |
* |
| 578 |
* When `wait` or `waitAsync` is called, a waiter is created and registered with |
| 579 |
* the SharedArrayBuffer. Waiter instances for a SharedArrayRawBuffer are |
| 580 |
* connected in a circular doubly-linked list, containing both sync and async |
| 581 |
* waiters. Sync waiters are stack allocated in the stack frame of the waiting |
| 582 |
* thread. Async waiters are heap-allocated. The `waiters` field of the |
| 583 |
* SharedArrayRawBuffer is a dedicated list head node for the list. Waiters are |
| 584 |
* awoken in a first-in-first-out order. The `next` field of the list head node |
| 585 |
* points to the highest priority waiter. The `prev` field points to the lowest |
| 586 |
* priority waiter. This list is traversed when `notify` is called to find the |
| 587 |
* waiters that should be woken up. |
| 588 |
* |
| 589 |
* Synchronous waits are implemented using a per-context condition variable. See |
| 590 |
* FutexThread::wait. |
| 591 |
* |
| 592 |
* Asynchronous waits are more complicated, particularly with respect to |
| 593 |
* timeouts. In addition to the AsyncFutexWaiter that is added to the list of |
| 594 |
* waiters, we also create: |
| 595 |
* |
| 596 |
* 1. A Promise object to return to the caller. The promise will be resolved |
| 597 |
* when the waiter is notified or times out. |
| 598 |
* 2. A WaitAsyncNotifyTask (derived from OffThreadPromiseTask) wrapping that |
| 599 |
* promise. `notify` can be called from any thread, but the promise must be |
| 600 |
* resolved on the thread that owns it. To resolve the promise, we dispatch |
| 601 |
* the task to enqueue a promise resolution task in the target's event |
| 602 |
* loop. The notify task is stored in the AsyncFutexWaiter. |
| 603 |
* 3. If there is a non-zero timeout, a WaitAsyncTimeoutTask (derived from |
| 604 |
* JS::Dispatchable) containing a pointer to the async waiter. We dispatch |
| 605 |
* this task to the embedding's event loop, with a delay. When the timeout |
| 606 |
* expires and the task runs, if the promise has not yet been resolved, we |
| 607 |
* resolve it with "timed-out". |
| 608 |
* |
| 609 |
* `waitAsync` Lifetimes |
| 610 |
* --------------------- |
| 611 |
* ┌─────┐ |
| 612 |
* │ SAB │ |
| 613 |
* └─────┘ |
| 614 |
* ┌────► ◄────┐ bi-directional linked list |
| 615 |
* │ │ |
| 616 |
* ▼ ▼ |
| 617 |
* *waiter *waiter |
| 618 |
* ▲ ▲ |
| 619 |
* │ │ |
| 620 |
* └───► * ◄──┘ |
| 621 |
* │ |
| 622 |
* ┌───────▼────────┐ |
| 623 |
* │AsyncFutexWaiter│ ◄───────────┐ |
| 624 |
* └────────────────┘ │ |
| 625 |
* │ │ |
| 626 |
* │ borrow │ borrow |
| 627 |
* ▼ ▼ |
| 628 |
* ┌────────────────────┐ ┌───────────────────┐ |
| 629 |
* │WaitAsyncTimeoutTask│ │WaitAsyncNotifyTask│ ◄─────┐ |
| 630 |
* └────────────────────┘ └───┬───────────────┘ │ |
| 631 |
* ▲ │ ▲ │ |
| 632 |
* │ │ │ │ (transfered) |
| 633 |
* │ own ▼ │ │ own |
| 634 |
* ┌───────────────────────────┐ ┌─────────────┐ │ ┌─────────────────────┐ |
| 635 |
* │DelayedJSDispatchaleHandler│ │PromiseObject│ │ │JSDispatchableHandler│ |
| 636 |
* └───────────────────────────┘ └─────────────┘ │ └─────────────────────┘ |
| 637 |
* ▲ ▲ │ |
| 638 |
* ┌────────┼────────────────────────┼──────┐ │ |
| 639 |
* │ ┌──────┴───────┐ ┌────┴────┐ │ │ own (initialized) |
| 640 |
* │ │TimeoutManager│ │JSContext┼─┼──────┘ |
| 641 |
* │ └──────────────┘ └─────────┘ │ Cancellable List |
| 642 |
* │ │ |
| 643 |
* │ Runtime (MainThread or Worker) │ |
| 644 |
* └────────────────────────────────────────┘ |
| 645 |
* |
| 646 |
* |
| 647 |
* The data representing an async wait is divided between the JSContext in which |
| 648 |
* it was created and the SharedArrayBuffer being waited on. There are three |
| 649 |
* potential components: |
| 650 |
* |
| 651 |
* A) The AsyncFutexWaiter itself (shared by the SharedArrayRawBuffer, |
| 652 |
* WaitAsyncNotifyTask, and WaitAsyncTimeoutTask if it exists). It |
| 653 |
* will be cleaned up manually. |
| 654 |
* B) The corresponding WaitAsyncNotifyTask (owned by the JS::Context). It |
| 655 |
* destroys itself on run. |
| 656 |
* C) The WaitAsyncTimeoutTask (owned by the embedding's job queue). It |
| 657 |
* destroys itself on run. |
| 658 |
* |
| 659 |
* WaitAsyncNotifyTask and WaitAsyncTimeoutTask (if it exists) delete |
| 660 |
* themselves. When either task is run or destroyed, they also trigger the |
| 661 |
* destruction and unlinking of the AsyncFutexWaiter. There are |
| 662 |
* four scenarios: |
| 663 |
* |
| 664 |
* 1. A call to `Atomics.notify` notifies the waiter (atomics_notify_impl) |
| 665 |
* from another thread. |
| 666 |
* A) The async waiter is removed from the list. |
| 667 |
* B) The notify task is removed from OffThreadPromiseRuntimeState's |
| 668 |
* cancelable list and is dispatched to resolve the promise with "ok". |
| 669 |
* The task then destroys itself. |
| 670 |
* C) The WaitAsyncTimeoutTask is disabled. It will fire and do nothing. |
| 671 |
* See AsyncFutexWaiter::maybeCancelTimeout in atomics_notify_impl. |
| 672 |
* D) The async waiter is destroyed. |
| 673 |
* |
| 674 |
* 2. A call to `Atomics.notify` notifies the waiter (atomics_notify_impl) |
| 675 |
* from the same thread. |
| 676 |
* A) The async waiter is removed from the list. |
| 677 |
* B) The notify task is cancelled. The promise is extracted and resolved |
| 678 |
* directly. |
| 679 |
* C) The WaitAsyncTimeoutTask is disabled. It will fire and do nothing. |
| 680 |
* See AsyncFutexWaiter::maybeCancelTimeout in atomics_notify_impl. |
| 681 |
* D) The async waiter is destroyed. |
| 682 |
* |
| 683 |
* 3. The timeout expires without notification (WaitAsyncTimeoutTask::run) |
| 684 |
* A) The async waiter is removed from the list. |
| 685 |
* B) The notify task is dispatched to resolve the promise with "timed-out" |
| 686 |
* and destroys itself.. |
| 687 |
* C) The timeout task is running and will be destroyed when it's done. |
| 688 |
* D) The async waiter is destroyed. |
| 689 |
* |
| 690 |
* 4. The context is destroyed (OffThreadPromiseRuntimeState::shutdown): |
| 691 |
* A) The async waiter is removed and destroyed by |
| 692 |
* WaitAsyncNotifyTask::prepareForCancel. |
| 693 |
* B) The notify task is cancelled and destroyed by |
| 694 |
* OffThreadPromiseRuntimeState::shutdown. |
| 695 |
* C) The WaitAsyncTimeoutTask is disabled. |
| 696 |
* See AsyncFutexWaiter::maybeCancelTimeout in prepareForCancel. |
| 697 |
* |
| 698 |
* 5. The SharedArrayBuffer is collected by the GC (~FutexWaiterListHead) |
| 699 |
* A) Async waiters without timeouts can no longer resolve. They are removed. |
| 700 |
* B) If no timeout task exists, the notify task is dispatched and |
| 701 |
* destroys itself, without resolving the promise. |
| 702 |
* C) If there is an enqueued timeout, the waiter can still be resolved. |
| 703 |
* In this case it will not be destroyed until it times out. |
| 704 |
* |
| 705 |
* The UniquePtr can be thought of as a "runnable handle" that gives exclusive |
| 706 |
* access to executing a runnable by a given owner. The runnable will still |
| 707 |
* delete itself (via js_delete, see OffThreadPromiseRuntimeState.cpp |
| 708 |
* implementation of OffThreadPromiseTask::run). If somehow the UniquePtr is not |
| 709 |
* passed to embedding code that will run the code, the task is released from |
| 710 |
* the pointer. We then use the list of raw pointers in |
| 711 |
* OffThreadPromiseRuntimeState's cancellable and dead lists are used to |
| 712 |
* identify which were never dispatched, and which failed to dispatch, and clear |
| 713 |
* them when the engine has an opportunity to do so (i.e. shutdown). |
| 714 |
*/ |
| 715 |
|
| 716 |
class WaitAsyncNotifyTask; |
| 717 |
class WaitAsyncTimeoutTask; |
| 718 |
|
| 719 |
class AutoLockFutexAPI { |
| 720 |
// We have to wrap this in a Maybe because of the way loading |
| 721 |
// mozilla::Atomic pointers works. |
| 722 |
mozilla::Maybe<js::UniqueLock<js::Mutex>> unique_; |
| 723 |
|
| 724 |
public: |
| 725 |
AutoLockFutexAPI() { |
| 726 |
js::Mutex* lock = FutexThread::lock_; |
| 727 |
unique_.emplace(*lock); |
| 728 |
} |
| 729 |
|
| 730 |
~AutoLockFutexAPI() { unique_.reset(); } |
| 731 |
|
| 732 |
js::UniqueLock<js::Mutex>& unique() { return *unique_; } |
| 733 |
}; |
| 734 |
|
| 735 |
// Represents one waiter. This is the abstract base class for SyncFutexWaiter |
| 736 |
// and AsyncFutexWaiter. |
| 737 |
class FutexWaiter : public FutexWaiterListNode { |
| 738 |
protected: |
| 739 |
FutexWaiter(JSContext* cx, size_t offset, FutexWaiterKind kind) |
| 740 |
: FutexWaiterListNode(kind), offset_(offset), cx_(cx) {} |
| 741 |
|
| 742 |
size_t offset_; // Element index within the SharedArrayBuffer |
| 743 |
JSContext* cx_; // The thread that called `wait` or `waitAsync`. |
| 744 |
|
| 745 |
public: |
| 746 |
bool isSync() const { return kind_ == FutexWaiterKind::Sync; } |
| 747 |
SyncFutexWaiter* asSync() { |
| 748 |
MOZ_ASSERT(isSync()); |
| 749 |
return reinterpret_cast<SyncFutexWaiter*>(this); |
| 750 |
} |
| 751 |
|
| 752 |
bool isAsync() const { return kind_ == FutexWaiterKind::Async; } |
| 753 |
AsyncFutexWaiter* asAsync() { |
| 754 |
MOZ_ASSERT(isAsync()); |
| 755 |
return reinterpret_cast<AsyncFutexWaiter*>(this); |
| 756 |
} |
| 757 |
size_t offset() const { return offset_; } |
| 758 |
JSContext* cx() { return cx_; } |
| 759 |
}; |
| 760 |
|
| 761 |
// Represents a worker blocked while calling |Atomics.wait|. |
| 762 |
// Instances of js::SyncFutexWaiter are stack-allocated and linked |
| 763 |
// onto the waiter list across a call to FutexThread::wait(). |
| 764 |
// When this waiter is notified, the worker will resume execution. |
| 765 |
class MOZ_STACK_CLASS SyncFutexWaiter : public FutexWaiter { |
| 766 |
public: |
| 767 |
SyncFutexWaiter(JSContext* cx, size_t offset) |
| 768 |
: FutexWaiter(cx, offset, FutexWaiterKind::Sync) {} |
| 769 |
}; |
| 770 |
|
| 771 |
// Represents a waiter asynchronously waiting after calling |Atomics.waitAsync|. |
| 772 |
// Instances of js::AsyncFutexWaiter are heap-allocated. |
| 773 |
// When this waiter is notified, the promise it holds will be resolved. |
| 774 |
class AsyncFutexWaiter : public FutexWaiter { |
| 775 |
public: |
| 776 |
AsyncFutexWaiter(JSContext* cx, size_t offset) |
| 777 |
: FutexWaiter(cx, offset, FutexWaiterKind::Async) {} |
| 778 |
|
| 779 |
WaitAsyncNotifyTask* notifyTask() { return notifyTask_; } |
| 780 |
|
| 781 |
void setNotifyTask(WaitAsyncNotifyTask* task) { |
| 782 |
MOZ_ASSERT(!notifyTask_); |
| 783 |
notifyTask_ = task; |
| 784 |
} |
| 785 |
|
| 786 |
void setTimeoutTask(WaitAsyncTimeoutTask* task) { |
| 787 |
MOZ_ASSERT(!timeoutTask_); |
| 788 |
timeoutTask_ = task; |
| 789 |
} |
| 790 |
|
| 791 |
bool hasTimeout() const { return !!timeoutTask_; } |
| 792 |
WaitAsyncTimeoutTask* timeoutTask() const { return timeoutTask_; } |
| 793 |
|
| 794 |
void maybeClearTimeout(AutoLockFutexAPI& lock); |
| 795 |
|
| 796 |
private: |
| 797 |
// Both of these pointers are borrowed pointers. The notifyTask is owned by |
| 798 |
// the runtime's cancellable list, while the timeout task (if it exists) is |
| 799 |
// owned by the embedding's timeout manager. |
| 800 |
WaitAsyncNotifyTask* notifyTask_ = nullptr; |
| 801 |
WaitAsyncTimeoutTask* timeoutTask_ = nullptr; |
| 802 |
}; |
| 803 |
|
| 804 |
// When an async waiter from a different context is notified, this |
| 805 |
// task is queued to resolve the promise on the thread to which it |
| 806 |
// belongs. |
| 807 |
// |
| 808 |
// WaitAsyncNotifyTask (derived from OffThreadPromiseTask) is wrapping that |
| 809 |
// promise. `Atomics.notify` can be called from any thread, but the promise must |
| 810 |
// be resolved on the thread that owns it. To resolve the promise, we dispatch |
| 811 |
// the task to enqueue a promise resolution task in the target's event |
| 812 |
// loop. |
| 813 |
// |
| 814 |
// See [SMDOC] Atomics.wait for more details. |
| 815 |
class WaitAsyncNotifyTask : public OffThreadPromiseTask { |
| 816 |
public: |
| 817 |
enum class Result { Ok, TimedOut, Dead }; |
| 818 |
|
| 819 |
private: |
| 820 |
Result result_ = Result::Ok; |
| 821 |
|
| 822 |
// A back-edge to the waiter so that it can be cleaned up when the |
| 823 |
// Notify Task is dispatched and destroyed. |
| 824 |
AsyncFutexWaiter* waiter_ = nullptr; |
| 825 |
|
| 826 |
public: |
| 827 |
WaitAsyncNotifyTask(JSContext* cx, Handle<PromiseObject*> promise) |
| 828 |
: OffThreadPromiseTask(cx, promise) {} |
| 829 |
|
| 830 |
void setWaiter(AsyncFutexWaiter* waiter) { |
| 831 |
MOZ_ASSERT(!waiter_); |
| 832 |
waiter_ = waiter; |
| 833 |
} |
| 834 |
|
| 835 |
void setResult(Result result, AutoLockFutexAPI& lock) { result_ = result; } |
| 836 |
|
| 837 |
bool resolve(JSContext* cx, Handle<PromiseObject*> promise) override { |
| 838 |
RootedValue resultMsg(cx); |
| 839 |
switch (result_) { |
| 840 |
case Result::Ok: |
| 841 |
resultMsg = StringValue(cx->names().ok); |
| 842 |
break; |
| 843 |
case Result::TimedOut: |
| 844 |
resultMsg = StringValue(cx->names().timed_out_); |
| 845 |
break; |
| 846 |
case Result::Dead: |
| 847 |
// The underlying SharedArrayBuffer is no longer reachable, and no |
| 848 |
// timeout is associated with this waiter. The promise will never |
| 849 |
// resolve. There's nothing to do here. |
| 850 |
return true; |
| 851 |
} |
| 852 |
return PromiseObject::resolve(cx, promise, resultMsg); |
| 853 |
} |
| 854 |
|
| 855 |
void prepareForCancel() override; |
| 856 |
}; |
| 857 |
|
| 858 |
// WaitAsyncNotifyTask (derived from OffThreadPromiseTask) is wrapping that |
| 859 |
// promise. `notify` can be called from any thread, but the promise must be |
| 860 |
// resolved on the thread that owns it. To resolve the promise, we dispatch |
| 861 |
// the task to enqueue a promise resolution task in the target's event |
| 862 |
// loop. |
| 863 |
// |
| 864 |
// See [SMDOC] Atomics.wait for more details. |
| 865 |
class WaitAsyncTimeoutTask : public JS::Dispatchable { |
| 866 |
AsyncFutexWaiter* waiter_; |
| 867 |
|
| 868 |
public: |
| 869 |
explicit WaitAsyncTimeoutTask(AsyncFutexWaiter* waiter) : waiter_(waiter) { |
| 870 |
MOZ_ASSERT(waiter_); |
| 871 |
} |
| 872 |
|
| 873 |
void clear(AutoLockFutexAPI&) { waiter_ = nullptr; } |
| 874 |
bool cleared(AutoLockFutexAPI&) { return !waiter_; } |
| 875 |
|
| 876 |
void run(JSContext*, MaybeShuttingDown maybeshuttingdown) final; |
| 877 |
void transferToRuntime() final; |
| 878 |
}; |
| 879 |
|
| 880 |
} // namespace js |
| 881 |
|
| 882 |
// https://tc39.es/ecma262/#sec-addwaiter |
| 883 |
static void AddWaiter(SharedArrayRawBuffer* sarb, FutexWaiter* node, |
| 884 |
AutoLockFutexAPI&) { |
| 885 |
FutexWaiterListNode* listHead = sarb->waiters(); |
| 886 |
|
| 887 |
// Step 3: Append waiterRecord to WL.[[Waiters]]. |
| 888 |
node->setNext(listHead); |
| 889 |
node->setPrev(listHead->prev()); |
| 890 |
listHead->prev()->setNext(node); |
| 891 |
listHead->setPrev(node); |
| 892 |
} |
| 893 |
|
| 894 |
// https://tc39.es/ecma262/#sec-removewaiter |
| 895 |
static void RemoveWaiterImpl(FutexWaiterListNode* node, AutoLockFutexAPI&) { |
| 896 |
if (!node->prev()) { |
| 897 |
MOZ_ASSERT(!node->next()); |
| 898 |
return; |
| 899 |
} |
| 900 |
|
| 901 |
node->prev()->setNext(node->next()); |
| 902 |
node->next()->setPrev(node->prev()); |
| 903 |
|
| 904 |
node->setNext(nullptr); |
| 905 |
node->setPrev(nullptr); |
| 906 |
} |
| 907 |
|
| 908 |
// Sync waiters are stack allocated and can simply be removed from the list. |
| 909 |
static void RemoveSyncWaiter(SyncFutexWaiter* waiter, AutoLockFutexAPI& lock) { |
| 910 |
RemoveWaiterImpl(waiter, lock); |
| 911 |
} |
| 912 |
|
| 913 |
// Async waiters are heap allocated. After removing the waiter, the caller |
| 914 |
// is responsible for freeing it. Return the waiter to help enforce this. |
| 915 |
[[nodiscard]] AsyncFutexWaiter* RemoveAsyncWaiter(AsyncFutexWaiter* waiter, |
| 916 |
AutoLockFutexAPI& lock) { |
| 917 |
RemoveWaiterImpl(waiter, lock); |
| 918 |
return waiter; |
| 919 |
} |
| 920 |
|
| 921 |
FutexWaiterListHead::~FutexWaiterListHead() { |
| 922 |
// Cleanup steps from 5. in SMDOC for Atomics.waitAsync |
| 923 |
// When a SharedArrayRawBuffer is no longer reachable, the contents of its |
| 924 |
// waiters list can no longer be notified. However, they can still resolve if |
| 925 |
// they have an associated timeout. When the list head goes away, we walk |
| 926 |
// through the remaining waiters and clean up the ones that don't have |
| 927 |
// timeouts. We leave the remaining waiters in a free-floating linked list; |
| 928 |
// they will remove themselves as the timeouts fire or the associated runtime |
| 929 |
// shuts down. |
| 930 |
AutoLockHelperThreadState helperLock; |
| 931 |
AutoLockFutexAPI lock; |
| 932 |
|
| 933 |
FutexWaiterListNode* iter = next(); |
| 934 |
while (iter != this) { |
| 935 |
// All remaining FutexWaiters must be async. A sync waiter can only exist if |
| 936 |
// a thread is waiting, and that thread must have a reference to the shared |
| 937 |
// array buffer it's waiting on, so that buffer can't be freed. |
| 938 |
|
| 939 |
AsyncFutexWaiter* removedWaiter = |
| 940 |
RemoveAsyncWaiter(iter->toWaiter()->asAsync(), lock); |
| 941 |
iter = iter->next(); |
| 942 |
|
| 943 |
if (removedWaiter->hasTimeout()) { |
| 944 |
// If a timeout task exists, assert that the timeout task can still access |
| 945 |
// it. This will allow it to clean it up when it runs. See the comment in |
| 946 |
// WaitAsyncTimeoutTask::run() or the the SMDOC in this file. |
| 947 |
MOZ_ASSERT(removedWaiter->timeoutTask()->cleared(lock)); |
| 948 |
continue; |
| 949 |
} |
| 950 |
// In the case that a timeout task does not exist, the two live raw |
| 951 |
// pointers at this point are WaitAsyncNotifyTask and the |
| 952 |
// AsyncFutexWaiter. We can clean them up here as there is no way to |
| 953 |
// notify them without the SAB or without waiting for the shutdown of the |
| 954 |
// JS::Context. In order to do this, we store the removed waiter in a |
| 955 |
// unique ptr, so that it is cleared after this function, and dispatch and |
| 956 |
// destroy the notify task. |
| 957 |
UniquePtr<AsyncFutexWaiter> ownedWaiter(removedWaiter); |
| 958 |
WaitAsyncNotifyTask* task = ownedWaiter->notifyTask(); |
| 959 |
task->setResult(WaitAsyncNotifyTask::Result::Dead, lock); |
| 960 |
task->removeFromCancellableListAndDispatch(helperLock); |
| 961 |
} |
| 962 |
|
| 963 |
RemoveWaiterImpl(this, lock); |
| 964 |
} |
| 965 |
|
| 966 |
// Creates an object to use as the return value of Atomics.waitAsync. |
| 967 |
static PlainObject* CreateAsyncResultObject(JSContext* cx, bool async, |
| 968 |
HandleValue promiseOrString) { |
| 969 |
Rooted<PlainObject*> resultObject(cx, NewPlainObject(cx)); |
| 970 |
if (!resultObject) { |
| 971 |
return nullptr; |
| 972 |
} |
| 973 |
|
| 974 |
RootedValue isAsync(cx, BooleanValue(async)); |
| 975 |
if (!NativeDefineDataProperty(cx, resultObject, cx->names().async, isAsync, |
| 976 |
JSPROP_ENUMERATE)) { |
| 977 |
return nullptr; |
| 978 |
} |
| 979 |
|
| 980 |
MOZ_ASSERT_IF(!async, promiseOrString.isString()); |
| 981 |
MOZ_ASSERT_IF(async, promiseOrString.isObject() && |
| 982 |
promiseOrString.toObject().is<PromiseObject>()); |
| 983 |
if (!NativeDefineDataProperty(cx, resultObject, cx->names().value, |
| 984 |
promiseOrString, JSPROP_ENUMERATE)) { |
| 985 |
return nullptr; |
| 986 |
} |
| 987 |
|
| 988 |
return resultObject; |
| 989 |
} |
| 990 |
|
| 991 |
void WaitAsyncNotifyTask::prepareForCancel() { |
| 992 |
AutoLockFutexAPI lock; |
| 993 |
UniquePtr<AsyncFutexWaiter> waiter(RemoveAsyncWaiter(waiter_, lock)); |
| 994 |
waiter->maybeClearTimeout(lock); |
| 995 |
} |
| 996 |
|
| 997 |
void WaitAsyncTimeoutTask::run(JSContext* cx, |
| 998 |
MaybeShuttingDown maybeShuttingDown) { |
| 999 |
AutoLockHelperThreadState helperLock; |
| 1000 |
AutoLockFutexAPI lock; |
| 1001 |
|
| 1002 |
// If the waiter was notified while this task was enqueued, do nothing. |
| 1003 |
if (cleared(lock)) { |
| 1004 |
js_delete(this); |
| 1005 |
return; |
| 1006 |
} |
| 1007 |
|
| 1008 |
// Cleanup steps from 3. and 5. lifecycle in SMDOC for Atomics.waitAsync |
| 1009 |
// Take ownership of the async waiter, so that it will be freed |
| 1010 |
// when we return. |
| 1011 |
UniquePtr<AsyncFutexWaiter> asyncWaiter(RemoveAsyncWaiter(waiter_, lock)); |
| 1012 |
|
| 1013 |
// Dispatch a task to resolve the promise with value "timed-out". |
| 1014 |
WaitAsyncNotifyTask* task = asyncWaiter->notifyTask(); |
| 1015 |
task->setResult(WaitAsyncNotifyTask::Result::TimedOut, lock); |
| 1016 |
task->removeFromCancellableListAndDispatch(helperLock); |
| 1017 |
js_delete(this); |
| 1018 |
} |
| 1019 |
|
| 1020 |
void WaitAsyncTimeoutTask::transferToRuntime() { |
| 1021 |
// Clear and delete. Clearing this task will result in the cancellable |
| 1022 |
// notify task being cleaned up on shutdown, as it can no longer be triggered. |
| 1023 |
// In as sense, the task "transfered" for cleanup is the notify task. |
| 1024 |
{ |
| 1025 |
AutoLockFutexAPI lock; |
| 1026 |
clear(lock); |
| 1027 |
} |
| 1028 |
// As we are not managing any state, the runtime is not tracking this task, |
| 1029 |
// and we have nothing to run, we can delete. |
| 1030 |
js_delete(this); |
| 1031 |
} |
| 1032 |
|
| 1033 |
void AsyncFutexWaiter::maybeClearTimeout(AutoLockFutexAPI& lock) { |
| 1034 |
if (timeoutTask_) { |
| 1035 |
timeoutTask_->clear(lock); |
| 1036 |
} |
| 1037 |
} |
| 1038 |
|
| 1039 |
// DoWait Steps 17-31 |
| 1040 |
// https://tc39.es/ecma262/#sec-dowait |
| 1041 |
template <typename T> |
| 1042 |
static FutexThread::WaitResult AtomicsWaitAsyncCriticalSection( |
| 1043 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, T value, |
| 1044 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout, |
| 1045 |
Handle<PromiseObject*> promise) { |
| 1046 |
// Step 17: Enter critical section. |
| 1047 |
// We need to initialize an OffThreadPromiseTask inside this critical section. |
| 1048 |
// To avoid deadlock, we claim the helper thread lock first. |
| 1049 |
AutoLockHelperThreadState helperThreadLock; |
| 1050 |
AutoLockFutexAPI futexLock; |
| 1051 |
|
| 1052 |
// Steps 18-20: |
| 1053 |
SharedMem<T*> addr = |
| 1054 |
sarb->dataPointerShared().cast<T*>() + (byteOffset / sizeof(T)); |
| 1055 |
if (jit::AtomicOperations::loadSafeWhenRacy(addr) != value) { |
| 1056 |
return FutexThread::WaitResult::NotEqual; |
| 1057 |
} |
| 1058 |
|
| 1059 |
// Step 21 |
| 1060 |
bool hasTimeout = timeout.isSome(); |
| 1061 |
if (hasTimeout && timeout.value().IsZero()) { |
| 1062 |
return FutexThread::WaitResult::TimedOut; |
| 1063 |
} |
| 1064 |
|
| 1065 |
// Steps 22-30 |
| 1066 |
// To handle potential failures, we split this up into two phases: |
| 1067 |
// First, we allocate everything: the notify task, the waiter, and |
| 1068 |
// (if necessary) the timeout task. The allocations are managed |
| 1069 |
// using unique pointers, which will free them on failure. This |
| 1070 |
// phase has no external side-effects. |
| 1071 |
|
| 1072 |
// Second, we transfer ownership of the allocations to the right places: |
| 1073 |
// the waiter owns the notify task, the shared array buffer owns the waiter, |
| 1074 |
// and the event loop owns the timeout task. This phase is infallible. |
| 1075 |
auto notifyTask = js::MakeUnique<WaitAsyncNotifyTask>(cx, promise); |
| 1076 |
if (!notifyTask) { |
| 1077 |
JS_ReportOutOfMemory(cx); |
| 1078 |
return FutexThread::WaitResult::Error; |
| 1079 |
} |
| 1080 |
auto waiter = js::MakeUnique<AsyncFutexWaiter>(cx, byteOffset); |
| 1081 |
if (!waiter) { |
| 1082 |
JS_ReportOutOfMemory(cx); |
| 1083 |
return FutexThread::WaitResult::Error; |
| 1084 |
} |
| 1085 |
|
| 1086 |
notifyTask->setWaiter(waiter.get()); |
| 1087 |
waiter->setNotifyTask(notifyTask.get()); |
| 1088 |
|
| 1089 |
UniquePtr<WaitAsyncTimeoutTask> timeoutTask; |
| 1090 |
if (hasTimeout) { |
| 1091 |
timeoutTask = js::MakeUnique<WaitAsyncTimeoutTask>(waiter.get()); |
| 1092 |
if (!timeoutTask) { |
| 1093 |
JS_ReportOutOfMemory(cx); |
| 1094 |
return FutexThread::WaitResult::Error; |
| 1095 |
} |
| 1096 |
waiter->setTimeoutTask(timeoutTask.get()); |
| 1097 |
} |
| 1098 |
|
| 1099 |
// This is the last fallible operation. If it fails, all allocations |
| 1100 |
// will be freed. init has no side-effects if it fails. |
| 1101 |
if (!js::OffThreadPromiseTask::InitCancellable(cx, helperThreadLock, |
| 1102 |
std::move(notifyTask))) { |
| 1103 |
return FutexThread::WaitResult::Error; |
| 1104 |
} |
| 1105 |
|
| 1106 |
// Below this point, everything is infallible. |
| 1107 |
AddWaiter(sarb, waiter.release(), futexLock); |
| 1108 |
|
| 1109 |
if (hasTimeout) { |
| 1110 |
MOZ_ASSERT(!!timeoutTask); |
| 1111 |
OffThreadPromiseRuntimeState& state = |
| 1112 |
cx->runtime()->offThreadPromiseState.ref(); |
| 1113 |
// We are not tracking the dispatch of the timeout task using the |
| 1114 |
// OffThreadPromiseRuntimeState, so we ignore the return value. If this |
| 1115 |
// fails, the embeddings should call transferToRuntime on timeoutTask |
| 1116 |
// which will clear itself, and set the notify task to be cleaned on |
| 1117 |
// shutdown. |
| 1118 |
(void)state.delayedDispatchToEventLoop(std::move(timeoutTask), |
| 1119 |
timeout.value().ToMilliseconds()); |
| 1120 |
} |
| 1121 |
|
| 1122 |
// Step 31: Leave critical section. |
| 1123 |
return FutexThread::WaitResult::OK; |
| 1124 |
} |
| 1125 |
|
| 1126 |
// DoWait steps 12-35 |
| 1127 |
// https://tc39.es/ecma262/#sec-dowait |
| 1128 |
// This implements the mode=ASYNC case. |
| 1129 |
template <typename T> |
| 1130 |
static PlainObject* AtomicsWaitAsync( |
| 1131 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, T value, |
| 1132 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1133 |
// Step 16a. |
| 1134 |
Rooted<PromiseObject*> promiseObject( |
| 1135 |
cx, CreatePromiseObjectWithoutResolutionFunctions(cx)); |
| 1136 |
if (!promiseObject) { |
| 1137 |
return nullptr; |
| 1138 |
} |
| 1139 |
|
| 1140 |
// Steps 17-31 |
| 1141 |
switch (AtomicsWaitAsyncCriticalSection(cx, sarb, byteOffset, value, timeout, |
| 1142 |
promiseObject)) { |
| 1143 |
case FutexThread::WaitResult::NotEqual: { |
| 1144 |
// Steps 16b, 20c-e |
| 1145 |
RootedValue msg(cx, StringValue(cx->names().not_equal_)); |
| 1146 |
return CreateAsyncResultObject(cx, false, msg); |
| 1147 |
} |
| 1148 |
case FutexThread::WaitResult::TimedOut: { |
| 1149 |
// Steps 16b, 21c-e |
| 1150 |
RootedValue msg(cx, StringValue(cx->names().timed_out_)); |
| 1151 |
return CreateAsyncResultObject(cx, false, msg); |
| 1152 |
} |
| 1153 |
case FutexThread::WaitResult::Error: |
| 1154 |
return nullptr; |
| 1155 |
case FutexThread::WaitResult::OK: |
| 1156 |
break; |
| 1157 |
} |
| 1158 |
|
| 1159 |
// Steps 15b, 33-35 |
| 1160 |
RootedValue objectValue(cx, ObjectValue(*promiseObject)); |
| 1161 |
return CreateAsyncResultObject(cx, true, objectValue); |
| 1162 |
} |
| 1163 |
|
| 1164 |
// DoWait steps 12-32 |
| 1165 |
// https://tc39.es/ecma262/#sec-dowait |
| 1166 |
// This implements the mode=SYNC case. |
| 1167 |
template <typename T> |
| 1168 |
static FutexThread::WaitResult AtomicsWait( |
| 1169 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, T value, |
| 1170 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1171 |
// Validation and other guards should ensure that this does not happen. |
| 1172 |
MOZ_ASSERT(sarb, "wait is only applicable to shared memory"); |
| 1173 |
|
| 1174 |
SharedMem<T*> addr = |
| 1175 |
sarb->dataPointerShared().cast<T*>() + (byteOffset / sizeof(T)); |
| 1176 |
|
| 1177 |
// Steps 17 and 31 (through destructor). |
| 1178 |
// This lock also protects the "waiters" field on SharedArrayRawBuffer, |
| 1179 |
// and it provides the necessary memory fence. |
| 1180 |
AutoLockFutexAPI lock; |
| 1181 |
|
| 1182 |
// Steps 18-20. |
| 1183 |
if (jit::AtomicOperations::loadSafeWhenRacy(addr) != value) { |
| 1184 |
return FutexThread::WaitResult::NotEqual; |
| 1185 |
} |
| 1186 |
|
| 1187 |
// Steps 14, 22-27 |
| 1188 |
SyncFutexWaiter w(cx, byteOffset); |
| 1189 |
|
| 1190 |
// Steps 28-29 |
| 1191 |
AddWaiter(sarb, &w, lock); |
| 1192 |
FutexThread::WaitResult retval = cx->fx.wait(cx, lock.unique(), timeout); |
| 1193 |
RemoveSyncWaiter(&w, lock); |
| 1194 |
|
| 1195 |
// Step 32 |
| 1196 |
return retval; |
| 1197 |
} |
| 1198 |
|
| 1199 |
FutexThread::WaitResult js::atomics_wait_impl( |
| 1200 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, int32_t value, |
| 1201 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1202 |
return AtomicsWait(cx, sarb, byteOffset, value, timeout); |
| 1203 |
} |
| 1204 |
|
| 1205 |
FutexThread::WaitResult js::atomics_wait_impl( |
| 1206 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, int64_t value, |
| 1207 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1208 |
return AtomicsWait(cx, sarb, byteOffset, value, timeout); |
| 1209 |
} |
| 1210 |
|
| 1211 |
PlainObject* js::atomics_wait_async_impl( |
| 1212 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, int32_t value, |
| 1213 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1214 |
return AtomicsWaitAsync(cx, sarb, byteOffset, value, timeout); |
| 1215 |
} |
| 1216 |
|
| 1217 |
PlainObject* js::atomics_wait_async_impl( |
| 1218 |
JSContext* cx, SharedArrayRawBuffer* sarb, size_t byteOffset, int64_t value, |
| 1219 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1220 |
return AtomicsWaitAsync(cx, sarb, byteOffset, value, timeout); |
| 1221 |
} |
| 1222 |
|
| 1223 |
// https://tc39.es/ecma262/#sec-dowait |
| 1224 |
// DoWait ( mode, typedArray, index, value, timeout ), steps 8-35. |
| 1225 |
template <typename T> |
| 1226 |
static bool DoAtomicsWait(JSContext* cx, bool isAsync, |
| 1227 |
Handle<TypedArrayObject*> unwrappedTypedArray, |
| 1228 |
size_t index, T value, HandleValue timeoutv, |
| 1229 |
MutableHandleValue r) { |
| 1230 |
mozilla::Maybe<mozilla::TimeDuration> timeout; |
| 1231 |
if (!timeoutv.isUndefined()) { |
| 1232 |
// Step 8. |
| 1233 |
double timeout_ms; |
| 1234 |
if (!ToNumber(cx, timeoutv, &timeout_ms)) { |
| 1235 |
return false; |
| 1236 |
} |
| 1237 |
|
| 1238 |
// Step 9. |
| 1239 |
if (!std::isnan(timeout_ms)) { |
| 1240 |
if (timeout_ms < 0) { |
| 1241 |
timeout = mozilla::Some(mozilla::TimeDuration::FromSeconds(0.0)); |
| 1242 |
} else if (!std::isinf(timeout_ms)) { |
| 1243 |
timeout = |
| 1244 |
mozilla::Some(mozilla::TimeDuration::FromMilliseconds(timeout_ms)); |
| 1245 |
} |
| 1246 |
} |
| 1247 |
} |
| 1248 |
|
| 1249 |
// Step 10. |
| 1250 |
if (!isAsync && !cx->fx.canWait()) { |
| 1251 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 1252 |
JSMSG_ATOMICS_WAIT_NOT_ALLOWED); |
| 1253 |
return false; |
| 1254 |
} |
| 1255 |
|
| 1256 |
// Step 11. |
| 1257 |
Rooted<SharedArrayBufferObject*> unwrappedSab( |
| 1258 |
cx, unwrappedTypedArray->bufferShared()); |
| 1259 |
|
| 1260 |
// Step 12 |
| 1261 |
mozilla::Maybe<size_t> offset = unwrappedTypedArray->byteOffset(); |
| 1262 |
MOZ_ASSERT( |
| 1263 |
offset, |
| 1264 |
"offset can't become invalid because shared buffers can only grow"); |
| 1265 |
|
| 1266 |
// Step 13. |
| 1267 |
// The computation will not overflow because range checks have been |
| 1268 |
// performed. |
| 1269 |
size_t byteIndexInBuffer = index * sizeof(T) + *offset; |
| 1270 |
|
| 1271 |
// Steps 14-35. |
| 1272 |
if (isAsync) { |
| 1273 |
PlainObject* resultObject = atomics_wait_async_impl( |
| 1274 |
cx, unwrappedSab->rawBufferObject(), byteIndexInBuffer, value, timeout); |
| 1275 |
if (!resultObject) { |
| 1276 |
return false; |
| 1277 |
} |
| 1278 |
r.setObject(*resultObject); |
| 1279 |
return true; |
| 1280 |
} |
| 1281 |
|
| 1282 |
switch (atomics_wait_impl(cx, unwrappedSab->rawBufferObject(), |
| 1283 |
byteIndexInBuffer, value, timeout)) { |
| 1284 |
case FutexThread::WaitResult::NotEqual: |
| 1285 |
r.setString(cx->names().not_equal_); |
| 1286 |
return true; |
| 1287 |
case FutexThread::WaitResult::OK: |
| 1288 |
r.setString(cx->names().ok); |
| 1289 |
return true; |
| 1290 |
case FutexThread::WaitResult::TimedOut: |
| 1291 |
r.setString(cx->names().timed_out_); |
| 1292 |
return true; |
| 1293 |
case FutexThread::WaitResult::Error: |
| 1294 |
return false; |
| 1295 |
default: |
| 1296 |
MOZ_CRASH("Should not happen"); |
| 1297 |
} |
| 1298 |
} |
| 1299 |
|
| 1300 |
// https://tc39.es/ecma262/#sec-dowait |
| 1301 |
// DoWait ( mode, typedArray, index, value, timeout ) |
| 1302 |
static bool DoWait(JSContext* cx, bool isAsync, HandleValue objv, |
| 1303 |
HandleValue index, HandleValue valv, HandleValue timeoutv, |
| 1304 |
MutableHandleValue r) { |
| 1305 |
// Steps 1-2. |
| 1306 |
Rooted<TypedArrayObject*> unwrappedTypedArray(cx); |
| 1307 |
if (!ValidateIntegerTypedArray(cx, objv, true, &unwrappedTypedArray)) { |
| 1308 |
return false; |
| 1309 |
} |
| 1310 |
MOZ_ASSERT(unwrappedTypedArray->type() == Scalar::Int32 || |
| 1311 |
unwrappedTypedArray->type() == Scalar::BigInt64); |
| 1312 |
|
| 1313 |
// Step 3 |
| 1314 |
if (!unwrappedTypedArray->isSharedMemory()) { |
| 1315 |
return ReportBadArrayType(cx); |
| 1316 |
} |
| 1317 |
|
| 1318 |
// Step 4. |
| 1319 |
size_t intIndex; |
| 1320 |
if (!ValidateAtomicAccess(cx, unwrappedTypedArray, index, &intIndex)) { |
| 1321 |
return false; |
| 1322 |
} |
| 1323 |
|
| 1324 |
// Step 5 |
| 1325 |
if (unwrappedTypedArray->type() == Scalar::Int32) { |
| 1326 |
// Step 7. |
| 1327 |
int32_t value; |
| 1328 |
if (!ToInt32(cx, valv, &value)) { |
| 1329 |
return false; |
| 1330 |
} |
| 1331 |
|
| 1332 |
// Steps 8-35. |
| 1333 |
return DoAtomicsWait(cx, isAsync, unwrappedTypedArray, intIndex, value, |
| 1334 |
timeoutv, r); |
| 1335 |
} |
| 1336 |
|
| 1337 |
MOZ_ASSERT(unwrappedTypedArray->type() == Scalar::BigInt64); |
| 1338 |
|
| 1339 |
// Step 6. |
| 1340 |
RootedBigInt value(cx, ToBigInt(cx, valv)); |
| 1341 |
if (!value) { |
| 1342 |
return false; |
| 1343 |
} |
| 1344 |
|
| 1345 |
// Steps 8-35. |
| 1346 |
return DoAtomicsWait(cx, isAsync, unwrappedTypedArray, intIndex, |
| 1347 |
BigInt::toInt64(value), timeoutv, r); |
| 1348 |
} |
| 1349 |
|
| 1350 |
// 24.4.11 Atomics.wait ( typedArray, index, value, timeout ) |
| 1351 |
// https://tc39.es/ecma262/#sec-atomics.wait |
| 1352 |
static bool atomics_wait(JSContext* cx, unsigned argc, Value* vp) { |
| 1353 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1354 |
HandleValue objv = args.get(0); |
| 1355 |
HandleValue index = args.get(1); |
| 1356 |
HandleValue valv = args.get(2); |
| 1357 |
HandleValue timeoutv = args.get(3); |
| 1358 |
MutableHandleValue r = args.rval(); |
| 1359 |
|
| 1360 |
return DoWait(cx, /*isAsync = */ false, objv, index, valv, timeoutv, r); |
| 1361 |
} |
| 1362 |
|
| 1363 |
// Atomics.waitAsync ( typedArray, index, value, timeout ) |
| 1364 |
// https://tc39.es/ecma262/#sec-atomics.waitasync |
| 1365 |
static bool atomics_wait_async(JSContext* cx, unsigned argc, Value* vp) { |
| 1366 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1367 |
HandleValue objv = args.get(0); |
| 1368 |
HandleValue index = args.get(1); |
| 1369 |
HandleValue valv = args.get(2); |
| 1370 |
HandleValue timeoutv = args.get(3); |
| 1371 |
MutableHandleValue r = args.rval(); |
| 1372 |
|
| 1373 |
return DoWait(cx, /*isAsync = */ true, objv, index, valv, timeoutv, r); |
| 1374 |
} |
| 1375 |
|
| 1376 |
// Atomics.notify ( typedArray, index, count ), steps 8-13. |
| 1377 |
// https://tc39.es/ecma262/#sec-atomics.notify |
| 1378 |
bool js::atomics_notify_impl(JSContext* cx, SharedArrayRawBuffer* sarb, |
| 1379 |
size_t byteOffset, int64_t count, int64_t* woken) { |
| 1380 |
MOZ_ASSERT(woken); |
| 1381 |
|
| 1382 |
// Validation should ensure this does not happen. |
| 1383 |
MOZ_ASSERT(sarb, "notify is only applicable to shared memory"); |
| 1384 |
|
| 1385 |
// Step 8 |
| 1386 |
*woken = 0; |
| 1387 |
|
| 1388 |
Rooted<GCVector<PromiseObject*>> promisesToResolve( |
| 1389 |
cx, GCVector<PromiseObject*>(cx)); |
| 1390 |
{ |
| 1391 |
// Steps 9, 12 (through destructor). |
| 1392 |
AutoLockHelperThreadState helperLock; |
| 1393 |
AutoLockFutexAPI lock; |
| 1394 |
// Steps 10-11 |
| 1395 |
FutexWaiterListNode* waiterListHead = sarb->waiters(); |
| 1396 |
FutexWaiterListNode* iter = waiterListHead->next(); |
| 1397 |
while (count && iter != waiterListHead) { |
| 1398 |
FutexWaiter* waiter = iter->toWaiter(); |
| 1399 |
iter = iter->next(); |
| 1400 |
if (byteOffset != waiter->offset()) { |
| 1401 |
continue; |
| 1402 |
} |
| 1403 |
if (waiter->isSync()) { |
| 1404 |
// For sync waits, the context to notify is currently sleeping. |
| 1405 |
// We notify that context (unless it's already been notified by |
| 1406 |
// another thread). |
| 1407 |
if (!waiter->cx()->fx.isWaiting()) { |
| 1408 |
continue; |
| 1409 |
} |
| 1410 |
waiter->cx()->fx.notify(FutexThread::NotifyExplicit); |
| 1411 |
} else { |
| 1412 |
// For async waits, we resolve a promise. |
| 1413 |
|
| 1414 |
// Steps to clean up case 1. and 2. in SMDOC for Atomics.waitAsync |
| 1415 |
// Take ownership of the async waiter, so that it will be |
| 1416 |
// freed at the end of this block. |
| 1417 |
UniquePtr<AsyncFutexWaiter> asyncWaiter( |
| 1418 |
RemoveAsyncWaiter(waiter->asAsync(), lock)); |
| 1419 |
asyncWaiter->maybeClearTimeout(lock); |
| 1420 |
// If we are notifying a waiter that was created by the current |
| 1421 |
// context, we resolve the promise directly instead of dispatching |
| 1422 |
// a task to the event loop. |
| 1423 |
OffThreadPromiseTask* task = asyncWaiter->notifyTask(); |
| 1424 |
if (waiter->cx() == cx) { |
| 1425 |
// Add the promise to a list to resolve as soon as we've left the |
| 1426 |
// critical section. |
| 1427 |
PromiseObject* promise = |
| 1428 |
OffThreadPromiseTask::ExtractAndForget(task, helperLock); |
| 1429 |
if (!promisesToResolve.append(promise)) { |
| 1430 |
return false; |
| 1431 |
} |
| 1432 |
} else { |
| 1433 |
// Dispatch a task to resolve the promise with value "ok". |
| 1434 |
task->removeFromCancellableListAndDispatch(helperLock); |
| 1435 |
} |
| 1436 |
} |
| 1437 |
// Overflow will be a problem only in two cases: |
| 1438 |
// (1) 128-bit systems with substantially more than 2^64 bytes of |
| 1439 |
// memory per process, and a very lightweight |
| 1440 |
// Atomics.waitAsync(). Obviously a future problem. |
| 1441 |
// (2) Bugs. |
| 1442 |
MOZ_RELEASE_ASSERT(*woken < INT64_MAX); |
| 1443 |
(*woken)++; |
| 1444 |
if (count > 0) { |
| 1445 |
--count; |
| 1446 |
} |
| 1447 |
} |
| 1448 |
} |
| 1449 |
|
| 1450 |
// Step 10 (reordered) |
| 1451 |
// We resolve same-thread promises after we've left the critical section to |
| 1452 |
// avoid mutex ordering problems. |
| 1453 |
RootedValue resultMsg(cx, StringValue(cx->names().ok)); |
| 1454 |
for (uint32_t i = 0; i < promisesToResolve.length(); i++) { |
| 1455 |
AutoRealm ar(cx, promisesToResolve[i]); |
| 1456 |
if (!PromiseObject::resolve(cx, promisesToResolve[i], resultMsg)) { |
| 1457 |
MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed()); |
| 1458 |
return false; |
| 1459 |
} |
| 1460 |
} |
| 1461 |
|
| 1462 |
// Step 13. |
| 1463 |
return true; |
| 1464 |
} |
| 1465 |
|
| 1466 |
// ES2021 draft rev bd868f20b8c574ad6689fba014b62a1dba819e56 |
| 1467 |
// 24.4.12 Atomics.notify ( typedArray, index, count ) |
| 1468 |
static bool atomics_notify(JSContext* cx, unsigned argc, Value* vp) { |
| 1469 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1470 |
HandleValue objv = args.get(0); |
| 1471 |
HandleValue index = args.get(1); |
| 1472 |
HandleValue countv = args.get(2); |
| 1473 |
MutableHandleValue r = args.rval(); |
| 1474 |
|
| 1475 |
// Step 1. |
| 1476 |
Rooted<TypedArrayObject*> unwrappedTypedArray(cx); |
| 1477 |
if (!ValidateIntegerTypedArray(cx, objv, true, &unwrappedTypedArray)) { |
| 1478 |
return false; |
| 1479 |
} |
| 1480 |
MOZ_ASSERT(unwrappedTypedArray->type() == Scalar::Int32 || |
| 1481 |
unwrappedTypedArray->type() == Scalar::BigInt64); |
| 1482 |
|
| 1483 |
// Step 2. |
| 1484 |
size_t intIndex; |
| 1485 |
if (!ValidateAtomicAccess(cx, unwrappedTypedArray, index, &intIndex)) { |
| 1486 |
return false; |
| 1487 |
} |
| 1488 |
|
| 1489 |
// Steps 3-4. |
| 1490 |
int64_t count; |
| 1491 |
if (countv.isUndefined()) { |
| 1492 |
count = -1; |
| 1493 |
} else { |
| 1494 |
double dcount; |
| 1495 |
if (!ToInteger(cx, countv, &dcount)) { |
| 1496 |
return false; |
| 1497 |
} |
| 1498 |
if (dcount < 0.0) { |
| 1499 |
dcount = 0.0; |
| 1500 |
} |
| 1501 |
count = dcount < double(1ULL << 63) ? int64_t(dcount) : -1; |
| 1502 |
} |
| 1503 |
|
| 1504 |
// https://github.com/tc39/ecma262/pull/1908 |
| 1505 |
if (!unwrappedTypedArray->isSharedMemory()) { |
| 1506 |
r.setInt32(0); |
| 1507 |
return true; |
| 1508 |
} |
| 1509 |
|
| 1510 |
// Step 5. |
| 1511 |
Rooted<SharedArrayBufferObject*> unwrappedSab( |
| 1512 |
cx, unwrappedTypedArray->bufferShared()); |
| 1513 |
|
| 1514 |
// Step 6. |
| 1515 |
mozilla::Maybe<size_t> offset = unwrappedTypedArray->byteOffset(); |
| 1516 |
MOZ_ASSERT( |
| 1517 |
offset, |
| 1518 |
"offset can't become invalid because shared buffers can only grow"); |
| 1519 |
|
| 1520 |
// Steps 7-9. |
| 1521 |
// The computation will not overflow because range checks have been |
| 1522 |
// performed. |
| 1523 |
size_t elementSize = Scalar::byteSize(unwrappedTypedArray->type()); |
| 1524 |
size_t indexedPosition = intIndex * elementSize + *offset; |
| 1525 |
|
| 1526 |
// Steps 10-16. |
| 1527 |
|
| 1528 |
int64_t woken = 0; |
| 1529 |
if (!atomics_notify_impl(cx, unwrappedSab->rawBufferObject(), indexedPosition, |
| 1530 |
count, &woken)) { |
| 1531 |
return false; |
| 1532 |
} |
| 1533 |
|
| 1534 |
r.setNumber(double(woken)); |
| 1535 |
|
| 1536 |
return true; |
| 1537 |
} |
| 1538 |
|
| 1539 |
/** |
| 1540 |
* Atomics.pause ( [ N ] ) |
| 1541 |
* |
| 1542 |
* https://tc39.es/proposal-atomics-microwait/ |
| 1543 |
*/ |
| 1544 |
static bool atomics_pause(JSContext* cx, unsigned argc, Value* vp) { |
| 1545 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1546 |
|
| 1547 |
// Step 1. |
| 1548 |
if (args.hasDefined(0)) { |
| 1549 |
if (!args[0].isNumber() || !IsInteger(args[0].toNumber())) { |
| 1550 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 1551 |
JSMSG_ATOMICS_PAUSE_BAD_COUNT); |
| 1552 |
return false; |
| 1553 |
} |
| 1554 |
} |
| 1555 |
|
| 1556 |
// Step 2. |
| 1557 |
// |
| 1558 |
// We ignore the iteration count when not inlining this operation. |
| 1559 |
jit::AtomicOperations::pause(); |
| 1560 |
|
| 1561 |
// Step 3. |
| 1562 |
args.rval().setUndefined(); |
| 1563 |
return true; |
| 1564 |
} |
| 1565 |
|
| 1566 |
/* static */ |
| 1567 |
bool js::FutexThread::initialize() { |
| 1568 |
MOZ_ASSERT(!lock_); |
| 1569 |
lock_ = js_new<js::Mutex>(mutexid::FutexThread); |
| 1570 |
return lock_ != nullptr; |
| 1571 |
} |
| 1572 |
|
| 1573 |
/* static */ |
| 1574 |
void js::FutexThread::destroy() { |
| 1575 |
if (lock_) { |
| 1576 |
js::Mutex* lock = lock_; |
| 1577 |
js_delete(lock); |
| 1578 |
lock_ = nullptr; |
| 1579 |
} |
| 1580 |
} |
| 1581 |
|
| 1582 |
/* static */ |
| 1583 |
void js::FutexThread::lock() { |
| 1584 |
// Load the atomic pointer. |
| 1585 |
js::Mutex* lock = lock_; |
| 1586 |
|
| 1587 |
lock->lock(); |
| 1588 |
} |
| 1589 |
|
| 1590 |
/* static */ mozilla::Atomic<js::Mutex*, mozilla::SequentiallyConsistent> |
| 1591 |
FutexThread::lock_; |
| 1592 |
|
| 1593 |
/* static */ |
| 1594 |
void js::FutexThread::unlock() { |
| 1595 |
// Load the atomic pointer. |
| 1596 |
js::Mutex* lock = lock_; |
| 1597 |
|
| 1598 |
lock->unlock(); |
| 1599 |
} |
| 1600 |
|
| 1601 |
js::FutexThread::FutexThread() |
| 1602 |
: cond_(nullptr), state_(Idle), canWait_(false) {} |
| 1603 |
|
| 1604 |
bool js::FutexThread::initInstance() { |
| 1605 |
MOZ_ASSERT(lock_); |
| 1606 |
cond_ = js_new<js::ConditionVariable>(); |
| 1607 |
return cond_ != nullptr; |
| 1608 |
} |
| 1609 |
|
| 1610 |
void js::FutexThread::destroyInstance() { |
| 1611 |
if (cond_) { |
| 1612 |
js_delete(cond_); |
| 1613 |
} |
| 1614 |
} |
| 1615 |
|
| 1616 |
bool js::FutexThread::isWaiting() { |
| 1617 |
// When a worker is awoken for an interrupt it goes into state |
| 1618 |
// WaitingNotifiedForInterrupt for a short time before it actually |
| 1619 |
// wakes up and goes into WaitingInterrupted. In those states the |
| 1620 |
// worker is still waiting, and if an explicit notify arrives the |
| 1621 |
// worker transitions to Woken. See further comments in |
| 1622 |
// FutexThread::wait(). |
| 1623 |
return state_ == Waiting || state_ == WaitingInterrupted || |
| 1624 |
state_ == WaitingNotifiedForInterrupt; |
| 1625 |
} |
| 1626 |
|
| 1627 |
FutexThread::WaitResult js::FutexThread::wait( |
| 1628 |
JSContext* cx, js::UniqueLock<js::Mutex>& locked, |
| 1629 |
const mozilla::Maybe<mozilla::TimeDuration>& timeout) { |
| 1630 |
MOZ_ASSERT(&cx->fx == this); |
| 1631 |
MOZ_ASSERT(cx->fx.canWait()); |
| 1632 |
MOZ_ASSERT(state_ == Idle || state_ == WaitingInterrupted); |
| 1633 |
|
| 1634 |
// Disallow waiting when a runtime is processing an interrupt. |
| 1635 |
// See explanation below. |
| 1636 |
|
| 1637 |
if (state_ == WaitingInterrupted) { |
| 1638 |
UnlockGuard unlock(locked); |
| 1639 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 1640 |
JSMSG_ATOMICS_WAIT_NOT_ALLOWED); |
| 1641 |
return WaitResult::Error; |
| 1642 |
} |
| 1643 |
|
| 1644 |
// Go back to Idle after returning. |
| 1645 |
auto onFinish = mozilla::MakeScopeExit([&] { state_ = Idle; }); |
| 1646 |
|
| 1647 |
const bool isTimed = timeout.isSome(); |
| 1648 |
|
| 1649 |
auto finalEnd = timeout.map([](const mozilla::TimeDuration& timeout) { |
| 1650 |
return mozilla::TimeStamp::Now() + timeout; |
| 1651 |
}); |
| 1652 |
|
| 1653 |
// 4000s is about the longest timeout slice that is guaranteed to |
| 1654 |
// work cross-platform. |
| 1655 |
auto maxSlice = mozilla::TimeDuration::FromSeconds(4000.0); |
| 1656 |
|
| 1657 |
for (;;) { |
| 1658 |
// If we are doing a timed wait, calculate the end time for this wait |
| 1659 |
// slice. |
| 1660 |
auto sliceEnd = finalEnd.map([&](mozilla::TimeStamp& finalEnd) { |
| 1661 |
auto sliceEnd = mozilla::TimeStamp::Now() + maxSlice; |
| 1662 |
if (finalEnd < sliceEnd) { |
| 1663 |
sliceEnd = finalEnd; |
| 1664 |
} |
| 1665 |
return sliceEnd; |
| 1666 |
}); |
| 1667 |
|
| 1668 |
state_ = Waiting; |
| 1669 |
|
| 1670 |
MOZ_ASSERT((cx->runtime()->beforeWaitCallback == nullptr) == |
| 1671 |
(cx->runtime()->afterWaitCallback == nullptr)); |
| 1672 |
mozilla::DebugOnly<bool> callbacksPresent = |
| 1673 |
cx->runtime()->beforeWaitCallback != nullptr; |
| 1674 |
|
| 1675 |
void* cookie = nullptr; |
| 1676 |
uint8_t clientMemory[JS::WAIT_CALLBACK_CLIENT_MAXMEM]; |
| 1677 |
if (cx->runtime()->beforeWaitCallback) { |
| 1678 |
cookie = (*cx->runtime()->beforeWaitCallback)(clientMemory); |
| 1679 |
} |
| 1680 |
|
| 1681 |
if (isTimed) { |
| 1682 |
(void)cond_->wait_until(locked, *sliceEnd); |
| 1683 |
} else { |
| 1684 |
cond_->wait(locked); |
| 1685 |
} |
| 1686 |
|
| 1687 |
MOZ_ASSERT((cx->runtime()->afterWaitCallback != nullptr) == |
| 1688 |
callbacksPresent); |
| 1689 |
if (cx->runtime()->afterWaitCallback) { |
| 1690 |
(*cx->runtime()->afterWaitCallback)(cookie); |
| 1691 |
} |
| 1692 |
|
| 1693 |
switch (state_) { |
| 1694 |
case FutexThread::Waiting: |
| 1695 |
// Timeout or spurious wakeup. |
| 1696 |
if (isTimed) { |
| 1697 |
auto now = mozilla::TimeStamp::Now(); |
| 1698 |
if (now >= *finalEnd) { |
| 1699 |
return WaitResult::TimedOut; |
| 1700 |
} |
| 1701 |
} |
| 1702 |
break; |
| 1703 |
|
| 1704 |
case FutexThread::Woken: |
| 1705 |
return WaitResult::OK; |
| 1706 |
|
| 1707 |
case FutexThread::WaitingNotifiedForInterrupt: |
| 1708 |
// The interrupt handler may reenter the engine. In that case |
| 1709 |
// there are two complications: |
| 1710 |
// |
| 1711 |
// - The waiting thread is not actually waiting on the |
| 1712 |
// condition variable so we have to record that it |
| 1713 |
// should be woken when the interrupt handler returns. |
| 1714 |
// To that end, we flag the thread as interrupted around |
| 1715 |
// the interrupt and check state_ when the interrupt |
| 1716 |
// handler returns. A notify() call that reaches the |
| 1717 |
// runtime during the interrupt sets state_ to Woken. |
| 1718 |
// |
| 1719 |
// - It is in principle possible for wait() to be |
| 1720 |
// reentered on the same thread/runtime and waiting on the |
| 1721 |
// same location and to yet again be interrupted and enter |
| 1722 |
// the interrupt handler. In this case, it is important |
| 1723 |
// that when another agent notifies waiters, all waiters using |
| 1724 |
// the same runtime on the same location are woken in LIFO |
| 1725 |
// order; FIFO may be the required order, but FIFO would |
| 1726 |
// fail to wake up the innermost call. Interrupts are |
| 1727 |
// outside any spec anyway. Also, several such suspended |
| 1728 |
// waiters may be woken at a time. |
| 1729 |
// |
| 1730 |
// For the time being we disallow waiting from within code |
| 1731 |
// that runs from within an interrupt handler; this may |
| 1732 |
// occasionally (very rarely) be surprising but is |
| 1733 |
// expedient. Other solutions exist, see bug #1131943. The |
| 1734 |
// code that performs the check is above, at the head of |
| 1735 |
// this function. |
| 1736 |
|
| 1737 |
state_ = WaitingInterrupted; |
| 1738 |
{ |
| 1739 |
UnlockGuard unlock(locked); |
| 1740 |
if (!cx->handleInterrupt()) { |
| 1741 |
return WaitResult::Error; |
| 1742 |
} |
| 1743 |
} |
| 1744 |
if (state_ == Woken) { |
| 1745 |
return WaitResult::OK; |
| 1746 |
} |
| 1747 |
break; |
| 1748 |
|
| 1749 |
default: |
| 1750 |
MOZ_CRASH("Bad FutexState in wait()"); |
| 1751 |
} |
| 1752 |
} |
| 1753 |
} |
| 1754 |
|
| 1755 |
void js::FutexThread::notify(NotifyReason reason) { |
| 1756 |
MOZ_ASSERT(isWaiting()); |
| 1757 |
|
| 1758 |
if ((state_ == WaitingInterrupted || state_ == WaitingNotifiedForInterrupt) && |
| 1759 |
reason == NotifyExplicit) { |
| 1760 |
state_ = Woken; |
| 1761 |
return; |
| 1762 |
} |
| 1763 |
switch (reason) { |
| 1764 |
case NotifyExplicit: |
| 1765 |
state_ = Woken; |
| 1766 |
break; |
| 1767 |
case NotifyForJSInterrupt: |
| 1768 |
if (state_ == WaitingNotifiedForInterrupt) { |
| 1769 |
return; |
| 1770 |
} |
| 1771 |
state_ = WaitingNotifiedForInterrupt; |
| 1772 |
break; |
| 1773 |
default: |
| 1774 |
MOZ_CRASH("bad NotifyReason in FutexThread::notify()"); |
| 1775 |
} |
| 1776 |
cond_->notify_all(); |
| 1777 |
} |
| 1778 |
|
| 1779 |
const JSFunctionSpec AtomicsMethods[] = { |
| 1780 |
JS_INLINABLE_FN("compareExchange", atomics_compareExchange, 4, 0, |
| 1781 |
AtomicsCompareExchange), |
| 1782 |
JS_INLINABLE_FN("load", atomics_load, 2, 0, AtomicsLoad), |
| 1783 |
JS_INLINABLE_FN("store", atomics_store, 3, 0, AtomicsStore), |
| 1784 |
JS_INLINABLE_FN("exchange", atomics_exchange, 3, 0, AtomicsExchange), |
| 1785 |
JS_INLINABLE_FN("add", atomics_add, 3, 0, AtomicsAdd), |
| 1786 |
JS_INLINABLE_FN("sub", atomics_sub, 3, 0, AtomicsSub), |
| 1787 |
JS_INLINABLE_FN("and", atomics_and, 3, 0, AtomicsAnd), |
| 1788 |
JS_INLINABLE_FN("or", atomics_or, 3, 0, AtomicsOr), |
| 1789 |
JS_INLINABLE_FN("xor", atomics_xor, 3, 0, AtomicsXor), |
| 1790 |
JS_INLINABLE_FN("isLockFree", atomics_isLockFree, 1, 0, AtomicsIsLockFree), |
| 1791 |
JS_FN("wait", atomics_wait, 4, 0), |
| 1792 |
JS_FN("waitAsync", atomics_wait_async, 4, 0), |
| 1793 |
JS_FN("notify", atomics_notify, 3, 0), |
| 1794 |
JS_FN("wake", atomics_notify, 3, 0), // Legacy name |
| 1795 |
JS_INLINABLE_FN("pause", atomics_pause, 0, 0, AtomicsPause), |
| 1796 |
JS_FS_END, |
| 1797 |
}; |
| 1798 |
|
| 1799 |
static const JSPropertySpec AtomicsProperties[] = { |
| 1800 |
JS_STRING_SYM_PS(toStringTag, "Atomics", JSPROP_READONLY), |
| 1801 |
JS_PS_END, |
| 1802 |
}; |
| 1803 |
|
| 1804 |
static JSObject* CreateAtomicsObject(JSContext* cx, JSProtoKey key) { |
| 1805 |
RootedObject proto(cx, &cx->global()->getObjectPrototype()); |
| 1806 |
return NewTenuredObjectWithGivenProto(cx, &AtomicsObject::class_, proto); |
| 1807 |
} |
| 1808 |
|
| 1809 |
static const ClassSpec AtomicsClassSpec = { |
| 1810 |
CreateAtomicsObject, |
| 1811 |
nullptr, |
| 1812 |
AtomicsMethods, |
| 1813 |
AtomicsProperties, |
| 1814 |
}; |
| 1815 |
|
| 1816 |
const JSClass AtomicsObject::class_ = { |
| 1817 |
"Atomics", |
| 1818 |
JSCLASS_HAS_CACHED_PROTO(JSProto_Atomics), |
| 1819 |
JS_NULL_CLASS_OPS, |
| 1820 |
&AtomicsClassSpec, |
| 1821 |
}; |