forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathThreadAtomics.cpp
More file actions
1825 lines (1725 loc) · 92.5 KB
/
Copy pathThreadAtomics.cpp
File metadata and controls
1825 lines (1725 loc) · 92.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2026 Oven, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ThreadAtomics.h"
#include "LockObject.h"
#include "ArrayStorage.h"
#include "JSCInlines.h"
#include "JSLock.h"
#include "JSPromise.h"
#include "ObjectConstructor.h"
#include "SparseArrayValueMap.h"
#include "ThreadManager.h"
#include "ThreadObject.h"
#include "VMLite.h" // UNGIL §J.3 (U-T11): the spawned park lite is the CURRENT lite (TERM1 rule 4).
#include <wtf/HashSet.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/RunLoop.h>
#include <wtf/Scope.h>
namespace JSC {
// UNGIL same-library seams (U-T11; the currentThreadHoldsEntryToken pattern —
// redeclared here, not in any header, matching WaiterListManager.cpp): the
// §A.2.4 rule-4 PARK-LITE D9 poll predicates (VMTraps.cpp), the §J.3
// captured-lite record (JSLock.cpp), and the annex-W W1 parked-carrier
// watchdog service episode (JSLock.cpp).
bool parkLitePollTerminationRequested(VM&, VMLite* parkLite);
bool parkLitePollWatchdogCheckRequested(VM&, VMLite* parkLite);
VMLite* capturedParkLiteOfCurrentThreadIfAny(VM&);
bool reacquireParkedCarrierAndServiceWatchdogCheck(VM&);
// ---------------- S2-parallel-cpu-waste instrumentation ----------------
//
// Process-wide property-Atomics RMW retry counters (declared in
// ThreadAtomics.h). Bumped only under Options::logJSLockContention() so the
// off-option / flag-off path is one predicted-not-taken branch. The bench
// (Tools/threads/scalebench/js/bench.js) does Atomics.add(counters, '…', 1)
// on a SINGLE shared object every doc/query; at W=16 that is ~W writers on
// the same inline slot. The CAS-retry burn for that shape lives INSIDE
// atomicSlotLockFreeLoop (ConcurrentButterfly.cpp), which loops internally on
// CAS failure and never escapes Restart — so g_threadAtomicsRMWRestarts here
// captures STRUCTURAL restarts only, and g_threadAtomicsSlotCASRetries is
// the hook for that loop's fall-through-and-retry arm — DEFINED here,
// INCREMENTED THERE (one-liner, owned by the ConcurrentButterfly implementer
// slot; reads 0 until landed). dumpThreadAtomicsRMWStats() is called from
// LockObject.cpp's atexit dump so both halves of the S2 instrumentation
// report together.
std::atomic<uint64_t> g_threadAtomicsRMWCalls { 0 };
std::atomic<uint64_t> g_threadAtomicsRMWRestarts { 0 };
std::atomic<uint64_t> g_threadAtomicsSlotCASRetries { 0 };
void dumpThreadAtomicsRMWStats()
{
uint64_t calls = g_threadAtomicsRMWCalls.load(std::memory_order_relaxed);
uint64_t restarts = g_threadAtomicsRMWRestarts.load(std::memory_order_relaxed);
uint64_t casRetries = g_threadAtomicsSlotCASRetries.load(std::memory_order_relaxed);
dataLogLn("[logJSLockContention] ThreadAtomics property-RMW: calls=", calls,
" outerRestarts=", restarts,
" slotCASRetries=", casRetries,
casRetries ? "" : " (slotCASRetries hook not yet wired in ConcurrentButterfly.cpp::atomicSlotLockFreeLoop)");
}
// ---------------- own-data-property helpers ----------------
enum class OwnPropertyKind : uint8_t { Missing, Data, Accessor };
#if USE(JSVALUE64)
// I5 fix - SPEC-ungil ANNEX C1 third arm / OM SPEC-objectmodel ANNEX Q (I31):
// flag-on, the quickly-family deliberately answers FALSE for every
// ArrayStorage shape so generic callers fall to the E5 / 4.6 cell-locked
// path. For Atomics property ops that "not lock-free-quickly readable" must
// NOT be conflated with "not a plain data property": an in-vector, non-hole
// AS element with no sparse map is exactly the slot the 9.5 locked AS arm
// (atomicSlotReadModifyWriteAtIndex's hasAnyArrayStorage arm,
// ConcurrentButterfly.cpp) operates on. Probe it under the cell lock,
// mirroring that arm's gates VERBATIM (m_sparseMap || index >= vectorLength
// || index >= length => NotPlain; empty slot => Hole) so a probe that
// classifies Data can never hand the accessor a persistently-Restarting slot
// (livelock). butterfly() is legal here per the 9.5 accessor contract: AS
// never segments (I31), and the shape is re-checked under the lock.
// Read-only - never allocates or parks under the cell lock (OM I20); the SW
// pre-lock protocol is the WRITE side's job and stays inside the 9.5
// accessor. NOTE: this is a cell-lock site OUTSIDE ConcurrentButterfly.cpp,
// so it is unobserved by the TU-private O3 depth witness
// (t_cellLocksHeldByConcurrentButterfly); its obligation (no allocation, no
// park, no safepoint under the lock) must be preserved by future edits.
enum class ArrayStorageElementProbe : uint8_t { NotArrayStorage, Plain, Hole, NotPlain };
static ArrayStorageElementProbe probeArrayStorageElementForAtomics(JSObject* object, uint32_t index, JSValue& value)
{
ASSERT(Options::useJSThreads());
if (!hasAnyArrayStorage(object->indexingType()))
return ArrayStorageElementProbe::NotArrayStorage;
Locker locker { object->cellLock() }; // I31/L5: every flag-on runtime AS access is cell-locked, reads included.
if (!hasAnyArrayStorage(object->indexingType())) // Shape moved before the lock landed: caller re-classifies.
return ArrayStorageElementProbe::NotArrayStorage;
ArrayStorage* storage = object->butterfly()->arrayStorage();
if (storage->m_sparseMap || index >= storage->vectorLength() || index >= storage->length())
return ArrayStorageElementProbe::NotPlain; // Sparse/out-of-bounds: exotic, matches the locked arm's reject.
JSValue stored = storage->m_vector[index].get();
if (!stored)
return ArrayStorageElementProbe::Hole;
value = stored;
return ArrayStorageElementProbe::Plain;
}
#endif // USE(JSVALUE64)
// Returns Missing with an exception pending for the two rejected receiver
// classes (see the 4.5 atomicity comment below); every caller
// RETURN_IF_EXCEPTIONs immediately after this call, so a gated receiver can
// never fall into a Missing-create path.
static OwnPropertyKind getOwnPropertyForAtomics(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue& value, unsigned& attributes)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// Gate 1: reentrant receivers. After this check, the method-table probe
// below runs no user JS (other exotic getOwnPropertySlot implementations
// may reify lazy properties or allocate, but never call out to JS), and
// atomicsStoreOnProperty's isExtensible() is a plain structure-flag read.
if (object->type() == ProxyObjectType || object->type() == GlobalProxyType) [[unlikely]] {
throwTypeError(globalObject, scope, "Atomics property operations cannot be performed on a Proxy"_s);
return OwnPropertyKind::Missing;
}
PropertySlot slot(object, PropertySlot::InternalMethodType::GetOwnProperty);
bool hasProperty = object->methodTable()->getOwnPropertySlot(object, globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, OwnPropertyKind::Missing);
if (!hasProperty)
return OwnPropertyKind::Missing;
attributes = slot.attributes();
if (!slot.isValue())
return OwnPropertyKind::Accessor;
// Gate 2: the own data property must be plain structure/butterfly
// storage, so the read here and the later putDirect/putDirectIndex hit
// the SAME slot. The probe above may have reified a lazy property (e.g.
// function name/length), so the re-validation runs after it on purpose.
if (std::optional<uint32_t> index = parseIndex(propertyName)) {
if (!object->canGetIndexQuickly(index.value())) [[unlikely]] {
#if USE(JSVALUE64)
// I5 fix: flag-on, AS shapes answer "not quickly" BY DESIGN (OM
// ANNEX Q/I31) so generic callers fall to cell-locked access -
// that is not "not a plain data property". Probe the locked AS
// arm's slot; under the GIL the read below and the later
// putDirectIndex (which routes through the I31-locked generic
// path flag-on) remain one atomic step. The Hole arm is
// unreachable here (no GIL drop between getOwnPropertySlot and
// this probe), so any non-Plain result falls to the TypeError.
if (Options::useJSThreads()) {
JSValue stored;
if (probeArrayStorageElementForAtomics(object, index.value(), stored) == ArrayStorageElementProbe::Plain) {
value = stored;
attributes = 0; // In-vector AS elements are writable/enumerable/configurable.
return OwnPropertyKind::Data;
}
}
#endif
throwTypeError(globalObject, scope, "Atomics property operations require a plain data property"_s);
return OwnPropertyKind::Missing;
}
value = object->getIndexQuickly(index.value());
attributes = 0; // Butterfly elements are writable/enumerable/configurable.
return OwnPropertyKind::Data;
}
unsigned structureAttributes = 0;
PropertyOffset offset = object->structure()->get(vm, propertyName, structureAttributes);
if (!isValidOffset(offset)) [[unlikely]] {
throwTypeError(globalObject, scope, "Atomics property operations require a plain data property"_s);
return OwnPropertyKind::Missing;
}
attributes = structureAttributes;
value = object->getDirect(offset);
return OwnPropertyKind::Data;
}
static bool sameValueZeroForAtomics(JSGlobalObject* globalObject, JSValue a, JSValue b)
{
if (a.isNumber() && b.isNumber()) {
double x = a.asNumber();
double y = b.asNumber();
if (std::isnan(x) && std::isnan(y))
return true;
return x == y;
}
return sameValue(globalObject, a, b);
}
// SPEC-api 4.5: every property op is "one atomic step". Under the phase-1 GIL
// that holds only if NO user JS can run between the own-property read and the
// write below (operand coercions happen before the read). Two receiver
// classes would break that mechanically, so getOwnPropertyForAtomics rejects
// them with TypeError up front (landed deviation; rationale recorded in
// docs/threads/INTEGRATE-api.md "Landed deviations" — the frozen 4.5 table
// does not enumerate exotic receivers):
//
// 1. Reentrant receivers — ProxyObject / JSGlobalProxy: their
// getOwnPropertySlot (and isExtensible) run arbitrary trap JS, which can
// reach a GIL-dropping park site (join, cond.wait, contended lock.hold,
// property Atomics.wait) mid-step; another thread could then mutate the
// property between a CAS/RMW's read and its write — a cross-thread TOCTOU
// that would falsify the advertised CAS atomicity.
//
// 2. Exotic own data properties not backed by plain structure/butterfly
// storage — e.g. JSArray "length", RegExpObject "lastIndex", StringObject
// indexed chars, sparse-map indices, global var-scope bindings: the method
// table reports them as own data properties, but putDirect/putDirectIndex
// would install a DUPLICATE shadow property next to the exotic one (an
// object state no sequential JS program can create, violating THREAD.md's
// indistinguishable-heap requirement).
//
// After these gates the read is a non-reentrant structure/butterfly probe and
// the write targets exactly the probed slot. Post-GIL these bodies re-home
// onto the object-model atomic slot CAS/RMW helpers (OM §9.5) per Deviation
// 12; the §7 signatures are frozen so only the bodies change.
// THREADS-INTEGRATE(api): Dev 12 re-freeze point (atomic slot CAS/RMW).
// THREADS-INTEGRATE(ungil): U-T10 LANDED the re-home - GIL-off the four value
// ops dispatch to the *GilOff bodies below (SPEC-ungil ANNEX C1 accessors in
// ConcurrentButterfly.cpp); GIL-on keeps the bodies in this section verbatim.
// Writes an EXISTING own data property's value, preserving its attributes.
// putDirect/putDirectMayBeIndex default to attributes 0, and putDirectInternal
// (PutModeDefineOwnProperty) performs an attribute-change Structure transition
// whenever newAttributes != currentAttributes — which would silently strip
// DontEnum/DontDelete/ReadOnly. 4.5 ops only ever change the value.
static void putExistingOwnDataPropertyForAtomics(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue value, unsigned attributes)
{
unsigned preservedAttributes = attributes & (PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum | PropertyAttribute::DontDelete);
if (std::optional<uint32_t> index = parseIndex(propertyName)) {
object->putDirectIndex(globalObject, index.value(), value, preservedAttributes, PutDirectIndexLikePutDirect);
return;
}
object->putDirect(globalObject->vm(), propertyName, value, preservedAttributes);
}
#if USE(JSVALUE64)
// ---------------- GIL-off re-home (SPEC-ungil §C.1/§C.2, U-T10) ----------------
//
// GIL-off (vm.gilOff()), the VM lock no longer serializes mutators, so the
// "one atomic step" bodies above are re-homed onto the OM §9.5 atomic slot
// accessors (ANNEX C1): probe -> accessor -> status dispatch, looping on
// Restart (the accessor re-validates structure/shape/offset provenance and
// runs the write-side SW protocols internally; restarts are I33-bounded by
// the forward-only shape order, plus the same adversarial-progress caveat as
// the §C.3(b) dequeue-and-restart class). CARRIED across the re-home (§C.2):
// - D3 exotic-receiver TypeErrors: the probe below keeps the GIL probe's
// Proxy/GlobalProxy gate and plain-slot gates, messages identical;
// - D7 writability inside the atomic body: probe-time ReadOnly TypeErrors
// here, re-validated in the accessor's locked arm (Restart on mismatch -
// the fresh probe then throws).
// GIL-on (and flag-off) keeps the bodies above byte-for-byte: every gilOff
// branch below is unreachable there (U19 oracle; SD4-class deltas are owned
// by U-T11, not this file's value ops).
//
// Store's Missing arm stays on the OM's generic ADD machinery - a fresh-
// property ADD is a structure/shape transition and §9.5 accessors only cover
// EXISTING slots - but BOTH legs are conditional adds now
// (putDirectForAtomicsMissingAdd / putDirectIndexForAtomicsMissingAdd): a
// lost race restarts the probe instead of clobbering a racer's descriptor.
struct ConcurrentAtomicsProbe {
OwnPropertyKind kind { OwnPropertyKind::Missing };
unsigned attributes { 0 };
std::optional<uint32_t> index;
PropertyOffset offset { invalidOffset };
StructureID structureID;
// I5 fix amendment: getOwnPropertySlot saw a value but the cell-locked AS
// probe then saw a hole (racing delete/shrink). No sequential
// interleaving yields a "plain data property" TypeError there - the
// caller's outer loop must re-probe, and the fresh getOwnPropertySlot
// classifies Missing (store ADDS, load throws its precise "no own
// property" error). Progress: each restart requires an external mutation
// in the window - the same bounded-adversarial class as C.3(b).
bool restart { false };
};
// GIL-off twin of getOwnPropertyForAtomics: same gates, same TypeError
// messages, but resolves the named offset with the lock-free walker
// (Structure::getConcurrently - Structure::get(VM&) may materialize the
// property table, a GIL-on-only luxury) and records {offset, structureID}
// provenance for the accessor's I34 validation instead of reading the value
// here (the accessor's seq_cst load is the read that counts).
static ConcurrentAtomicsProbe probeOwnPropertyForAtomicsConcurrent(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
ConcurrentAtomicsProbe probe;
// Gate 1 (D3): reentrant receivers.
if (object->type() == ProxyObjectType || object->type() == GlobalProxyType) [[unlikely]] {
throwTypeError(globalObject, scope, "Atomics property operations cannot be performed on a Proxy"_s);
return probe;
}
PropertySlot slot(object, PropertySlot::InternalMethodType::GetOwnProperty);
bool hasProperty = object->methodTable()->getOwnPropertySlot(object, globalObject, propertyName, slot);
RETURN_IF_EXCEPTION(scope, probe);
if (!hasProperty)
return probe;
probe.attributes = slot.attributes();
if (!slot.isValue()) {
probe.kind = OwnPropertyKind::Accessor;
return probe;
}
// Gate 2 (D3): plain structure/butterfly storage only. §C.2 routes
// parseIndex hits to the indexed accessor (one arm per shape, 8g).
if (std::optional<uint32_t> index = parseIndex(propertyName)) {
if (!object->canGetIndexQuickly(index.value())) [[unlikely]] {
// I5 fix (ANNEX C1: "ArrayStorage/dict-indexed - third arm; C.2
// routes parseIndex hits here"): classify the locked AS arm's
// slots as Data so dispatchAtomicSlotRequest reaches
// atomicSlot*AtIndex's cell-locked arm. The probe mirrors that
// arm's gates EXACTLY (sparse map / out-of-bounds => TypeError
// here; hole => restart, see the struct comment), so kind=Data
// can never feed the accessor a persistently-Restarting slot.
// Race shape: this probe and the accessor take the cell lock
// SEPARATELY - if thread B mutates between them (shrink, delete,
// sparse conversion, AS->flat shape move), the accessor's
// under-lock re-checks report Restart and the NEXT probe
// re-classifies on fresh state (succeeds or throws); an
// adversarial add/delete flip-flop is the same
// bounded-adversarial-progress class as C.3(b)'s
// dequeue-and-restart. The write-side SW=0 foreign pre-lock
// protocol stays inside the accessor (AS PRE-LOCK, r8 item 6).
JSValue ignoredValue;
switch (probeArrayStorageElementForAtomics(object, index.value(), ignoredValue)) {
case ArrayStorageElementProbe::Plain:
probe.index = index;
probe.attributes = 0; // In-vector AS elements are writable/enumerable/configurable.
probe.kind = OwnPropertyKind::Data;
return probe;
case ArrayStorageElementProbe::Hole:
probe.restart = true;
return probe;
case ArrayStorageElementProbe::NotArrayStorage:
case ArrayStorageElementProbe::NotPlain:
break;
}
throwTypeError(globalObject, scope, "Atomics property operations require a plain data property"_s);
return probe;
}
probe.index = index;
probe.attributes = 0; // Butterfly elements are writable/enumerable/configurable.
probe.kind = OwnPropertyKind::Data;
return probe;
}
Structure* structure = object->structure();
unsigned structureAttributes = 0;
PropertyOffset offset = structure->getConcurrently(propertyName.uid(), structureAttributes);
if (!isValidOffset(offset)) [[unlikely]] {
throwTypeError(globalObject, scope, "Atomics property operations require a plain data property"_s);
return probe;
}
// U-T10 amend: the accessor-ness decision above was made against the
// structure the methodTable walk saw; THIS structure (re-read after it)
// is the one whose {offset, structureID} provenance the §9.5 accessor
// validates (I34). A racing data->accessor reconfiguration between the
// two reads would otherwise hand the LOCK-FREE arm a kind=Data probe
// whose structureID check PASSES while the slot holds a GetterSetter -
// an Exchange/RMW would CAS a primitive over it (type confusion). Reject
// non-plain attributes against the SAME structure the provenance is
// taken from, mirroring the third arm's under-lock re-check; this also
// keeps CustomValue slots (which can answer slot.isValue()) out of the
// lock-free arms, per ANNEX C1's "plain ... own NAMED data slots only".
if (structureAttributes & (PropertyAttribute::Accessor | PropertyAttribute::CustomAccessor | PropertyAttribute::CustomValue)) [[unlikely]] {
probe.attributes = structureAttributes;
probe.kind = OwnPropertyKind::Accessor;
return probe;
}
probe.attributes = structureAttributes;
probe.offset = offset;
probe.structureID = structure->id();
probe.kind = OwnPropertyKind::Data;
return probe;
}
static ALWAYS_INLINE JSValue dispatchAtomicSlotRequest(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, const ConcurrentAtomicsProbe& probe, const AtomicSlotRequest& request, AtomicSlotStatus& status)
{
if (probe.index)
return object->atomicSlotReadModifyWriteAtIndex(globalObject, probe.index.value(), request, status);
return object->atomicSlotReadModifyWrite(globalObject, propertyName.uid(), probe.offset, probe.structureID, request, status);
}
static JSValue atomicsLoadOnPropertyGilOff(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
while (true) {
auto probe = probeOwnPropertyForAtomicsConcurrent(globalObject, object, propertyName);
RETURN_IF_EXCEPTION(scope, { });
if (probe.restart) [[unlikely]] // I5 fix amendment: racing delete/shrink made a hole; re-probe on fresh state.
continue;
if (probe.kind != OwnPropertyKind::Data) {
throwTypeError(globalObject, scope, "Atomics.load: object has no own property"_s);
return { };
}
AtomicSlotRequest request; // operation = Load
AtomicSlotStatus status = AtomicSlotStatus::Restart;
JSValue result = dispatchAtomicSlotRequest(globalObject, object, propertyName, probe, request, status);
if (status == AtomicSlotStatus::Applied)
return result;
ASSERT(status == AtomicSlotStatus::Restart);
}
}
// ---------------- §C.2 Missing arm, INDEXED conditional add ----------------
//
// Receiver gate: the fast-put classes whose attribute-0 indexed adds the
// loop below models. Replica of JSObject.cpp's TU-private
// canDoFastPutDirectIndex, with two deliberate deltas:
// - NO arguments-type admission (review round 2 (b)): Direct/Scoped
// Arguments index their own mapped storage, not the shapes the loop
// models; they keep the generic path (today's behavior, no new risk).
// - NO inSparseIndexingMode()/CoW exclusion: a sparse-mode receiver's map
// is exactly what the conditional add handles (the generic
// defineOwnProperty leg it would otherwise take re-opens the descriptor
// clobber through defineOwnIndexedProperty's reconfiguration arm), and
// CoW words are materialized by the loop itself.
static bool canUseConditionalIndexedMissingAdd(JSObject* object)
{
return (isJSArray(object) || is<JSFinalObject>(object)) && !TypeInfo::isArgumentsType(object->type());
}
// U-T10 amend: the INDEXED twin of putDirectForAtomicsMissingAdd - closes the
// KNOWN RESIDUAL previously recorded at the Missing-arm call site below
// (INTEGRATE-ungil, U-T10 amend item 3). The old leg called putDirectIndex
// verbatim; its ArrayStorage terminal (SparseArrayValueMap::putDirect,
// LikePutDirect) force-sets an EXISTING sparse entry to a plain attributes-0
// data property, silently clobbering a racing indexed defineProperty's
// accessor / non-writable descriptor (MC-PRIM P4 / MC-REENT S3c).
//
// Contract (same as the named helper): null on success; non-null = LOST RACE
// - the caller restarts, and the fresh probe re-classifies on settled state
// (Accessor / non-plain => the precise D3/D7 TypeError; plain data => the
// value-only Exchange leg). Unlike the named helper this one CAN throw
// (exotic-receiver generic fallback, conversion/map-allocation OOM), so the
// caller must RETURN_IF_EXCEPTION before testing the returned error.
//
// Publication protocol (review round 1 amendment (c)): the sparse-map
// conditional add and the value publish run in ONE critical section under
// the OBJECT's cellLock - the same lock defineOwnIndexedProperty holds
// around ITS map->add. With add and publish atomic w.r.t. define's add,
// isNewEntry alone decides the winner:
// - we win the add: define's later add returns !isNewEntry and takes its
// reconfiguration path against our already-published plain entry -
// linearizes as store-then-define. No define-side descriptor write can
// interleave between our add and our publish: BOTH putIndexedDescriptor
// sites (defineOwnIndexedProperty's new-entry arm and its
// reconfiguration arm) are sequenced after define's object-cellLocked
// add, which our window excludes;
// - define wins the add: our add returns !isNewEntry and we write NOTHING
// - the restart's fresh probe sees the settled descriptor and throws the
// precise TypeError (or Exchange-legs a plain data racer).
// Unlocked attribute-0 value writers (putEntry/putDirect reached from plain
// JS puts, which never carry descriptors on these receiver classes - every
// descriptor write on a fast-put receiver routes through
// defineOwnIndexedProperty's object-cellLocked add) can interleave with the
// publish; absorbing one is a value-only overwrite of a plain attributes-0
// entry under the MAP's lock and linearizes as their-put-then-our-store.
// The publish terminal is the map's locked putDirect: it re-checks ReadOnly
// under the map's cellLock and force-sets the value - on OUR fresh
// attributes-0 entry (reconfiguration excluded above) that is a plain value
// publish, never a descriptor change.
//
// Loop shape (every arm either finishes, returns lost-race, or makes the
// shape strictly more settled before re-dispatching - no shape can spin):
// 1. dense stores via trySetIndexQuickly (flag-on it self-dispatches to
// trySetIndexQuicklyConcurrent; AS and Undecided answer false by
// design, §Q/I31, so no sparse map is ever consulted here);
// 2. CoW materializes (§4.8 cell-locked materializer, concurrent-correct
// flag-on) and re-dispatches;
// 3. AS in-vector: locked fill - the same one-locked-window store the
// I31-routed in-vector arm of
// putDirectIndexBeyondVectorLengthWithArrayStorage uses;
// 4. AS beyond-vector, no map: dense-enough indexes grow the vector
// OUTSIDE the lock and re-dispatch into arm 3; sparse-worthy indexes
// (or growth failure) allocate a map OUTSIDE the lock and install it
// install-if-absent under the lock (allocateSparseIndexMap
// unconditionally REPLACES m_sparseMap, which would orphan a racing
// define's whole map - never used here);
// 5. AS with map: the conditional add + publish described above, then the
// same I21 map-identity revalidation as JSObject.cpp's flag-on
// map->putDirect sites (a racing map replacement orphans the entry =>
// lost race; the restart re-derives and re-stores on the live map);
// 6. non-AS shapes the quick store rejected (beyond-vector dense, blank
// sparse-worthy/slow-put) convert to ArrayStorage and re-dispatch into
// arms 3-5. Deliberately NOT putByIndexBeyondVectorLengthWithoutAttributes:
// its sparse terminal is putEntry, which CALLS a racing accessor's
// setter - wrong for Atomics.store, which must restart and throw. The
// AS arm's conditional add is the only sparse terminal this helper
// permits. Shape conservatism is deliberate and JS-unobservable: a
// beyond-vector Atomics.store add takes ArrayStorage rather than
// growing the dense shape (GIL-on/flag-off paths untouched).
//
// Known residual (narrowed, recorded): a racing preventExtensions can still
// be overtaken between the post-add isStructureExtensible re-check and the
// publish - the named leg closes this exactly via the E4 structureID CAS;
// the indexed sparse add has no structure CAS to hang the re-check on. The
// window is one lock-internal interval (was: the whole probe->putDirectIndex
// span), and the failure mode is an extra plain property on a freshly
// non-extensible object - the same state the pre-fix code produced, never a
// descriptor clobber. Mirrors defineOwnIndexedProperty's own post-add
// re-check discipline.
ASCIILiteral JSObject::putDirectIndexForAtomicsMissingAdd(JSGlobalObject* globalObject, uint32_t i, JSValue value)
{
ASSERT(Options::useJSThreads());
ASSERT(i <= MAX_ARRAY_INDEX); // parseIndex never yields larger.
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (!canUseConditionalIndexedMissingAdd(this)) {
// Exotic receivers (typed arrays, StringObject, arguments, ...) keep
// today's generic path: their per-class defineOwnProperty runs,
// exactly as GIL-on; the sparse-map force-set terminal is not the
// shape they reach.
putDirectIndex(globalObject, i, value);
RETURN_IF_EXCEPTION(scope, ASCIILiteral { });
return { };
}
SparseArrayValueMap* pendingMap = nullptr; // GC-visible via conservative stack scan.
while (true) {
// (1) Plain dense store on a fast flat/segmented word.
if (trySetIndexQuickly(vm, i, value))
return { };
if (isCopyOnWrite(indexingMode())) [[unlikely]] {
convertFromCopyOnWrite(vm); // §4.8: routes through the cell-locked materializer.
continue;
}
IndexingType type = indexingType();
if (hasAnyArrayStorage(type)) {
{
Locker locker { cellLock() };
ArrayStorage* storage = arrayStorageOrNull();
if (!storage)
continue; // Shape moved before the lock landed: re-dispatch.
if (i < storage->vectorLength()) {
// (3) Locked in-vector fill (handles holes; bumps
// m_numValuesInVector and length itself).
//
// Map-governance gate (MC-REENT S3c close-out): the
// in-vector arm must not bypass a sparse map that governs
// this index. A racing indexed define can interleave with
// a foreign generic-path vector grow as
// define: createArrayStorage (no map yet)
// peer: increaseVectorLength(i+1) (locked AS-COPY)
// define: allocateSparseIndexMap + setSparseMode +
// cellLocked add(i) + descriptor publish
// us: i < vectorLength -> unconditional vector fill
// leaving a non-empty vector slot that SHADOWS the map's
// accessor/non-writable descriptor (OM I31: in sparse
// mode the vector must stay hole-only; a map entry for a
// sub-vectorLength index is define's, never ours). Both
// probes are safe here: define's map->add runs under this
// same object cellLock, and contains() self-locks the
// map's cell lock — the same map-under-object order arm
// (5)'s map->putDirect terminal already uses.
SparseArrayValueMap* governingMap = storage->m_sparseMap.get();
if (governingMap && (governingMap->sparseMode() || governingMap->contains(i))) [[unlikely]] {
if (governingMap->contains(i))
return "lost indexed-add race (existing sparse entry)"_s; // Restart reclassifies on the settled descriptor.
// Sparse mode, no entry for i (reachable stably when
// a foreign grow raced the mode flip): the map is
// the only legal terminal — fall through to arm (5)'s
// conditional add below instead of returning
// lost-race, which would livelock (the re-probe still
// answers Missing on this settled state).
} else {
setIndexQuicklyForArrayStorageIndexingType(vm, i, value);
return { };
}
}
if (i >= storage->length())
storage->setLength(i + 1); // LikePutDirect semantics: no length-writability gate.
SparseArrayValueMap* map = storage->m_sparseMap.get();
if (!map) {
if (pendingMap) {
// (4) Install-if-absent under the cell lock.
storage->m_sparseMap.set(vm, this, pendingMap);
map = pendingMap;
pendingMap = nullptr;
}
// else: fall out to allocate a map outside the lock.
//
// NO dense-growth (increaseVectorLength) arm here, by
// ruling on TSAN family growarrayright-vs-sparsemap-atomics
// (OM §4 — NOT blessed; CVE map mc-reent-store-missing-
// indexed-define-race). The previous mirror of
// putDirectIndexBeyondVectorLengthWithArrayStorage's !map
// dense-growth leg dropped this lock and called
// increaseVectorLength, whose growArrayRight memcpy plain-
// reads the WHOLE old butterfly (including the
// ArrayStorage::m_sparseMap header word) under our
// cellLock. defineOwnIndexedProperty's blank-shape arm of
// ensureArrayStorageExistsAndEnterDictionaryIndexingMode
// does createArrayStorage(0,0) then allocateSparseIndexMap
// — and that m_sparseMap.set runs WITHOUT the cellLock, so
// increaseVectorLength's locked sparse-mode re-check cannot
// synchronize with it: the memcpy and the storeCell race on
// the same word (UB), and our AS-COPY publish can drop
// define's freshly-installed map. Removing the grow arm
// leaves arm-(4)'s locked, atomic m_sparseMap.set as the
// ONLY butterfly-header write this function performs in the
// AS arm; define's later cellLocked re-read + pendingMap
// re-derive + heal loop linearize against it via this same
// lock. Density is a non-goal on the Atomics.store
// indexed-miss slow path; a foreign generic putter that
// wants vector growth still grows via the §4.6-locked
// JSObject.cpp paths, and arm-(3)'s in-vector fill above
// services any such peer-grown vector.
}
if (map) {
// (5) Conditional sparse add + publish, ONE object-cellLock
// window (see the protocol comment above). map->add only
// fastMallocs (no GC allocation, no JS), so it is
// wrappable under the cell lock (O1) - the exact call
// defineOwnIndexedProperty makes under this same lock.
SparseArrayValueMap::AddResult result = map->add(this, i);
if (!result.isNewEntry)
return "lost indexed-add race (existing sparse entry)"_s; // NEVER write a foreign entry.
if (!isStructureExtensible()) [[unlikely]] {
// Same post-add re-check + remove defineOwnIndexedProperty
// performs; remove by KEY - the AddResult iterator can
// dangle across the map's internal unlock (AB18-G).
map->remove(i);
return "lost indexed-add race (became non-extensible)"_s;
}
bool ok = map->putDirect(globalObject, this, i, value, 0, PutDirectIndexLikePutDirect);
RETURN_IF_EXCEPTION(scope, ASCIILiteral { });
if (!ok) [[unlikely]]
return "lost indexed-publish race"_s; // Entry went ReadOnly/removed under the map lock.
// I21 map-identity revalidation, same discipline as the
// flag-on map->putDirect sites in JSObject.cpp.
ArrayStorage* freshStorage = arrayStorageOrNull();
if (!freshStorage || freshStorage->m_sparseMap.get() != map) [[unlikely]]
return "lost indexed-publish race (sparse map replaced)"_s;
return { };
}
}
pendingMap = SparseArrayValueMap::create(vm); // GC allocation: never under the cell lock (I20/O1).
continue;
}
if (hasUndecided(type)) {
convertUndecidedForValue(vm, value);
continue;
}
if (!hasIndexedProperties(type)
&& !indexingShouldBeSparse() && !needsSlowPutIndexing()
&& !indexIsSufficientlyBeyondLengthForSparseMap(i, 0) && i < MIN_SPARSE_ARRAY_INDEX) {
// Blank, vector-worthy index: dense first install, ordered as the
// generic blank arm orders it (N3 loser re-dispatches: a racer
// installed first, so the shape moved).
if (tryCreateInitialForValueAndSetConcurrent(vm, i, value))
return { };
continue;
}
// (6) Everything else: take ArrayStorage and re-dispatch into the AS
// arm. ensureArrayStorageSlow is the §4.6 stop-routed flag-on
// converter and self-handles a racing AS install (loser leg).
ArrayStorage* storage = indexingShouldBeSparse()
? ensureArrayStorageExistsAndEnterDictionaryIndexingMode(vm)
: ensureArrayStorage(vm);
if (!storage) [[unlikely]] {
// hijacksIndexingHeader receivers cannot take AS: generic path,
// as GIL-on.
putDirectIndex(globalObject, i, value);
RETURN_IF_EXCEPTION(scope, ASCIILiteral { });
return { };
}
continue;
}
}
static JSValue atomicsStoreOnPropertyGilOff(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue value)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
while (true) {
auto probe = probeOwnPropertyForAtomicsConcurrent(globalObject, object, propertyName);
RETURN_IF_EXCEPTION(scope, { });
if (probe.restart) [[unlikely]] // I5 fix amendment: racing delete/shrink made a hole; re-probe on fresh state.
continue;
switch (probe.kind) {
case OwnPropertyKind::Accessor:
throwTypeError(globalObject, scope, "Atomics.store: property is an accessor"_s);
return { };
case OwnPropertyKind::Data: {
if (probe.attributes & PropertyAttribute::ReadOnly) {
throwTypeError(globalObject, scope, "Atomics.store: property is not writable"_s);
return { };
}
// Existing slot: a §9.5 Exchange (value-only - no putDirect, no
// attribute-changing transition; result discarded).
AtomicSlotRequest request;
request.operation = AtomicSlotOperation::Exchange;
request.replacement = value;
AtomicSlotStatus status = AtomicSlotStatus::Restart;
dispatchAtomicSlotRequest(globalObject, object, propertyName, probe, request, status);
if (status == AtomicSlotStatus::Applied)
return value;
ASSERT(status == AtomicSlotStatus::Restart);
continue;
}
case OwnPropertyKind::Missing: {
bool extensible = object->isExtensible(globalObject);
RETURN_IF_EXCEPTION(scope, { });
if (!extensible) {
throwTypeError(globalObject, scope, "Atomics.store: cannot add a property to a non-extensible object"_s);
return { };
}
if (std::optional<uint32_t> index = parseIndex(propertyName)) {
// Fresh INDEXED element: conditional add (the indexed twin of
// the named leg below) - closes the formerly-recorded KNOWN
// RESIDUAL (INTEGRATE-ungil, U-T10 amend item 3). A non-null
// error means we LOST a race with a concurrent indexed
// define/remove/reshape: restart the probe, which
// re-classifies on settled state (accessor / non-writable =>
// the precise TypeError above; plain data => the value-only
// Exchange leg). Exception checked FIRST: unlike the named
// helper, the indexed one can throw (exotic-receiver generic
// fallback, conversion/map-allocation OOM).
ASCIILiteral error = object->putDirectIndexForAtomicsMissingAdd(globalObject, index.value(), value);
RETURN_IF_EXCEPTION(scope, { });
if (!error.isNull()) [[unlikely]]
continue;
return value;
}
// Fresh NAMED data property (writable/enumerable/configurable).
// U-T10 amend: NOT putDirect (define-own semantics) - GIL-off,
// a key that materialized between the Missing probe and the put
// would be attribute-clobbered (a racing accessor replaced, a
// racing ReadOnly stripped, via the attribute-change transition
// to attributes 0), and a racing preventExtensions could be
// overtaken - none of which any sequential interleaving of
// Atomics.store can produce. The conditional add re-derives
// existence/extensibility inside the OM's E4-published §2 loop:
// a non-null error means we LOST such a race - restart, and the
// fresh probe re-classifies and throws the precise D3/D7/
// non-extensible TypeError. A racing plain writable data add is
// absorbed as a value-only replace (attributes preserved), which
// linearizes as define-then-store.
PutPropertySlot addSlot(object, true);
ASCIILiteral error = object->putDirectForAtomicsMissingAdd(vm, propertyName, value, addSlot);
if (!error.isNull()) [[unlikely]]
continue;
return value;
}
}
RELEASE_ASSERT_NOT_REACHED();
}
}
static JSValue atomicsCompareExchangeOnPropertyGilOff(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue expected, JSValue replacement)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
const bool logContention = Options::logJSLockContention();
if (logContention) [[unlikely]]
g_threadAtomicsRMWCalls.fetch_add(1, std::memory_order_relaxed);
while (true) {
auto probe = probeOwnPropertyForAtomicsConcurrent(globalObject, object, propertyName);
RETURN_IF_EXCEPTION(scope, { });
if (probe.restart) [[unlikely]] // I5 fix amendment: racing delete/shrink made a hole; re-probe on fresh state.
continue;
if (probe.kind != OwnPropertyKind::Data) {
throwTypeError(globalObject, scope, "Atomics.compareExchange: object has no own data property"_s);
return { };
}
// D7 (see the GIL body's rationale): thrown unconditionally, not only
// when SVZ matches.
if (probe.attributes & PropertyAttribute::ReadOnly) {
throwTypeError(globalObject, scope, "Atomics.compareExchange: property is not writable"_s);
return { };
}
AtomicSlotStatus status = AtomicSlotStatus::Restart;
JSValue current;
if (probe.index)
current = object->atomicSlotCompareExchangeAtIndex(globalObject, probe.index.value(), expected, replacement, status);
else
current = object->atomicSlotCompareExchange(globalObject, propertyName.uid(), probe.offset, probe.structureID, expected, replacement, status);
switch (status) {
case AtomicSlotStatus::Applied:
case AtomicSlotStatus::NotEqual:
return current; // SVZ semantics: returns the value READ either way.
case AtomicSlotStatus::NeedsStringResolution: {
// Resolve the rope(s) OUTSIDE any lock (§N.2 single-flight; may
// allocate and throw OOM), then re-probe. Resolution rewrites the
// rope in place, so an unchanged slot makes progress next pass;
// a storm of fresh rope stores re-enters here - the same
// adversarial-progress class as §C.3(b)'s dequeue-and-restart.
if (expected.isString()) {
auto resolvedExpected = asString(expected)->value(globalObject);
RETURN_IF_EXCEPTION(scope, { });
UNUSED_VARIABLE(resolvedExpected);
}
if (current.isString()) {
auto resolvedCurrent = asString(current)->value(globalObject);
RETURN_IF_EXCEPTION(scope, { });
UNUSED_VARIABLE(resolvedCurrent);
}
if (logContention) [[unlikely]]
g_threadAtomicsRMWRestarts.fetch_add(1, std::memory_order_relaxed);
continue;
}
case AtomicSlotStatus::Restart:
if (logContention) [[unlikely]]
g_threadAtomicsRMWRestarts.fetch_add(1, std::memory_order_relaxed);
continue;
case AtomicSlotStatus::NotNumber:
case AtomicSlotStatus::LockedRevalidate: // Accessor-internal; never escapes.
break;
}
RELEASE_ASSERT_NOT_REACHED();
}
}
static JSValue atomicsRMWOnPropertyGilOff(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, AtomicsRMWOp op, JSValue operand)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// Operand coercions first (may run JS), exactly as the GIL bodies order
// them; the atomic step is the accessor call below.
AtomicSlotRequest request;
switch (op) {
case AtomicsRMWOp::Exchange:
request.operation = AtomicSlotOperation::Exchange;
request.replacement = operand;
break;
case AtomicsRMWOp::Add:
case AtomicsRMWOp::Sub:
request.operation = op == AtomicsRMWOp::Add ? AtomicSlotOperation::Add : AtomicSlotOperation::Sub;
request.operandNumber = operand.toNumber(globalObject);
RETURN_IF_EXCEPTION(scope, { });
break;
case AtomicsRMWOp::And:
case AtomicsRMWOp::Or:
case AtomicsRMWOp::Xor:
request.operation = op == AtomicsRMWOp::And ? AtomicSlotOperation::And
: op == AtomicsRMWOp::Or ? AtomicSlotOperation::Or : AtomicSlotOperation::Xor;
request.operandInt = operand.toInt32(globalObject);
RETURN_IF_EXCEPTION(scope, { });
break;
}
bool isExchange = op == AtomicsRMWOp::Exchange;
const bool logContention = Options::logJSLockContention();
if (logContention) [[unlikely]]
g_threadAtomicsRMWCalls.fetch_add(1, std::memory_order_relaxed);
while (true) {
auto probe = probeOwnPropertyForAtomicsConcurrent(globalObject, object, propertyName);
RETURN_IF_EXCEPTION(scope, { });
if (probe.restart) [[unlikely]] // I5 fix amendment: racing delete/shrink made a hole; re-probe on fresh state.
continue;
if (probe.kind != OwnPropertyKind::Data) {
throwTypeError(globalObject, scope, isExchange ? "Atomics.exchange: object has no own data property"_s : "Atomics RMW: object has no own data property"_s);
return { };
}
if (probe.attributes & PropertyAttribute::ReadOnly) {
throwTypeError(globalObject, scope, isExchange ? "Atomics.exchange: property is not writable"_s : "Atomics RMW: property is not writable"_s);
return { };
}
AtomicSlotStatus status = AtomicSlotStatus::Restart;
JSValue current = dispatchAtomicSlotRequest(globalObject, object, propertyName, probe, request, status);
switch (status) {
case AtomicSlotStatus::Applied:
return current;
case AtomicSlotStatus::NotNumber:
throwTypeError(globalObject, scope, "Atomics RMW: stored value is not a number"_s);
return { };
case AtomicSlotStatus::Restart:
if (logContention) [[unlikely]]
g_threadAtomicsRMWRestarts.fetch_add(1, std::memory_order_relaxed);
continue;
case AtomicSlotStatus::NotEqual:
case AtomicSlotStatus::NeedsStringResolution:
case AtomicSlotStatus::LockedRevalidate: // Accessor-internal; never escapes.
break;
}
RELEASE_ASSERT_NOT_REACHED();
}
}
#endif // USE(JSVALUE64)
JSValue atomicsLoadOnProperty(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName)
{
VM& vm = globalObject->vm();
#if USE(JSVALUE64)
if (vm.gilOff()) [[unlikely]]
return atomicsLoadOnPropertyGilOff(globalObject, object, propertyName);
#endif
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue value;
unsigned attributes = 0;
auto kind = getOwnPropertyForAtomics(globalObject, object, propertyName, value, attributes);
RETURN_IF_EXCEPTION(scope, { });
if (kind != OwnPropertyKind::Data) {
throwTypeError(globalObject, scope, "Atomics.load: object has no own property"_s);
return { };
}
return value;
}
JSValue atomicsStoreOnProperty(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue value)
{
VM& vm = globalObject->vm();
#if USE(JSVALUE64)
if (vm.gilOff()) [[unlikely]]
return atomicsStoreOnPropertyGilOff(globalObject, object, propertyName, value);
#endif
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue existing;
unsigned attributes = 0;
auto kind = getOwnPropertyForAtomics(globalObject, object, propertyName, existing, attributes);
RETURN_IF_EXCEPTION(scope, { });
switch (kind) {
case OwnPropertyKind::Accessor:
throwTypeError(globalObject, scope, "Atomics.store: property is an accessor"_s);
return { };
case OwnPropertyKind::Data:
if (attributes & PropertyAttribute::ReadOnly) {
throwTypeError(globalObject, scope, "Atomics.store: property is not writable"_s);
return { };
}
break;
case OwnPropertyKind::Missing: {
bool extensible = object->isExtensible(globalObject);
RETURN_IF_EXCEPTION(scope, { });
if (!extensible) {
throwTypeError(globalObject, scope, "Atomics.store: cannot add a property to a non-extensible object"_s);
return { };
}
break;
}
}
if (kind == OwnPropertyKind::Data)
putExistingOwnDataPropertyForAtomics(globalObject, object, propertyName, value, attributes);
else
object->putDirectMayBeIndex(globalObject, propertyName, value); // Fresh data property: writable/enumerable/configurable.
RETURN_IF_EXCEPTION(scope, { });
return value;
}
JSValue atomicsCompareExchangeOnProperty(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, JSValue expected, JSValue replacement)
{
VM& vm = globalObject->vm();
#if USE(JSVALUE64)
if (vm.gilOff()) [[unlikely]]
return atomicsCompareExchangeOnPropertyGilOff(globalObject, object, propertyName, expected, replacement);
#endif
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue current;
unsigned attributes = 0;
auto kind = getOwnPropertyForAtomics(globalObject, object, propertyName, current, attributes);
RETURN_IF_EXCEPTION(scope, { });
if (kind != OwnPropertyKind::Data) {
throwTypeError(globalObject, scope, "Atomics.compareExchange: object has no own data property"_s);
return { };
}
// 4.5 "stores rep" inherits store's writability rule (same as exchange's
// "store but requires own data k"): putExistingOwnDataPropertyForAtomics
// uses putDirect define-semantics, which would replace a ReadOnly slot's
// value in place — a heap state no sequential JS program can create
// (THREAD.md indistinguishable-heap requirement; a lock word CASed on a
// later-frozen object must fail, not keep mutating). Thrown
// unconditionally, matching store/exchange (not only when SVZ matches).
if (attributes & PropertyAttribute::ReadOnly) {
throwTypeError(globalObject, scope, "Atomics.compareExchange: property is not writable"_s);
return { };
}