forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathStructure.cpp
More file actions
3143 lines (2808 loc) · 151 KB
/
Copy pathStructure.cpp
File metadata and controls
3143 lines (2808 loc) · 151 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) 2008-2025 Apple Inc. All rights reserved.
* Copyright (C) 2020 Alexey Shvayka <shvaikalesh@gmail.com>.
*
* 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 APPLE INC. ``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 APPLE INC. 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 "Structure.h"
#include "BrandedStructure.h"
#include "BuiltinNames.h"
#include "DumpContext.h"
#include "JSCInlines.h"
#include "PropertyNameArray.h"
#include "PropertyTable.h"
#include "VMLite.h"
#include "VMLiteShared.h"
#include "WebAssemblyGCStructure.h"
#include <wtf/CommaPrinter.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/RefPtr.h>
#include <wtf/ScopedLambda.h>
#include <wtf/Vector.h>
#define DUMP_STRUCTURE_ID_STATISTICS 0
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
namespace JSC {
template<typename DetailsFunc>
void Structure::checkOffsetConsistency(PropertyTable* propertyTable, const DetailsFunc& detailsFunc) const
{
// We cannot reliably assert things about the property table in the concurrent
// compilation thread. It is possible for the table to be stolen and then have
// things added to it, which leads to the offsets being all messed up. We could
// get around this by grabbing a lock here, but I think that would be overkill.
if (isCompilationThread())
return;
// SPEC-objectmodel §6 L3/L4 (same rationale as the compilation-thread
// escape above, for N mutators): flag-on, a DICTIONARY's pinned table is
// edited in place under {cell lock, m_lock} while its structureID stays
// put, so callers that reach this check without those locks (the
// transition-planning paths in this file, racing another thread's
// cell-locked dictionary add) read a torn {maxOffset, table} pair — an
// off-by-N here is a legal transient, not corruption. Mutation sites
// still self-check under m_lock via Structure::add/remove's
// checkConsistency(); only the dictionary's unlocked spot-checks are
// skipped. NOTE (CVE-DBG-2): unlocked NON-dictionary spot-checks are
// skipped one level up, in the no-arg checkOffsetConsistency() wrapper —
// flag-on GIL-off, this template is now reached only from under m_lock
// (checkConsistency) or with a thread-local table
// (materializePropertyTable), where the dictionary condition below is the
// only remaining legal-transient case. Flag-off: unchanged (I22).
if (Options::useJSThreads() && isDictionary()) [[unlikely]]
return;
unsigned totalSize = propertyTable->propertyStorageSize();
unsigned inlineOverflowAccordingToTotalSize = totalSize < m_inlineCapacity ? 0 : totalSize - m_inlineCapacity;
auto fail = [&] (const char* description) {
dataLog("Detected offset inconsistency: ", description, "!\n");
dataLog("this = ", RawPointer(this), "\n");
dataLog("transitionOffset = ", transitionOffset(), "\n");
dataLog("maxOffset = ", maxOffset(), "\n");
dataLog("m_inlineCapacity = ", m_inlineCapacity, "\n");
dataLog("propertyTable = ", RawPointer(propertyTable), "\n");
dataLog("numberOfSlotsForMaxOffset = ", numberOfSlotsForMaxOffset(maxOffset(), m_inlineCapacity), "\n");
dataLog("totalSize = ", totalSize, "\n");
dataLog("inlineOverflowAccordingToTotalSize = ", inlineOverflowAccordingToTotalSize, "\n");
dataLog("numberOfOutOfLineSlotsForMaxOffset = ", numberOfOutOfLineSlotsForMaxOffset(maxOffset()), "\n");
detailsFunc();
UNREACHABLE_FOR_PLATFORM();
};
if (numberOfSlotsForMaxOffset(maxOffset(), m_inlineCapacity) != totalSize)
fail("numberOfSlotsForMaxOffset doesn't match totalSize");
if (inlineOverflowAccordingToTotalSize != numberOfOutOfLineSlotsForMaxOffset(maxOffset()))
fail("inlineOverflowAccordingToTotalSize doesn't match numberOfOutOfLineSlotsForMaxOffset");
}
#if DUMP_STRUCTURE_ID_STATISTICS
static UncheckedKeyHashSet<Structure*>& liveStructureSet = *(new UncheckedKeyHashSet<Structure*>);
#endif
inline void StructureTransitionTable::setSingleTransition(VM& vm, JSCell* owner, Structure* structure)
{
ASSERT(isUsingSingleSlot());
intptr_t newData = std::bit_cast<intptr_t>(structure) | UsingSingleSlotFlag;
if (Options::useJSThreads()) [[unlikely]] {
// TSAN family structure-fields (UG §K publication): this is the
// publish store of a freshly constructed transition target. Mutator
// lookups hold m_lock flag-on (L6), but GC concurrent-marking reads
// m_data via trySingleTransition under a DIFFERENT lock epoch and the
// single-slot word is also read during finalization — release here
// (plus the constructor-tail fence) orders the target's constructor
// stores before its pointer becomes loadable. Cold path (first
// transition install), so the arm64 stlr is acceptable; flag-off
// keeps the plain store below, bit-identical codegen.
WTF::atomicStore(&m_data, newData, std::memory_order_release);
} else
m_data = newData;
vm.writeBarrier(owner, structure);
}
bool StructureTransitionTable::contains(PointerKey rep, unsigned attributes, TransitionKind transitionKind) const
{
if (isUsingSingleSlot()) {
Structure* transition = trySingleTransition();
return transition && transition->m_transitionPropertyName == rep.pointer() && transition->transitionPropertyAttributes() == attributes && transition->transitionKind() == transitionKind;
}
return map()->get(StructureTransitionTable::Hash::createKey(rep, attributes, transitionKind));
}
void StructureTransitionTable::add(VM& vm, JSCell* owner, Structure* structure)
{
// SPEC-objectmodel Task 3b (SPEC-vmstate §5.3): allocating transition-table
// insertions (single-slot -> TransitionMap inflation, map node allocation)
// run under the process-global structure-allocation lock. Every caller in
// this file acquires it OUTSIDE the owning Structure's m_lock (§6 lock
// order: SAL rank 7a < JSCellLock 10a < Structure::m_lock 10b); the lock
// is non-recursive, so it must NOT be re-acquired here (vmstate §5.2).
ASSERT(!Options::useStructureAllocationLock() || SharedVMState::singleton().structureAllocationRegionDepth() == 1);
// SPEC-objectmodel L6/I37 (Task 3c): flag-on, inserts run under the owning
// Structure's m_lock and every insert site dual-checks getMatching() under
// that lock first (adopting a racing winner instead of inserting), so a
// duplicate-keyed insert here would silently clobber a published
// transition — a logic error.
ASSERT(!Options::useJSThreads() || !getMatching(structure));
if (isUsingSingleSlot()) {
Structure* existingTransition = trySingleTransition();
// This handles the first transition being added.
if (!existingTransition) {
setSingleTransition(vm, owner, structure);
return;
}
// This handles the second transition being added
// (or the first transition being despecified!)
setMap(new TransitionMap(vm));
add(vm, owner, existingTransition);
}
// Add the structure to the map.
map()->set(StructureTransitionTable::Hash::createKeyFromStructure(structure), structure);
}
void Structure::dumpStatistics()
{
#if DUMP_STRUCTURE_ID_STATISTICS
unsigned numberLeaf = 0;
unsigned numberUsingSingleSlot = 0;
unsigned numberSingletons = 0;
unsigned numberWithPropertyTables = 0;
unsigned totalPropertyTablesSize = 0;
for (auto* structure : liveStructureSet) {
switch (structure->m_transitionTable.size()) {
case 0:
++numberLeaf;
if (!structure->previousID())
++numberSingletons;
break;
case 1:
++numberUsingSingleSlot;
break;
}
if (PropertyTable* table = structure->propertyTableOrNull()) {
++numberWithPropertyTables;
totalPropertyTablesSize += table->sizeInMemory();
}
}
dataLogF("Number of live Structures: %d\n", liveStructureSet.size());
dataLogF("Number of Structures using the single item optimization for transition map: %d\n", numberUsingSingleSlot);
dataLogF("Number of Structures that are leaf nodes: %d\n", numberLeaf);
dataLogF("Number of Structures that singletons: %d\n", numberSingletons);
dataLogF("Number of Structures with PropertyTables: %d\n", numberWithPropertyTables);
dataLogF("Size of a single Structures: %d\n", static_cast<unsigned>(sizeof(Structure)));
dataLogF("Size of sum of all property maps: %d\n", totalPropertyTablesSize);
dataLogF("Size of average of all property maps: %f\n", static_cast<double>(totalPropertyTablesSize) / static_cast<double>(liveStructureSet.size()));
#else
dataLogF("Dumping Structure statistics is not enabled.\n");
#endif
}
#if ASSERT_ENABLED
void Structure::validateFlags()
{
bool hasStaticPropertyTable = false;
for (const ClassInfo* ci = classInfoForCells(); ci; ci = ci->parentClass) {
if (ci->staticPropHashTable)
hasStaticPropertyTable = true;
}
RELEASE_ASSERT(hasStaticPropertyTable == typeInfo().hasStaticPropertyTable());
const MethodTable& methodTable = m_classInfo->methodTable;
bool overridesGetCallData = methodTable.getCallData != JSCell::getCallData;
RELEASE_ASSERT(overridesGetCallData == typeInfo().overridesGetCallData());
bool overridesGetOwnPropertySlot =
methodTable.getOwnPropertySlot != JSObject::getOwnPropertySlot
&& methodTable.getOwnPropertySlot != JSCell::getOwnPropertySlot;
// We can strengthen this into an equivalence test if there are no classes
// that specifies this flag without overriding getOwnPropertySlot.
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=212956
if (overridesGetOwnPropertySlot)
RELEASE_ASSERT(typeInfo().overridesGetOwnPropertySlot());
bool overridesGetOwnPropertySlotByIndex =
methodTable.getOwnPropertySlotByIndex != JSObject::getOwnPropertySlotByIndex
&& methodTable.getOwnPropertySlotByIndex != JSCell::getOwnPropertySlotByIndex;
// We can strengthen this into an equivalence test if there are no classes
// that specifies this flag without overriding getOwnPropertySlotByIndex.
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=212958
if (overridesGetOwnPropertySlotByIndex)
RELEASE_ASSERT(typeInfo().interceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero());
bool overridesGetOwnPropertyNames =
methodTable.getOwnPropertyNames != JSObject::getOwnPropertyNames
&& methodTable.getOwnPropertyNames != JSCell::getOwnPropertyNames;
RELEASE_ASSERT(overridesGetOwnPropertyNames == typeInfo().overridesGetOwnPropertyNames());
bool overridesGetOwnSpecialPropertyNames =
methodTable.getOwnSpecialPropertyNames != JSObject::getOwnSpecialPropertyNames
&& methodTable.getOwnSpecialPropertyNames != JSCell::getOwnSpecialPropertyNames;
RELEASE_ASSERT(overridesGetOwnSpecialPropertyNames == typeInfo().overridesGetOwnSpecialPropertyNames());
bool overridesGetPrototype =
methodTable.getPrototype != static_cast<MethodTable::GetPrototypeFunctionPtr>(JSObject::getPrototype)
&& methodTable.getPrototype != JSCell::getPrototype;
RELEASE_ASSERT(overridesGetPrototype == typeInfo().overridesGetPrototype());
bool overridesPut = methodTable.put != JSObject::put && ((typeInfo().type() == StringType || typeInfo().type() == SymbolType || typeInfo().type() == HeapBigIntType) || methodTable.put != JSCell::put);
RELEASE_ASSERT(overridesPut == typeInfo().overridesPut());
bool overridesIsExtensible =
methodTable.isExtensible != static_cast<MethodTable::IsExtensibleFunctionPtr>(JSObject::isExtensible)
&& methodTable.isExtensible != JSCell::isExtensible;
RELEASE_ASSERT(overridesIsExtensible == typeInfo().overridesIsExtensible());
// MasqueradesAsUndefined requires non-null Realm.
RELEASE_ASSERT(realm() || !typeInfo().masqueradesAsUndefined());
}
#else
inline void Structure::validateFlags() { }
#endif
Structure::Structure(VM& vm, StructureVariant variant, JSGlobalObject* globalObject, const TypeInfo& typeInfo, const ClassInfo* classInfo)
: Structure(vm, globalObject, jsNull(), typeInfo, classInfo, NonArray, 0)
{
// §8.9 wave 3: TSAN-relaxed (plain non-TSAN) — concurrent stale-reference
// readers may probe variant() while this recycled cell is re-initialized.
tsanRelaxedStore(m_structureVariant, variant);
ASSERT(this->variant() == StructureVariant::WebAssemblyGC);
// §10.9 fixShape (2): the delegated-to constructor's publication
// storeStoreFence ran BEFORE the variant overwrite above, so the variant
// store was not ordered before a subsequent single-word publish. Re-issue
// the release so readers that reach this Structure through the publish
// see WebAssemblyGC, never the delegate's transient Normal. Flag-off
// codegen unchanged (predicted-not-taken branch only).
if (Options::useJSThreads()) [[unlikely]]
WTF::storeStoreFence();
}
Structure::Structure(VM& vm, JSGlobalObject* globalObject, JSValue prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
: JSCell(vm, vm.structureStructure.get())
, m_blob(indexingType, typeInfo)
, m_realm(globalObject, WriteBarrierEarlyInit)
, m_prototype(prototype, WriteBarrierEarlyInit)
, m_transitionWatchpointSet(IsWatched)
{
// TSAN family structure-fields (§8.9 fixShape (2)): the scalar members are
// initialized here with TSAN-relaxed stores (tsanRelaxedStore compiles to
// the identical plain store non-TSAN), not in the member-init-list — a
// member-init-list init is a plain store that races concurrent readers
// holding stale/recycled cell references (classInfoForCells/typeInfo/...,
// the 83 one-sided Structure::Structure keys), and clang's coalescing of
// adjacent plain init-list stores produced wide stores overlapping the
// m_lock byte and the watchpoint-set words (the Atomic<u8>/Atomic<u64>
// "ctor" keys). The WriteBarrier members above are already relaxed-atomic
// through storeCell; m_blob through TypeInfoBlob's relaxed accessors. The
// Atomic-bearing member TYPES (m_lock, the three watchpoint sets,
// m_transitionTable, m_seenProperties) construct through
// ConcurrentCtorMember (Structure.h, §10.9 fixShape (1)): under TSAN
// their storage is a deferred-construction union written with relaxed
// atomic stores, so the std::atomic constructors' plain stores never
// touch the member words; non-TSAN they are the plain types.
tsanRelaxedStore(m_outOfLineTypeFlags, typeInfo.outOfLineTypeFlags());
tsanRelaxedStore(m_inlineCapacity, static_cast<uint8_t>(inlineCapacity));
tsanRelaxedStore(m_bitField, static_cast<uint32_t>(0));
tsanRelaxedStore(m_transitionPropertyAttributes, static_cast<TransitionPropertyAttributes>(0));
tsanRelaxedStore(m_structureVariant, StructureVariant::Normal);
tsanRelaxedStore(m_transitionThreadLocalTID, static_cast<uint16_t>(0));
tsanRelaxedStore(m_propertyHash, static_cast<uint32_t>(0));
tsanRelaxedStore(m_classInfo, classInfo);
// SPEC-objectmodel §5: both TTL sets start IsWatched for new structures
// flag-on; flag-off they keep their inert NSDMI ClearWatchpoint (I22) and
// this single predicted-not-taken check is the only flag cost.
// N1: fresh structure - the creating thread is the sole lock-free
// butterfly-less transitioner while the TTL sets are valid (0 flag-off and
// on the main thread; never notTTLTID). Flag-off the field keeps the 0
// stored above and is never consulted (I22/E3), so skip the out-of-line
// currentButterflyTID() call (cross-DSO + TLS read) entirely.
if (Options::useJSThreads()) [[unlikely]] {
m_transitionThreadLocalWatchpointSet.startWatching();
m_writeThreadLocalWatchpointSet.startWatching();
tsanRelaxedStore(m_transitionThreadLocalTID, currentButterflyTID());
}
bool hasStaticNonEnumerableProperty = m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::DontEnum));
bool hasStaticNonConfigurableProperty = m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::DontDelete));
setDictionaryKind(NoneDictionaryKind);
setIsPinnedPropertyTable(false);
setHasAnyKindOfGetterSetterProperties(m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::AccessorOrCustomAccessorOrValue)));
setHasReadOnlyOrGetterSetterPropertiesExcludingProto(hasAnyKindOfGetterSetterProperties() || m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::ReadOnly)));
setHasNonEnumerableProperties(hasStaticNonEnumerableProperty || typeInfo.overridesGetOwnPropertySlot());
setHasSpecialProperties(false);
setHasNonConfigurableProperties(hasStaticNonConfigurableProperty || typeInfo.overridesGetOwnPropertySlot());
setHasNonConfigurableReadOnlyOrGetterSetterProperties(hasStaticNonConfigurableProperty || (typeInfo.overridesGetOwnPropertySlot() && typeInfo.type() != ArrayType));
setHasUnderscoreProtoPropertyExcludingOriginalProto(false);
setIsQuickPropertyAccessAllowedForEnumeration(true);
setTransitionPropertyAttributes(0);
setTransitionKind(TransitionKind::Unknown);
setMayBePrototype(false);
setDidPreventExtensions(typeInfo.overridesIsExtensible());
setDidTransition(false);
setStaticPropertiesReified(false);
setTransitionWatchpointIsLikelyToBeFired(false);
setHasBeenDictionary(false);
setProtectPropertyTableWhileTransitioning(false);
setTransitionOffset(vm, invalidOffset);
setMaxOffset(vm, invalidOffset);
ASSERT(inlineCapacity <= JSFinalObject::maxInlineCapacity);
ASSERT(static_cast<PropertyOffset>(inlineCapacity) < firstOutOfLineOffset);
ASSERT(!hasRareData());
ASSERT(hasAnyKindOfGetterSetterProperties() == m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::AccessorOrCustomAccessorOrValue)));
ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() == m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessorOrValue)));
validateFlags();
ASSERT(WTF::roundUpToMultipleOf<Structure::atomSize>(this) == this);
// TSAN family structure-fields (OM §5/§9.4, UG §K): publication release.
// Flag-on, this Structure becomes visible to other threads through a
// subsequent single-word publish (cell-header StructureID store,
// transition-table setSingleTransition, global/IC slots); concurrent
// readers then load m_classInfo/m_blob/m_realm/m_inlineCapacity without
// this structure's m_lock. All constructor stores must be ordered before
// any such publish store — the missing release the triage ruling calls
// out. Gated so the flag-off path keeps today's codegen (no dmb on arm64).
if (Options::useJSThreads()) [[unlikely]]
WTF::storeStoreFence();
}
const ClassInfo Structure::s_info = { "Structure"_s, nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(Structure) };
Structure::Structure(VM& vm, CreatingEarlyCellTag)
: JSCell(CreatingEarlyCell)
, m_prototype(jsNull(), WriteBarrierEarlyInit)
, m_transitionWatchpointSet(IsWatched)
{
// §8.9 wave 3: TSAN-relaxed scalar init instead of member-init-list plain
// stores — see the 7-argument constructor above for the full rationale.
tsanRelaxedStore(m_inlineCapacity, static_cast<uint8_t>(0));
tsanRelaxedStore(m_bitField, static_cast<uint32_t>(0));
tsanRelaxedStore(m_transitionPropertyAttributes, static_cast<TransitionPropertyAttributes>(0));
tsanRelaxedStore(m_structureVariant, StructureVariant::Normal);
tsanRelaxedStore(m_transitionThreadLocalTID, static_cast<uint16_t>(0));
tsanRelaxedStore(m_propertyHash, static_cast<uint32_t>(0));
tsanRelaxedStore(m_classInfo, static_cast<const ClassInfo*>(info()));
// N1 (early cell: VM startup runs on the creating thread; 0 on main).
// Flag-off: keep the 0 stored above (TID) and both TTL sets' inert
// ClearWatchpoint (I22), skip the out-of-line TLS read. Flag-on: start
// watching both TTL sets (§5).
if (Options::useJSThreads()) [[unlikely]] {
m_transitionThreadLocalWatchpointSet.startWatching();
m_writeThreadLocalWatchpointSet.startWatching();
tsanRelaxedStore(m_transitionThreadLocalTID, currentButterflyTID());
}
TypeInfo typeInfo { StructureType, StructureFlags };
bool hasStaticNonEnumerableProperty = m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::DontEnum));
bool hasStaticNonConfigurableProperty = m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::DontDelete));
setDictionaryKind(NoneDictionaryKind);
setIsPinnedPropertyTable(false);
setHasAnyKindOfGetterSetterProperties(m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::AccessorOrCustomAccessorOrValue)));
setHasReadOnlyOrGetterSetterPropertiesExcludingProto(hasAnyKindOfGetterSetterProperties() || m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::ReadOnly)));
setHasNonEnumerableProperties(hasStaticNonEnumerableProperty || typeInfo.overridesGetOwnPropertySlot());
setHasSpecialProperties(false);
setHasNonConfigurableProperties(hasStaticNonConfigurableProperty || typeInfo.overridesGetOwnPropertySlot());
setHasNonConfigurableReadOnlyOrGetterSetterProperties(hasStaticNonConfigurableProperty || (typeInfo.overridesGetOwnPropertySlot() && typeInfo.type() != ArrayType));
setHasUnderscoreProtoPropertyExcludingOriginalProto(false);
setIsQuickPropertyAccessAllowedForEnumeration(true);
setTransitionPropertyAttributes(0);
setTransitionKind(TransitionKind::Unknown);
setMayBePrototype(false);
setDidPreventExtensions(typeInfo.overridesIsExtensible());
setDidTransition(false);
setStaticPropertiesReified(false);
setTransitionWatchpointIsLikelyToBeFired(false);
setHasBeenDictionary(false);
setProtectPropertyTableWhileTransitioning(false);
setTransitionOffset(vm, invalidOffset);
setMaxOffset(vm, invalidOffset);
m_blob = TypeInfoBlob(0, typeInfo);
tsanRelaxedStore(m_outOfLineTypeFlags, typeInfo.outOfLineTypeFlags());
ASSERT(hasAnyKindOfGetterSetterProperties() == m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::AccessorOrCustomAccessorOrValue)));
ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() == m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessorOrValue)));
ASSERT(!this->typeInfo().overridesGetCallData() || m_classInfo->methodTable.getCallData != &JSCell::getCallData);
ASSERT(WTF::roundUpToMultipleOf<Structure::atomSize>(this) == this);
// Publication release — see the 7-argument constructor above.
if (Options::useJSThreads()) [[unlikely]]
WTF::storeStoreFence();
}
Structure::Structure(VM& vm, StructureVariant variant, Structure* previous)
: JSCell(vm, vm.structureStructure.get())
, m_seenProperties(previous->m_seenProperties)
, m_prototype(previous->m_prototype.get(), WriteBarrierEarlyInit)
, m_transitionWatchpointSet(IsWatched)
{
// §8.9 wave 3: TSAN-relaxed scalar init instead of member-init-list plain
// stores — see the 7-argument constructor above for the full rationale.
// The reads of `previous`'s fields are TSAN-relaxed too: `previous` is a
// published structure whose same words are concurrently written nowhere
// (post-ctor immutable) but whose own construction may not be
// TSAN-visible to this thread. m_seenProperties stays in the init list:
// its copy reads the source word with a relaxed load, and the member's
// own storage is written via ConcurrentCtorMember's deferred-ctor
// relaxed stores (§10.9 fixShape (1) — the r3 70-report key was the
// TinyBloomFilter NSDMI's std::atomic-constructor plain store, which the
// union wrapper now skips). m_prototype's EarlyInit ctor stores through
// the relaxed-atomic WriteBarrierBase accessors.
tsanRelaxedStore(m_inlineCapacity, tsanRelaxedLoad(previous->m_inlineCapacity));
tsanRelaxedStore(m_bitField, static_cast<uint32_t>(0));
tsanRelaxedStore(m_transitionPropertyAttributes, static_cast<TransitionPropertyAttributes>(0));
tsanRelaxedStore(m_structureVariant, variant);
tsanRelaxedStore(m_propertyHash, tsanRelaxedLoad(previous->m_propertyHash));
tsanRelaxedStore(m_classInfo, tsanRelaxedLoad(previous->m_classInfo));
// SPEC-objectmodel §5: transition targets also start IsWatched flag-on; a
// shared instance transitioning INTO this structure fires the target's sets
// per-event (F2/§4.2-0) before publishing, so fresh-valid is sound.
// Flag-off both sets keep their inert NSDMI ClearWatchpoint (I22).
//
// F4 monotonicity at creation time (GIL-ON put_by_id/delete_by_id IC
// livelock, staging semantics/ic-{put,delete}_by_id-vs-transition.js):
// each TTL set is born ALREADY-INVALID when the parent's same set has
// fired. The F4 chain-fire propagates firing to every successor that
// exists at fire time; a successor created AFTERWARDS used to be born
// fresh-valid, which is non-monotone — and for transitions that are
// never cached in the transition table (hasBeenDictionary() sources skip
// both the existing-transition lookup and the m_transitionTable.add), the
// §2 RESTART loop in putDirectInternal re-created a fresh-valid target on
// EVERY iteration: tryStructureOnlyTransition/trySegmentedTransition step
// 0 then saw anyTTLSetStillValid(source, target) true through the fresh
// target alone, fired it under a full stop-the-world, returned false
// (RESTART), and the next iteration made another fresh target — an
// unbounded fire->RESTART livelock on a shared object whose source family
// already has fired sets (observed: >12min inside one JS put). Inheriting
// per-set invalidity makes the retry converge (the re-created target no
// longer satisfies anyTTLSetStillValid) and matches what the chain-fire
// would have produced had this structure existed when the parent fired.
// The plain invalidating store is sound without a stop: this structure is
// unpublished (no other thread can reference it), the sets are thin (no
// Watchpoints installed, no compiled code can depend on them), and
// invalidate() on a thin set neither allocates nor iterates — so the
// constructor no-fire rule below is respected. Consumers only gate
// optimizations on IsStillValid/IsValidAndWatched, so born-invalid merely
// disables thread-locality elision for the new shape, exactly as F4
// intends for a shared family. Flag-off unchanged (I22).
if (Options::useJSThreads()) [[unlikely]] {
if (previous->transitionThreadLocalIsStillValid()) [[likely]]
m_transitionThreadLocalWatchpointSet.startWatching();
else
m_transitionThreadLocalWatchpointSet.invalidate(vm, StringFireDetail("F4: transition target created from a structure whose transitionThreadLocal set already fired"));
if (previous->writeThreadLocalIsStillValid()) [[likely]]
m_writeThreadLocalWatchpointSet.startWatching();
else
m_writeThreadLocalWatchpointSet.invalidate(vm, StringFireDetail("F4: transition target created from a structure whose writeThreadLocal set already fired"));
}
// N1: the structure transition TID is the CREATOR's TID, copied to targets
// (§2.1) - the shape's butterfly-less transition ownership follows the
// shape's creator, not whichever thread happens to reuse the shape.
// (Unconditional: flag-off previous' TID is always 0 - a single 16-bit
// copy, no Options load. TSAN-relaxed pair, plain non-TSAN.)
tsanRelaxedStore(m_transitionThreadLocalTID, tsanRelaxedLoad(previous->m_transitionThreadLocalTID));
setDictionaryKind(previous->dictionaryKind());
setIsPinnedPropertyTable(false);
setHasBeenFlattenedBefore(previous->hasBeenFlattenedBefore());
setHasAnyKindOfGetterSetterProperties(previous->hasAnyKindOfGetterSetterProperties());
setHasReadOnlyOrGetterSetterPropertiesExcludingProto(previous->hasReadOnlyOrGetterSetterPropertiesExcludingProto());
setHasNonEnumerableProperties(previous->hasNonEnumerableProperties());
setHasSpecialProperties(previous->hasSpecialProperties());
setHasNonConfigurableProperties(previous->hasNonConfigurableProperties());
setHasNonConfigurableReadOnlyOrGetterSetterProperties(previous->hasNonConfigurableReadOnlyOrGetterSetterProperties());
setHasUnderscoreProtoPropertyExcludingOriginalProto(previous->hasUnderscoreProtoPropertyExcludingOriginalProto());
setIsQuickPropertyAccessAllowedForEnumeration(previous->isQuickPropertyAccessAllowedForEnumeration());
setTransitionPropertyAttributes(0);
setTransitionKind(TransitionKind::Unknown);
setMayBePrototype(previous->mayBePrototype());
setDidPreventExtensions(previous->didPreventExtensions());
setDidTransition(true);
setStaticPropertiesReified(previous->staticPropertiesReified());
setHasBeenDictionary(previous->hasBeenDictionary());
setProtectPropertyTableWhileTransitioning(false);
setTransitionOffset(vm, invalidOffset);
setMaxOffset(vm, invalidOffset);
TypeInfo typeInfo = previous->typeInfo();
m_blob = TypeInfoBlob(previous->indexingModeIncludingHistory(), typeInfo);
tsanRelaxedStore(m_outOfLineTypeFlags, typeInfo.outOfLineTypeFlags());
ASSERT(!previous->typeInfo().structureIsImmortal());
setPreviousID(vm, previous);
// Do not fire watchpoint inside Structure constructor since watchpoint can involve further heap allocations.
// We fire watchpoint separately in Structure::finishCreation.
previous->didTransitionFromThisStructureWithoutFiringWatchpoint();
// Copy this bit now, in case previous was being watched.
setTransitionWatchpointIsLikelyToBeFired(previous->transitionWatchpointIsLikelyToBeFired());
// §10.9: relaxed-atomic store (setWithoutWriteBarrier) + explicit barrier
// instead of .set()'s plain setEarlyValue exchange — realm() readers can
// probe this recycled cell concurrently. Identical codegen.
if (JSGlobalObject* previousRealm = previous->m_realm.get()) {
ASSERT(!Options::useConcurrentJIT() || !isCompilationThread()); // Same assert .set() performed.
validateCell(previousRealm);
m_realm.setWithoutWriteBarrier(previousRealm);
vm.writeBarrier(this, previousRealm);
}
ASSERT(hasAnyKindOfGetterSetterProperties() || !m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::AccessorOrCustomAccessorOrValue)));
ASSERT(hasReadOnlyOrGetterSetterPropertiesExcludingProto() || !m_classInfo->hasStaticPropertyWithAnyOfAttributes(static_cast<uint8_t>(PropertyAttribute::ReadOnlyOrAccessorOrCustomAccessorOrValue)));
ASSERT(!this->typeInfo().overridesGetCallData() || m_classInfo->methodTable.getCallData != &JSCell::getCallData);
ASSERT(WTF::roundUpToMultipleOf<Structure::atomSize>(this) == this);
// Publication release — see the 7-argument constructor above.
if (Options::useJSThreads()) [[unlikely]]
WTF::storeStoreFence();
}
Structure::~Structure() = default;
void Structure::destroy(JSCell* cell)
{
auto* structure = static_cast<Structure*>(cell);
switch (structure->variant()) {
case StructureVariant::Normal:
structure->Structure::~Structure();
break;
case StructureVariant::Branded:
static_cast<BrandedStructure*>(structure)->BrandedStructure::~BrandedStructure();
break;
case StructureVariant::WebAssemblyGC:
#if ENABLE(WEBASSEMBLY)
static_cast<WebAssemblyGCStructure*>(structure)->WebAssemblyGCStructure::~WebAssemblyGCStructure();
#endif
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
}
Structure* Structure::create(PolyProtoTag, VM& vm, JSGlobalObject* globalObject, JSObject* prototype, const TypeInfo& typeInfo, const ClassInfo* classInfo, IndexingType indexingType, unsigned inlineCapacity)
{
// Task 3b: deliberately NO StructureAllocationLocker here — the delegated
// Structure::create below takes it internally (StructureCreateInlines.h)
// and the SAL is non-recursive (nesting self-deadlocks; vmstate §5.2/§5.3).
Structure* result = Structure::create(vm, globalObject, prototype, typeInfo, classInfo, indexingType, inlineCapacity);
unsigned oldOutOfLineCapacity = result->outOfLineCapacity();
result->addPropertyWithoutTransition(
vm, vm.propertyNames->builtinNames().polyProtoName(), static_cast<unsigned>(PropertyAttribute::DontEnum),
[&] (const GCSafeConcurrentJSLocker&, PropertyOffset offset, PropertyOffset newMaxOffset) {
RELEASE_ASSERT(Structure::outOfLineCapacity(newMaxOffset) == oldOutOfLineCapacity);
RELEASE_ASSERT(offset == knownPolyProtoOffset);
RELEASE_ASSERT(isInlineOffset(knownPolyProtoOffset));
result->m_prototype.setWithoutWriteBarrier(JSValue());
result->setMaxOffset(vm, newMaxOffset);
});
ASSERT(result->type() == StructureType);
return result;
}
bool Structure::isValidPrototype(JSValue prototype)
{
return prototype.isNull() || (prototype.isObject() && prototype.getObject()->mayBePrototype());
}
bool Structure::findStructuresAndMapForMaterialization(Vector<Structure*, 8>& structures, Structure*& structure, PropertyTable*& table)
{
ASSERT(structures.isEmpty());
table = nullptr;
for (structure = this; structure; structure = structure->previousID()) {
structure->m_lock.lock();
table = structure->propertyTableOrNull();
if (table) {
// Leave the structure locked, so that the caller can do things to it atomically
// before it loses its property table.
return true;
}
structures.append(structure);
structure->m_lock.unlock();
}
ASSERT(!structure);
ASSERT(!table);
return false;
}
// SPEC-objectmodel L6(ii) (Task 3c): materialize is already L6-conformant and
// needs no flag gate —
// - the chain walk (findStructuresAndMapForMaterialization) inspects each
// structure's table slot under THAT structure's m_lock, one at a time;
// - the SOURCE-table copy below runs while the found structure's m_lock is
// still held (findStructures... returns with it locked), so it cannot race
// a locked mutation of that published table;
// - the rebuilt table is PRIVATE until the GCSafe-locked setPropertyTable
// publication below (mutated lock-free before that, per L6);
// - O1: the function-scope DeferGC below is the sanctioned pre-lock deferral
// for every allocation made under m_lock here (copy, create, table->add).
// Callers must NOT hold this structure's m_lock.
PropertyTable* Structure::materializePropertyTable(VM& vm, bool setPropertyTable)
{
ASSERT(!isCompilationThread());
ASSERT(structure()->classInfoForCells() == info());
ASSERT(!protectPropertyTableWhileTransitioning());
DeferGC deferGC(vm);
Vector<Structure*, 8> structures;
Structure* structure;
PropertyTable* table;
bool didFindStructure = findStructuresAndMapForMaterialization(structures, structure, table);
unsigned capacity = numberOfSlotsForMaxOffset(maxOffset(), m_inlineCapacity);
if (didFindStructure) {
table = table->copy(vm, capacity);
structure->m_lock.unlock();
} else
table = PropertyTable::create(vm, capacity);
// Must hold the lock on this structure, since we will be modifying this structure's
// property map. We don't want getConcurrently() to see the property map in a half-baked
// state.
GCSafeConcurrentJSLocker locker(m_lock, vm);
// T3 (flag-on): publish AFTER the replay loop below, not before. The
// lock-free fast path in getConcurrently probes the published slot
// WITHOUT m_lock; between replay steps the table's edit stamp is even
// but the table is not yet exact for this structure, so an early
// publication would let a probe validate a WRONG miss/attribute. Keeping
// the table private until the replay completes restores the invariant
// "a published head table is exact for its structure at any even
// stamp". Locked readers never saw the half-baked table either way (we
// hold m_lock across both orders). Flag-off: today's publish-first
// order, byte-identical (I22).
bool deferPublicationUntilExact = Options::useJSThreads() && setPropertyTable;
if (setPropertyTable && !deferPublicationUntilExact)
this->setPropertyTable(vm, table);
// CVE A5 (MC-DF S4 / MC-INIT 4-adj; SPEC-objectmodel §6 I18/D1/I34/L6):
// the flag-off replay below RE-DERIVES every PropertyAddition link's
// offset via nextOffset() and asserts it equals the link's recorded
// transitionOffset(). Flag-off that derivation is a pure function of the
// chain (m_deletedOffsets is a plain LIFO), so the assert is sound.
// Flag-on it is NOT: nextOffset() draws from Reusable, which is fed
// SOLELY by §6 quarantine-epoch promotion — at ORIGINAL transition time
// a deleted offset may or may not have been promoted depending on whether
// a collection stop fell between the delete and the re-add, and that
// timing is unrecoverable here (the original table carrying the stamps is
// gone — stolen by a racing transition or swept by GC). The recorded
// transitionOffset() is therefore the ONLY authoritative replay source;
// re-derivation produces an internally-inconsistent table whose deleted-
// offset bookkeeping has drifted from its entries (the :717 assert in
// mc-jit-delete-reuse-stale-offset.CRASH{,.nojit}.log; downstream the
// drifted table hands out an already-live or past-maxOffset slot to the
// next add → cross-slot aliasing / slack read, the cellHeaderConcurrentLoad
// SEGV in mc-df-delete-reuse.CRASH.log).
//
// Flag-on discipline: keep the table's §6 deleted-offset lists EMPTY for
// the duration of the replay (so PropertyTable::add()'s I18 asserts hold
// for every recorded offset), track the deleted-offset SET locally, and
// for each PropertyAddition link CONSUME the recorded offset from that
// local set. After the loop, re-quarantine the residual set at the
// CURRENT epoch via addDeletedOffset(): a conservative re-stamp (the
// original deletion stamps are gone) that strictly upholds I18 — at worst
// the next add takes one fresh slot instead of a reusable one until the
// next stop. The residual's |size| + table->size() equals this
// structure's numberOfSlotsForMaxOffset, so propertyStorageSize() and
// checkOffsetConsistency below are exact.
//
// Flag-off: today's nextOffset()/addDeletedOffset() replay, unchanged
// (I22 — replayFromRecord is the latched single predicted-false branch;
// the local Vector is the same I22-noise class as `structures` above).
const bool replayFromRecord = Options::useJSThreads();
Vector<PropertyOffset, 8> replayDeletedOffsets;
if (replayFromRecord) [[unlikely]] {
// Drain the COPIED source table's combined Quarantined+Reusable into
// the local set: max-epoch promotion flushes Quarantined→Reusable
// (every real stamp is < max), then takeDeletedOffset() empties
// Reusable. After this both table lists are empty for the loop.
table->releaseQuarantinedSlots(std::numeric_limits<uint64_t>::max());
while (table->hasDeletedOffset())
replayDeletedOffsets.append(table->takeDeletedOffset());
}
for (size_t i = structures.size(); i--;) {
structure = structures[i];
if (!structure->m_transitionPropertyName)
continue;
switch (structure->transitionKind()) {
case TransitionKind::PropertyAddition: {
PropertyTableEntry entry(structure->m_transitionPropertyName.get(), structure->transitionOffset(), structure->transitionPropertyAttributes());
if (replayFromRecord) [[unlikely]] {
// Recorded offset is authoritative (CVE A5). Consume it from
// the local deleted set if it was a reused slot; otherwise it
// must be the fresh past-end slot (size + |deleted|) — the
// epoch-INDEPENDENT consistency check that replaces the
// unsound nextOffset()==transitionOffset() assert flag-on.
PropertyOffset recorded = structure->transitionOffset();
bool wasDeleted = replayDeletedOffsets.removeLast(recorded);
ASSERT_UNUSED(wasDeleted, wasDeleted || recorded == offsetForPropertyNumber(table->size() + static_cast<unsigned>(replayDeletedOffsets.size()), structure->inlineCapacity()));
auto [offset, attribute, result] = table->add(vm, entry);
ASSERT_UNUSED(result, result);
ASSERT_UNUSED(offset, offset == recorded);
UNUSED_VARIABLE(attribute);
break;
}
auto nextOffset = table->nextOffset(structure->inlineCapacity());
ASSERT_UNUSED(nextOffset, nextOffset == structure->transitionOffset());
auto [offset, attribute, result] = table->add(vm, entry);
ASSERT_UNUSED(result, result);
ASSERT_UNUSED(offset, offset == nextOffset);
UNUSED_VARIABLE(attribute);
break;
}
case TransitionKind::PropertyDeletion: {
auto [offset, attributes] = table->take(vm, structure->m_transitionPropertyName.get());
ASSERT_UNUSED(offset, offset != invalidOffset);
UNUSED_VARIABLE(attributes);
if (replayFromRecord) [[unlikely]] {
// Track locally; do NOT touch the table's §6 lists mid-replay
// (an addDeletedOffset() here would stamp at NOW and the next
// PropertyAddition link could not draw it — exactly the bug).
ASSERT(offset == structure->transitionOffset());
replayDeletedOffsets.append(structure->transitionOffset());
break;
}
table->addDeletedOffset(structure->transitionOffset());
break;
}
case TransitionKind::PropertyAttributeChange: {
PropertyOffset offset = table->updateAttributeIfExists(structure->m_transitionPropertyName.get(), structure->transitionPropertyAttributes());
ASSERT_UNUSED(offset, offset == structure->transitionOffset());
break;
}
case TransitionKind::SetBrand: {
continue;
}
default:
ASSERT_NOT_REACHED();
break;
}
}
if (replayFromRecord) [[unlikely]] {
// Re-quarantine the residual deleted-offset set at the current epoch
// (conservative; I18-safe — see the block comment above). After this,
// propertyStorageSize() == size() + |residual| == this structure's
// numberOfSlotsForMaxOffset, so checkOffsetConsistency below holds.
for (PropertyOffset deleted : replayDeletedOffsets)
table->addDeletedOffset(deleted);
}
if (deferPublicationUntilExact)
this->setPropertyTable(vm, table); // T3: now exact — publish (still under m_lock; fence inside orders the fill).
checkOffsetConsistency(
table,
[&] () {
dataLog("Detected in materializePropertyTable.\n");
dataLog("Found structure = ", RawPointer(structure), "\n");
dataLog("structures = ");
CommaPrinter comma;
for (Structure* structure : structures)
dataLog(comma, RawPointer(structure));
dataLog("\n");
});
return table;
}
bool Structure::holesMustForwardToPrototypeSlow(JSObject* base) const
{
ASSERT(base->structure() == this);
if (this->mayInterceptIndexedAccesses())
return true;
JSValue prototype = this->storedPrototype(base);
if (!prototype.isObject())
return false;
JSObject* object = asObject(prototype);
while (true) {
Structure& structure = *object->structure();
if (hasIndexedProperties(object->indexingType()) || structure.mayInterceptIndexedAccesses())
return true;
prototype = structure.storedPrototype(object);
if (!prototype.isObject())
return false;
object = asObject(prototype);
}
RELEASE_ASSERT_NOT_REACHED();
return false;
}
Structure* Structure::addPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset)
{
Structure* newStructure = addPropertyTransitionToExistingStructure(structure, propertyName, attributes, offset);
if (newStructure)
return newStructure;
return addNewPropertyTransition(vm, structure, propertyName, attributes, offset, PutPropertySlot::UnknownContext);
}
Structure* Structure::addNewPropertyTransition(VM& vm, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset& offset, PutPropertySlot::Context context, DeferredStructureTransitionWatchpointFire* deferred)
{
ASSERT(!structure->isDictionary());
ASSERT(structure->isObject());
// SPEC-objectmodel L6/I37 (Task 3c): flag-on, the caller's existing-transition
// lookup (addPropertyTransition / putDirectInternal) and this call are not one
// atomic step -- a racing mutator can publish the identical (uid, attributes,
// PropertyAddition) transition between the caller's locked miss and here. Re-check
// under the source's m_lock and adopt the winner (its transitionOffset is
// authoritative) instead of asserting; this also skips the doomed Structure
// allocation. The locked dual-check before m_transitionTable.add() below remains
// the correctness guard for the window between this recheck and the insert.
// Note: placing the recheck before shouldDoCacheableDictionaryTransitionForAdd
// means a loser whose context would have chosen a cacheable-dictionary transition
// adopts the winner's PropertyAddition instead -- flag-on-only heuristic
// divergence, intentionally accepted.
// Flag-off: today's debug assert, bit-identical behavior (I22).
if (Options::useJSThreads()) [[unlikely]] {
if (Structure* existing = addPropertyTransitionToExistingStructureConcurrently(structure, propertyName.uid(), attributes, offset)) {
existing->checkOffsetConsistency();
return existing;
}
} else
ASSERT(!Structure::addPropertyTransitionToExistingStructure(structure, propertyName, attributes, offset));
if (structure->shouldDoCacheableDictionaryTransitionForAdd(context)) {
ASSERT(!isCopyOnWrite(structure->indexingMode()));
Structure* transition = toCacheableDictionaryTransition(vm, structure, deferred);
ASSERT(structure != transition);
offset = transition->add(vm, propertyName, attributes);
return transition;
}
// SPEC-objectmodel Task 3b (SPEC-vmstate §5.3): the transition Structure's
// cell allocation and the allocating transition-table insertion below run
// under the structure-allocation lock (SAL, rank 7a), acquired OUTSIDE
// Structure::m_lock per the §6 lock order (SAL < JSCellLock < m_lock).
// Flag-on only:
// - salDeferGC keeps GC triggers out of the SAL regions (heap L5 / S1:
// never collect or park for STW holding the SAL; O1's sanctioned
// pre-lock DeferGC). Structure::create(vm, previous, deferred) cannot
// thread the locker's GCDeferralContext into its allocateCell (its body
// lives in StructureInlines.h, not a [SAL] emission file) — recorded in
// INTEGRATE-objectmodel.md for the vmstate M7 audit.
// - salDeferredFire guarantees the previous structure's transition
// watchpoints never fire inline inside Structure::create while the SAL
// is held: watchpoint firing may take rank-6b CodeBlock/jit locks,
// which are OUTER to ours and must never be acquired holding the SAL.
// I22 latched-option pattern (see StructureInlines.h
// addOrReplacePropertyWithoutTransition): one Config load at function
// entry; the compiler can then prove every SAL optional below is
// disengaged on the flag-off arm and elide the engaged-dtor checks, so
// the flag-off body is the pre-threads body behind a single
// predicted-false branch. (Options are frozen after init, so the latch
// is semantics-preserving; the three loads below could not be CSE'd
// across the opaque Structure::create / GCSafe-locker calls.)
const bool useSAL = Options::useStructureAllocationLock();
std::optional<DeferGC> salDeferGC;
std::optional<DeferredStructureTransitionWatchpointFire> salDeferredFire;
if (useSAL) [[unlikely]] {
salDeferGC.emplace(vm);
if (!deferred) {
salDeferredFire.emplace(vm, structure);
deferred = &*salDeferredFire;
}
}
Structure* transition;
{
// I10 at the call site: the locker's flag-off no-op lives behind a
// cross-DSO out-of-line call (VMLiteShared.cpp); gate construction on
// the same latched option so flag-off emits no call at all. (Same
// pattern at every StructureAllocationLocker site in this file.)
std::optional<SharedVMState::StructureAllocationLocker> structureAllocationLocker;
if (useSAL) [[unlikely]]
structureAllocationLocker.emplace(vm);
transition = Structure::create(vm, structure, deferred);
}
transition->m_cachedPrototypeChain.setMayBeNull(vm, transition, structure->cachedPrototypeChainConcurrently()); // Relaxed atomic read: the source chain slot is written lock-free (TSAN family structure-fields).
// While we are adding the property, rematerializing the property table is super weird: we already
// have a m_transitionPropertyName and transitionPropertyAttributes but the m_transitionOffset is still wrong. If the
// materialization algorithm runs, it'll build a property table that already has the property but
// at a bogus offset. Rather than try to teach the materialization code how to create a table under
// those conditions, we just tell the GC not to blow the table away during this period of time.
// Holding the lock ensures that we either do this before the GC starts scanning the structure, in
// which case the GC will not blow the table away, or we do it after the GC already ran in which
// case all is well. If it wasn't for the lock, the GC would have TOCTOU: if could read
// protectPropertyTableWhileTransitioning before we set it to true, and then blow the table away after.
{
ConcurrentJSLocker locker(transition->m_lock);
transition->setProtectPropertyTableWhileTransitioning(true);
}
transition->m_blob.setIndexingModeIncludingHistory(structure->indexingModeIncludingHistory() & ~CopyOnWrite);
transition->m_transitionPropertyName = propertyName.uid();
transition->setTransitionPropertyAttributes(attributes);
transition->setTransitionKind(TransitionKind::PropertyAddition);
transition->setPropertyTable(vm, structure->takePropertyTableOrCloneIfPinned(vm));
transition->setMaxOffset(vm, structure->maxOffset());
offset = transition->add(vm, propertyName, attributes);
transition->setTransitionOffset(vm, offset);
// Now that everything is fine with the new structure's bookkeeping, the GC is free to blow the
// table away if it wants. We can now rebuild it fine.
WTF::storeStoreFence();
transition->setProtectPropertyTableWhileTransitioning(false);
checkOffset(transition->transitionOffset(), transition->inlineCapacity());
if (!structure->hasBeenDictionary()) {
// Task 3b: SAL outside m_lock (§6 order); salDeferGC above keeps the
// GCSafe locker's deferred collection from starting under the SAL.
std::optional<SharedVMState::StructureAllocationLocker> structureAllocationLocker;
if (useSAL) [[unlikely]]
structureAllocationLocker.emplace(vm);
GCSafeConcurrentJSLocker locker(structure->m_lock, vm);
// SPEC-objectmodel L6/I37 (Task 3c): dual-check under m_lock — a
// racing thread may have published an identical transition between
// our locked lookup miss and this insert. Adopt the winner: blindly
// add()ing would clobber a Structure other instances already use
// (lost transition). Our candidate is discarded unreferenced; if it
// stole the source's table, the source simply rematerializes from its
// transition chain on demand. The winner's offset is authoritative