forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathHeap.cpp
More file actions
8744 lines (7983 loc) · 436 KB
/
Copy pathHeap.cpp
File metadata and controls
8744 lines (7983 loc) · 436 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) 2003-2026 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "config.h"
#include "Heap.h"
#include "JSCJSValueInlines.h"
#include "BuiltinExecutables.h"
#include "CodeBlock.h"
#include "CodeBlockSetInlines.h"
#include "CollectingScope.h"
#include "ConservativeRoots.h"
#include "EdenGCActivityCallback.h"
#include "EvalExecutable.h"
#include "Exception.h"
#include "FastMallocAlignedMemoryAllocator.h"
#include "FullGCActivityCallback.h"
#include "FunctionExecutableInlines.h"
#include "GCActivityCallback.h"
#include "GCIncomingRefCountedInlines.h"
#include "GCIncomingRefCountedSetInlines.h"
#include "GCSegmentedArrayInlines.h"
#include "GCTypeMap.h"
#include "GigacageAlignedMemoryAllocator.h"
#include "HasOwnPropertyCache.h"
#include "HeapHelperPool.h"
#include "HeapIterationScope.h"
#include "HeapProfiler.h"
#include "HeapSnapshot.h"
#include "JSCJSValueInlines.h"
#include "HeapSubspaceTypes.h"
#include "HeapVerifier.h"
#include "IncrementalSweeper.h"
#include "Interpreter.h"
#include "IsoCellSetInlines.h"
#include "IsoInlinedHeapCellTypeInlines.h"
#include "JITStubRoutineSet.h"
#include "JITWorklistInlines.h"
#include "JSFinalizationRegistry.h"
#include "JSThreadsSafepoint.h"
#include "JSFunctionWithFields.h"
#include "JSIterator.h"
#include "JSMicrotaskDispatcher.h"
#include "JSModuleLoader.h"
#include "JSPromiseCombinatorsContext.h"
#include "JSPromiseCombinatorsGlobalContext.h"
#include "JSPromiseReaction.h"
#include "JSRawJSONObject.h"
#include "JSRemoteFunction.h"
#include "JSSentinel.h"
#include "JSVirtualMachineInternal.h"
#include "JSWeakMap.h"
#include "JSWeakObjectRef.h"
#include "JSWeakSet.h"
#include "MachineStackMarker.h"
#include "MarkStackMergingConstraint.h"
#include "MarkedSpaceInlines.h"
#include "MarkingConstraintSet.h"
#include "MegamorphicCache.h"
#include "ModuleLoadingContext.h"
#include "ModuleProgramExecutable.h"
#include "ModuleRegistryEntry.h"
#include "NumberObject.h"
#include "PinballCompletion.h"
#include "PreventCollectionScope.h"
#include "RaceAmplifier.h"
#include "ProgramExecutable.h"
#include "ProxyObject.h"
#include "SamplingProfiler.h"
#include "ShadowChicken.h"
#include "SpaceTimeMutatorScheduler.h"
#include "StochasticSpaceTimeMutatorScheduler.h"
#include "StopIfNecessaryTimer.h"
#include "StructureAlignedMemoryAllocator.h"
#include "SubspaceInlines.h"
#include "SuperSampler.h"
#include "SweepingScope.h"
#include "SymbolTableInlines.h"
#include "SynchronousStopTheWorldMutatorScheduler.h"
#include "TypeProfiler.h"
#include "TypeProfilerLog.h"
#include "UnlinkedEvalCodeBlock.h"
#include "StopTheWorldCallback.h" // THREADS T5: StopTheWorldEvent for the §10.2 follower park.
#include "Structure.h" // UNGIL §D.1 (U-T12): transition-TID restamp + D1R TTL fires in the rebias stop.
#include "ThreadManager.h" // UNGIL §D.1 (U-T12): the dead-TID snapshot hand-off (two-phase vs §LK).
#include "VM.h"
#include "VMLite.h"
#include "VMLiteShared.h"
#include "VMManager.h" // THREADS T5 (§10.3/§10.9 + manifest items 4-5): requestStopAll/requestResumeAll(StopReason::GC), setGCParkCallbacks.
#include "VMTraps.h" // THREADS T5 (§10.2): election followers poll the stop-the-world trap bit.
#include "VerifierSlotVisitorInlines.h"
#include "WasmCallee.h"
#include "WeakMapImplInlines.h"
#include "WeakSetInlines.h"
#include <algorithm>
#include <wtf/AvailableMemory.h>
#include <wtf/BitVector.h> // UNGIL §D.1 (U-T12): the in-stop dead-TID membership set.
#include <atomic>
#include <wtf/CryptographicallyRandomNumber.h>
#include <wtf/ListDump.h>
#include <wtf/MemoryFootprint.h>
#include <wtf/RAMSize.h>
#include <wtf/Scope.h>
#include <wtf/SetForScope.h>
#include <wtf/SimpleStats.h>
#include <wtf/SystemTracing.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/Threading.h>
#include "InternalFieldTuple.h"
#if USE(BUN_JSC_ADDITIONS)
#include "JSString.h"
#include <wtf/text/ExternalStringImpl.h>
#endif
#if USE(FOUNDATION)
#include <wtf/spi/cocoa/objcSPI.h>
#endif
#ifdef JSC_GLIB_API_ENABLED
#include "JSCGLibWrapperObject.h"
#endif
namespace JSC {
// ===== UNGIL §A.3 (U-T5) cross-TU seams =====
// Defined in runtime/VMManager.cpp (window state + ticket park) and
// runtime/VMLite.cpp (ANNEX ISB1 stop-generation sync). Their headers
// (VMManager.h / VMLite.h) are OUTSIDE U-T5's writable file set; lifting
// these declarations into those headers is an orchestrator-tracked cleanup.
// Signatures must stay byte-identical to the definitions.
bool jsThreadsStopPendingFor(VM&); // seq_cst stop-word load (SB1; sole accessor pair lives in VMManager.cpp — U20).
bool jsThreadsCurrentThreadIsStopConductor(); // §A.3.3 tenure check (HBT3.2 self-exemption).
bool jsThreadsThreadGranularWorldIsStopped(); // §A.3.2 post-quiescence depth (AB-10 class-4 conductor disjuncts).
void jsThreadsParkForStopWindow(VM&); // NVS ticket park; pre: caller holds NO heap access.
void jsThreadsNotifyMutatorQuiesced(); // wakes the conductor's §A.3.2 predicate wait.
void jsThreadsSyncToStopGenerationBeforeJITEntry(); // ANNEX ISB1.2 (VMLite.cpp).
void jsThreadsBumpStopGeneration(); // ANNEX ISB1.1 (VMLite.cpp); bumped by EVERY conductor — §A.3 AND the §10 shared-GC conductor below.
bool jsThreadsModeStopGatesCurrentThread(VM&); // SPEC-ungil §A.3.2b(i): Mode-machine stop bit gates fresh access (VMManager.cpp).
void jsThreadsParkForModeStop(VM&); // §A.3.2b(i) NVS park until the Mode machine resumes; pre: caller holds NO heap access.
// ===== gc-sharedheap-zero-concurrent-overlap-now-11pct (SPEC-congc §7.1a) =====
//
// SCALEBENCH §35 round-2 measured Σp = Σcycle (zero mutator/marker overlap)
// under the pinned GIL-off env: every shared collection is a single STW
// window (§3.6 degenerate), and the i#1 root pass (Cs/Msr/Wlr/Msm) + bulk
// drainInParallel runs with all W siblings parked. At W=16 that fixed STW
// floor is ~143 ms = 11.0% of the 1291 ms wall — 45% of the residual JS->Java
// gap (Java W=16 = 976 ms). §27.S2 had previously REFUTED defaulting the full
// stage-C1 flag because at that tree (a) STW was only 5.4% of wall and (b)
// the unbounded scheduler-driven Concurrent handoffs added ~30 extra Reentry
// rendezvous per run (~9 ms each at W=16), eating the saving. Round-1's
// denominator shrink makes (a) no longer hold; (b) is the structural defect
// this lever bounds.
//
// sharedGCWindowedConductActive(): the §3 windowed conduct machinery
// (Reentry open / non-final close / §3.7 wait / F46 per-window atom-table
// pin / per-cycle reclaim placement) is live whenever a §13.2 stage flag is
// on OR the process is GIL-off. Under the gilOff arm the machinery runs in a
// BOUNDED single-handoff shape (§7.1a):
// - runFixpointPhase schedules AT MOST ONE Concurrent phase per cycle
// (t_sharedGCConcurrentHandoffsThisCycle, conductor-thread-local; reset in
// runBeginPhase's gilOff block) — the §27.S2(b) bound: extra rendezvous
// per conduct = #cycles, not scheduler-driven;
// - C1R stays OFF (sharedGCBarrierStateIsPerClient() unchanged): barriers
// keep the F44 multi-producer server-stack append, drained at the Reentry
// window's Msm constraint pass; the F19 server-master always-fenced pin
// holds under gilOff (setMutatorShouldBeFenced's `|| isGILOffProcess()`
// arm), so addToRememberedSet's unfenced ASSERT(isMarked) is unreachable
// and the fenced re-whiten CAS path (mutator-count-independent, §5.2
// CG-T3) covers between-window barrier execution. SPEC-congc §5.2/F44
// states CMS is contention/accounting only, NOT a soundness gate — so the
// single-handoff mode's correctness rests on the same §6.2 + §8.1 rules
// as full C1: Wlr/Cs are GreyedByExecution and re-run at the post-Reentry
// fixpoint (m_phaseVersion bumped by the Concurrent->Reloop edge), and
// every per-client LA is re-flushed by the Reentry stopThePeriphery
// (CG-I6 once-per-window pairing).
// Flag-off (useJSThreads=0 / useThreadGIL=1): VM::isGILOffProcess() is false,
// the predicate degenerates to sharedGCWindowedStagesEnabled() and every arm
// keyed on it stays byte-for-byte the §27.S2 default (CG-I0).
//
// File-local mirror of Heap::sharedGCWindowedStagesEnabled() (private; the
// option disjunction below MUST track Heap.h:1411 — both are the §13.2
// stage-flag list, validated by Options.cpp's prefix-rule check).
static ALWAYS_INLINE bool sharedGCWindowedConductActive()
{
return Options::useConcurrentSharedGCMarking() || Options::useSharedGCCollectorThread()
|| Options::useSharedGCIncrementalSweep() || Options::useSharedGCMutatorAssist()
|| VM::isGILOffProcess();
}
// Conductor-thread-local per-cycle handoff cap (§7.1a). Written and read only
// on the §3.7 closed-loop conductor thread (one cycle = one thread; CG-I19);
// reset at runBeginPhase's gilOff block, bumped at the runFixpointPhase
// gilOff scheduling arm. Unused outside gilOff (the C1 stage-flag arm is
// scheduler-driven, not capped).
static thread_local unsigned t_sharedGCConcurrentHandoffsThisCycle { 0 };
// NEVER_INLINE to prevent LTO from inlining this function, which can break
// compiler barriers in MarkedBlock::isMarked on x86_64.
NEVER_INLINE bool Heap::isMarked(const void* rawCell)
{
ASSERT(!m_isMarkingForGCVerifier);
HeapCell* cell = std::bit_cast<HeapCell*>(rawCell);
if (cell->isPreciseAllocation())
return cell->preciseAllocation().isMarked();
MarkedBlock& block = cell->markedBlock();
return block.isMarked(m_objectSpace.markingVersion(), cell);
}
namespace HeapInternal {
static constexpr bool verbose = false;
static constexpr bool verboseStop = false;
}
namespace {
double maxPauseMS(double thisPauseMS)
{
static double maxPauseMS;
maxPauseMS = std::max(thisPauseMS, maxPauseMS);
return maxPauseMS;
}
size_t minHeapSize(HeapType heapType, size_t ramSize)
{
switch (heapType) {
case HeapType::Large:
return static_cast<size_t>(std::min(
static_cast<double>(Options::largeHeapSize()),
ramSize * Options::smallHeapRAMFraction()));
case HeapType::Medium:
return Options::mediumHeapSize();
case HeapType::Small:
return Options::smallHeapSize();
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
}
size_t proportionalHeapSize(size_t heapSize, size_t ramSize)
{
if (VM::isInMiniMode())
return Options::miniVMHeapGrowthFactor() * heapSize;
bool useNewHeapGrowthFactor = true;
// Use new heuristic function for machines >= 16GB RAM.
// https://www.mathway.com/en/Algebra?asciimath=2%20*%20e%5E(-1%20*%20x)%20%2B%201%20%3Dy
size_t heapGrowthFunctionThresholdInBytes = static_cast<size_t>(Options::heapGrowthFunctionThresholdInMB()) * MB;
if (ramSize < heapGrowthFunctionThresholdInBytes)
useNewHeapGrowthFactor = false;
// Disable it for Darwin Intel machine.
#if OS(DARWIN) && CPU(X86_64)
useNewHeapGrowthFactor = false;
#endif
if (useNewHeapGrowthFactor) {
double x = static_cast<double>(std::min(heapSize, ramSize)) / ramSize;
double ratio = Options::heapGrowthMaxIncrease() * std::exp(-(Options::heapGrowthSteepnessFactor() * x)) + 1;
return ratio * heapSize;
}
#if USE(MEMORY_FOOTPRINT_API)
size_t memoryFootprint = WTF::memoryFootprint();
if (memoryFootprint < ramSize * Options::smallHeapRAMFraction())
return Options::smallHeapGrowthFactor() * heapSize;
if (memoryFootprint < ramSize * Options::mediumHeapRAMFraction())
return Options::mediumHeapGrowthFactor() * heapSize;
#else
if (heapSize < ramSize * Options::smallHeapRAMFraction())
return Options::smallHeapGrowthFactor() * heapSize;
if (heapSize < ramSize * Options::mediumHeapRAMFraction())
return Options::mediumHeapGrowthFactor() * heapSize;
#endif
return Options::largeHeapGrowthFactor() * heapSize;
}
void recordType(TypeCountSet& set, JSCell* cell)
{
auto typeName = "[unknown]"_s;
const ClassInfo* info = cell->classInfo();
if (info && info->className)
typeName = info->className;
set.add(typeName);
}
constexpr bool NODELETE measurePhaseTiming()
{
return false;
}
UncheckedKeyHashMap<const char*, GCTypeMap<SimpleStats>>& timingStats()
{
static UncheckedKeyHashMap<const char*, GCTypeMap<SimpleStats>>* result;
static std::once_flag once;
std::call_once(
once,
[] {
result = new UncheckedKeyHashMap<const char*, GCTypeMap<SimpleStats>>();
});
return *result;
}
SimpleStats& timingStats(const char* name, CollectionScope scope)
{
return timingStats().add(name, GCTypeMap<SimpleStats>()).iterator->value[scope];
}
class TimingScope {
public:
TimingScope(std::optional<CollectionScope> scope, ASCIILiteral name)
: m_scope(scope)
, m_name(name)
{
if (measurePhaseTiming())
m_before = MonotonicTime::now();
}
TimingScope(JSC::Heap& heap, ASCIILiteral name)
: TimingScope(heap.collectionScope(), name)
{
}
void NODELETE setScope(std::optional<CollectionScope> scope)
{
m_scope = scope;
}
void NODELETE setScope(JSC::Heap& heap)
{
setScope(heap.collectionScope());
}
~TimingScope()
{
if (measurePhaseTiming()) {
MonotonicTime after = MonotonicTime::now();
Seconds timing = after - m_before;
SimpleStats& stats = timingStats(m_name, *m_scope);
stats.add(timing.milliseconds());
dataLog("[GC:", *m_scope, "] ", m_name, " took: ", timing.milliseconds(), "ms (average ", stats.mean(), "ms).\n");
}
}
private:
std::optional<CollectionScope> m_scope;
MonotonicTime m_before;
ASCIILiteral m_name;
};
} // anonymous namespace
class Heap::HeapThread final : public AutomaticThread {
WTF_MAKE_TZONE_ALLOCATED_INLINE(HeapThread);
WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR(HeapThread);
public:
HeapThread(const AbstractLocker& locker, JSC::Heap& heap)
: AutomaticThread(locker, heap.m_threadLock, heap.m_threadCondition.copyRef())
, m_heap(heap)
{
}
ASCIILiteral name() const final
{
return "JSC Heap Collector Thread"_s;
}
private:
PollResult poll(const AbstractLocker& locker) final
{
if (m_heap.m_threadShouldStop) {
m_heap.notifyThreadStopping(locker);
return PollResult::Stop;
}
if (m_heap.shouldCollectInCollectorThread(locker)) {
m_heap.m_collectorThreadIsRunning = true;
return PollResult::Work;
}
m_heap.m_collectorThreadIsRunning = false;
return PollResult::Wait;
}
WorkResult work() final
{
m_heap.collectInCollectorThread();
return WorkResult::Continue;
}
void threadDidStart() final
{
Thread::registerGCThread(GCThreadType::Main);
}
void threadIsStopping(const AbstractLocker&) final
{
m_heap.m_collectorThreadIsRunning = false;
}
JSC::Heap& m_heap;
};
#define INIT_SERVER_ISO_SUBSPACE(name, heapCellType, type) \
, name ISO_SUBSPACE_INIT(*this, heapCellType, type)
#define INIT_SERVER_STRUCTURE_ISO_SUBSPACE(name, heapCellType, type) \
, name(#name, *this, heapCellType, WTF::roundUpToMultipleOf<type::atomSize>(sizeof(type)), type::numberOfLowerTierPreciseCells, makeUnique<StructureAlignedMemoryAllocator>())
Heap::Heap(VM& vm, HeapType heapType)
: m_heapType(heapType)
, m_ramSize(Options::forceRAMSize() ? Options::forceRAMSize() : ramSize())
, m_minBytesPerCycle(minHeapSize(m_heapType, m_ramSize))
, m_maxEdenSize(m_minBytesPerCycle)
, m_maxHeapSize(m_minBytesPerCycle)
, m_objectSpace(this)
, m_machineThreads(makeUnique<MachineThreads>())
, m_collectorSlotVisitor(makeUnique<SlotVisitor>(*this, "C"_s))
, m_mutatorSlotVisitor(makeUnique<SlotVisitor>(*this, "M"_s))
, m_mutatorMarkStack(makeUnique<MarkStackArray>())
, m_raceMarkStack(makeUnique<MarkStackArray>())
, m_constraintSet(makeUnique<MarkingConstraintSet>(*this))
, m_handleSet(vm)
, m_codeBlocks(makeUnique<CodeBlockSet>())
, m_jitStubRoutines(makeUnique<JITStubRoutineSet>())
// We seed with 10ms so that GCActivityCallback::didAllocate doesn't continuously
// schedule the timer if we've never done a collection.
, m_fullActivityCallback(FullGCActivityCallback::tryCreate(*this))
, m_edenActivityCallback(EdenGCActivityCallback::tryCreate(*this))
, m_sweeper(adoptRef(*new IncrementalSweeper(this)))
, m_stopIfNecessaryTimer(adoptRef(*new StopIfNecessaryTimer(vm)))
, m_sharedCollectorMarkStack(makeUnique<MarkStackArray>())
, m_sharedMutatorMarkStack(makeUnique<MarkStackArray>())
, m_helperClient(&heapHelperPool())
, m_threadLock(Box<Lock>::create())
, m_threadCondition(AutomaticThreadCondition::create())
// HeapCellTypes
, auxiliaryHeapCellType(CellAttributes(DoesNotNeedDestruction, HeapCell::Auxiliary))
, immutableButterflyHeapCellType(CellAttributes(DoesNotNeedDestruction, HeapCell::JSCellWithIndexingHeader))
, cellHeapCellType(CellAttributes(DoesNotNeedDestruction, HeapCell::JSCell))
, destructibleCellHeapCellType(CellAttributes(NeedsDestruction, HeapCell::JSCell))
, apiGlobalObjectHeapCellType(IsoHeapCellType::Args<JSAPIGlobalObject>())
, callbackConstructorHeapCellType(IsoHeapCellType::Args<JSCallbackConstructor>())
, callbackGlobalObjectHeapCellType(IsoHeapCellType::Args<JSCallbackObject<JSGlobalObject>>())
, callbackObjectHeapCellType(IsoHeapCellType::Args<JSCallbackObject<JSNonFinalObject>>())
, customGetterFunctionHeapCellType(IsoHeapCellType::Args<JSCustomGetterFunction>())
, customSetterFunctionHeapCellType(IsoHeapCellType::Args<JSCustomSetterFunction>())
, dateInstanceHeapCellType(IsoHeapCellType::Args<DateInstance>())
, errorInstanceHeapCellType(IsoHeapCellType::Args<ErrorInstance>())
, finalizationRegistryCellType(IsoHeapCellType::Args<JSFinalizationRegistry>())
, globalLexicalEnvironmentHeapCellType(IsoHeapCellType::Args<JSGlobalLexicalEnvironment>())
, globalObjectHeapCellType(IsoHeapCellType::Args<JSGlobalObject>())
, injectedScriptHostSpaceHeapCellType(IsoHeapCellType::Args<Inspector::JSInjectedScriptHost>())
, javaScriptCallFrameHeapCellType(IsoHeapCellType::Args<Inspector::JSJavaScriptCallFrame>())
, jsModuleRecordHeapCellType(IsoHeapCellType::Args<JSModuleRecord>())
, syntheticModuleRecordHeapCellType(IsoHeapCellType::Args<SyntheticModuleRecord>())
, moduleNamespaceObjectHeapCellType(IsoHeapCellType::Args<JSModuleNamespaceObject>())
, nativeStdFunctionHeapCellType(IsoHeapCellType::Args<JSNativeStdFunction>())
, weakMapHeapCellType(IsoHeapCellType::Args<JSWeakMap>())
, weakSetHeapCellType(IsoHeapCellType::Args<JSWeakSet>())
#if JSC_OBJC_API_ENABLED
, apiWrapperObjectHeapCellType(IsoHeapCellType::Args<JSCallbackObject<JSAPIWrapperObject>>())
, objCCallbackFunctionHeapCellType(IsoHeapCellType::Args<ObjCCallbackFunction>())
#endif
#ifdef JSC_GLIB_API_ENABLED
, apiWrapperObjectHeapCellType(IsoHeapCellType::Args<JSCallbackObject<JSAPIWrapperObject>>())
, callbackAPIWrapperGlobalObjectHeapCellType(IsoHeapCellType::Args<JSCallbackObject<JSAPIWrapperGlobalObject>>())
, jscCallbackFunctionHeapCellType(IsoHeapCellType::Args<JSCCallbackFunction>())
#endif
, intlCollatorHeapCellType(IsoHeapCellType::Args<IntlCollator>())
, intlDateTimeFormatHeapCellType(IsoHeapCellType::Args<IntlDateTimeFormat>())
, intlDisplayNamesHeapCellType(IsoHeapCellType::Args<IntlDisplayNames>())
, intlDurationFormatHeapCellType(IsoHeapCellType::Args<IntlDurationFormat>())
, intlListFormatHeapCellType(IsoHeapCellType::Args<IntlListFormat>())
, intlLocaleHeapCellType(IsoHeapCellType::Args<IntlLocale>())
, intlNumberFormatHeapCellType(IsoHeapCellType::Args<IntlNumberFormat>())
, intlPluralRulesHeapCellType(IsoHeapCellType::Args<IntlPluralRules>())
, intlRelativeTimeFormatHeapCellType(IsoHeapCellType::Args<IntlRelativeTimeFormat>())
, intlSegmentIteratorHeapCellType(IsoHeapCellType::Args<IntlSegmentIterator>())
, intlSegmenterHeapCellType(IsoHeapCellType::Args<IntlSegmenter>())
, intlSegmentsHeapCellType(IsoHeapCellType::Args<IntlSegments>())
, temporalTimeZoneHeapCellType(IsoHeapCellType::Args<TemporalTimeZone>())
#if ENABLE(WEBASSEMBLY)
, webAssemblyExceptionHeapCellType(IsoHeapCellType::Args<JSWebAssemblyException>())
, webAssemblyFunctionHeapCellType(IsoHeapCellType::Args<WebAssemblyFunction>())
, webAssemblyGlobalHeapCellType(IsoHeapCellType::Args<JSWebAssemblyGlobal>())
, webAssemblyInstanceHeapCellType(IsoHeapCellType::Args<JSWebAssemblyInstance>())
, webAssemblyMemoryHeapCellType(IsoHeapCellType::Args<JSWebAssemblyMemory>())
, webAssemblyModuleHeapCellType(IsoHeapCellType::Args<JSWebAssemblyModule>())
, webAssemblyModuleRecordHeapCellType(IsoHeapCellType::Args<WebAssemblyModuleRecord>())
, webAssemblyTableHeapCellType(IsoHeapCellType::Args<JSWebAssemblyTable>())
, webAssemblyTagHeapCellType(IsoHeapCellType::Args<JSWebAssemblyTag>())
#endif
// AlignedMemoryAllocators
, fastMallocAllocator(makeUnique<FastMallocAlignedMemoryAllocator>())
, primitiveGigacageAllocator(makeUnique<GigacageAlignedMemoryAllocator>(Gigacage::Primitive))
// Subspaces
, primitiveGigacageAuxiliarySpace("Primitive Gigacage Auxiliary"_s, *this, auxiliaryHeapCellType, primitiveGigacageAllocator.get()) // Hash:0x3e7cd762
, auxiliarySpace("Auxiliary"_s, *this, auxiliaryHeapCellType, fastMallocAllocator.get()) // Hash:0x96255ba1
, immutableButterflyAuxiliarySpace("ImmutableButterfly JSCellWithIndexingHeader"_s, *this, immutableButterflyHeapCellType, fastMallocAllocator.get()) // Hash:0xaadcb3c1
, cellSpace("JSCell"_s, *this, cellHeapCellType, fastMallocAllocator.get()) // Hash:0xadfb5a79
, destructibleObjectSpace("JSDestructibleObject"_s, *this, destructibleObjectHeapCellType, fastMallocAllocator.get()) // Hash:0x4f5ed7a9
FOR_EACH_JSC_COMMON_ISO_SUBSPACE(INIT_SERVER_ISO_SUBSPACE)
FOR_EACH_JSC_STRUCTURE_ISO_SUBSPACE(INIT_SERVER_STRUCTURE_ISO_SUBSPACE)
, codeBlockSpaceAndSet ISO_SUBSPACE_INIT(*this, destructibleCellHeapCellType, CodeBlock) // Hash:0x2b743c6a
, functionExecutableSpaceAndSet ISO_SUBSPACE_INIT(*this, destructibleCellHeapCellType, FunctionExecutable) // Hash:0xbcb36268
, programExecutableSpaceAndSet ISO_SUBSPACE_INIT(*this, destructibleCellHeapCellType, ProgramExecutable) // Hash:0x4c9208f7
, unlinkedFunctionExecutableSpaceAndSet ISO_SUBSPACE_INIT(*this, destructibleCellHeapCellType, UnlinkedFunctionExecutable) // Hash:0x3ba0f4e1
{
if (Options::forceFencedBarrier()) {
m_mutatorShouldBeFenced = true;
m_barrierThreshold = tautologicalThreshold;
}
m_worldState.store(0);
// §11 (T7): the epoch is a by-value member; wire its server back-pointer
// here so bumpAndReclaim() can assert I11 and walk the client registry.
m_safepointEpoch.setServer(*this);
// GIL-off shared-GC-heap: Heap::addToRememberedSet appends to
// m_mutatorMarkStack from the write-barrier slow path of EVERY attached
// mutator thread, so its append()s must serialize (see MarkStack.h —
// postIncTop is a non-atomic RMW of both the cached top and the head
// segment's top, and append can expand the segment list; a lost
// increment is a lost remembered-set entry => live old-gen object's
// young reference never re-scanned => use-after-free). The other shared
// stacks are already serialized elsewhere: m_raceMarkStack by
// m_raceMarkStackLock (SlotVisitor.cpp appendToMarkStack race arm),
// m_sharedCollectorMarkStack / m_sharedMutatorMarkStack by
// m_markingMutex; per-SlotVisitor stacks are single-producer.
if (Options::useSharedGCHeap())
m_mutatorMarkStack->setMultiProducerAccess();
for (unsigned i = 0, numberOfParallelThreads = heapHelperPool().numberOfThreads(); i < numberOfParallelThreads; ++i) {
std::unique_ptr<SlotVisitor> visitor = makeUnique<SlotVisitor>(*this, toCString("P", i + 1));
if (Options::optimizeParallelSlotVisitorsForStoppedMutator())
visitor->optimizeForStoppedMutator();
m_availableParallelSlotVisitors.append(visitor.get());
m_parallelSlotVisitors.append(WTF::move(visitor));
}
if (Options::useConcurrentGC()) {
if (Options::useStochasticMutatorScheduler())
m_scheduler = makeUnique<StochasticSpaceTimeMutatorScheduler>(*this);
else
m_scheduler = makeUnique<SpaceTimeMutatorScheduler>(*this);
} else {
// We simulate turning off concurrent GC by making the scheduler say that the world
// should always be stopped when the collector is running.
m_scheduler = makeUnique<SynchronousStopTheWorldMutatorScheduler>();
}
if (Options::verifyHeap())
m_verifier = makeUnique<HeapVerifier>(this, Options::numberOfGCCyclesToRecordForVerification());
m_collectorSlotVisitor->optimizeForStoppedMutator();
// When memory is critical, allow allocating 25% of the amount above the critical threshold before collecting.
size_t memoryAboveCriticalThreshold = static_cast<size_t>(static_cast<double>(m_ramSize) * (1.0 - Options::criticalGCMemoryThreshold()));
m_maxEdenSizeWhenCritical = memoryAboveCriticalThreshold / 4;
Locker locker { *m_threadLock };
lazyInitialize(m_thread, adoptRef(*new HeapThread(locker, *this)));
}
#undef INIT_SERVER_ISO_SUBSPACE
#undef INIT_SERVER_STRUCTURE_ISO_SUBSPACE
Heap::~Heap()
{
// Scribble m_worldState to make it clear that the heap has already been destroyed if we crash in checkConn
m_worldState.store(0xbadbeeffu);
forEachSlotVisitor(
[&] (SlotVisitor& visitor) {
visitor.clearMarkStacks();
});
m_mutatorMarkStack->clear();
m_raceMarkStack->clear();
for (WeakBlock* block : m_logicallyEmptyWeakBlocks)
WeakBlock::destroy(*this, block);
}
bool Heap::isPagedOut()
{
return m_objectSpace.isPagedOut();
}
void Heap::dumpHeapStatisticsAtVMDestruction()
{
unsigned counter = 0;
// SharedGC (T8): VM-destruction context — no other client thread can be
// running JS against this server; MSPL covers the I5b bit reads of the
// iteration (MarkedSpace::stopAllocating's teardown carve-out).
MutatorSlowPathLocker mutatorSlowPathLocker(*this);
HeapIterationScope iterationScope(*this);
m_objectSpace.forEachBlock([&] (MarkedBlock::Handle* block) {
unsigned live = 0;
block->forEachLiveCell([&] (size_t, HeapCell*, HeapCell::Kind) {
live++;
return IterationStatus::Continue;
});
dataLogLn("[", counter++, "] ", block->cellSize(), ", ", live, " / ", block->cellsPerBlock(), " ", static_cast<double>(live) / block->cellsPerBlock() * 100, "% ", block->attributes(), " ", block->subspace()->name());
block->forEachLiveCell([&] (size_t, HeapCell* heapCell, HeapCell::Kind kind) {
if (kind == HeapCell::Kind::JSCell) {
auto* cell = static_cast<JSCell*>(heapCell);
if (cell->isObject())
dataLogLn(" ", JSValue((JSObject*)cell));
else
dataLogLn(" ", *cell);
}
return IterationStatus::Continue;
});
});
}
// The VM is being destroyed and the collector will never run again.
// Run all pending finalizers now because we won't get another chance.
void Heap::lastChanceToFinalize()
{
MonotonicTime before;
if (Options::logGC()) [[unlikely]] {
before = MonotonicTime::now();
dataLog("[GC<", RawPointer(this), ">: shutdown ");
}
m_isShuttingDown = true;
// SharedGC (T9): main-VM-only — server shutdown runs on the main VM's
// destruction path (secondary clients must already have detached/removed;
// HeapClientSet teardown ordering, I13).
RELEASE_ASSERT(!vm().entryScope);
RELEASE_ASSERT(m_mutatorState == MutatorState::Running);
if (m_collectContinuouslyThread) {
{
Locker locker { m_collectContinuouslyLock };
m_shouldStopCollectingContinuously = true;
m_collectContinuouslyCondition.notifyOne();
}
m_collectContinuouslyThread->waitForCompletion();
}
dataLogIf(Options::logGC(), "1");
// Prevent new collections from being started. This is probably not even necessary, since we're not
// going to call into anything that starts collections. Still, this makes the algorithm more
// obviously sound.
m_isSafeToCollect = false;
dataLogIf(Options::logGC(), "2");
bool isCollecting;
{
Locker locker { *m_threadLock };
RELEASE_ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
isCollecting = m_lastServedTicket < m_lastGrantedTicket;
}
if (isCollecting) {
dataLogIf(Options::logGC(), "...]\n");
// Wait for the current collection to finish.
waitForCollector(
[&] (const AbstractLocker&) -> bool {
RELEASE_ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
return m_lastServedTicket == m_lastGrantedTicket;
});
dataLogIf(Options::logGC(), "[GC<", RawPointer(this), ">: shutdown ");
}
dataLogIf(Options::logGC(), "3");
RELEASE_ASSERT(m_requests.isEmpty());
RELEASE_ASSERT(m_lastServedTicket == m_lastGrantedTicket);
// Carefully bring the thread down.
bool stopped = false;
{
Locker locker { *m_threadLock };
stopped = m_thread->tryStop(locker);
m_threadShouldStop = true;
if (!stopped)
m_threadCondition->notifyOne(locker);
}
dataLogIf(Options::logGC(), "4");
if (!stopped)
m_thread->join();
dataLogIf(Options::logGC(), "5 ");
if (Options::dumpHeapStatisticsAtVMDestruction()) [[unlikely]]
dumpHeapStatisticsAtVMDestruction();
m_arrayBuffers.lastChanceToFinalize();
{
// SharedGC (T8/§5.3 teardown): a stale sticky-ISS flag can outlive
// the last secondary client until the §10D revert poll, so server
// teardown's directory-bit flips and final sweeps run under MSPL
// (no-op when !isSharedServer(), I10). Dropped around
// releaseDelayedReleasedObjects(), which may re-enter JS.
MutatorSlowPathLocker mutatorSlowPathLocker(*this);
m_objectSpace.stopAllocatingForGood();
m_objectSpace.lastChanceToFinalize();
}
releaseDelayedReleasedObjects();
sweepAllLogicallyEmptyWeakBlocks(); // Takes MSPL itself when shared (T8).
{
MutatorSlowPathLocker mutatorSlowPathLocker(*this);
m_objectSpace.freeMemory();
}
dataLogIf(Options::logGC(), (MonotonicTime::now() - before).milliseconds(), "ms]\n");
}
void Heap::releaseDelayedReleasedObjects()
{
#if USE(FOUNDATION) || defined(JSC_GLIB_API_ENABLED)
// We need to guard against the case that releasing an object can create more objects due to the
// release calling into JS. When those JS call(s) exit and all locks are being dropped we end up
// back here and could try to recursively release objects. We guard that with a recursive entry
// count. Only the initial call will release objects, recursive calls simple return and let the
// the initial call to the function take care of any objects created during release time.
// This also means that we need to loop until there are no objects in m_delayedReleaseObjects
// and use a temp Vector for the actual releasing.
if (!m_delayedReleaseRecursionCount++) {
while (!m_delayedReleaseObjects.isEmpty()) {
// SharedGC (T9): main-VM-only — Foundation/GLib delayed releases
// are API-lock-coupled (DropAllLocks below targets the main VM's
// JSLock); GIL-phase sound via JSLock migration (I2).
ASSERT(vm().currentThreadIsHoldingAPILock());
auto objectsToRelease = WTF::move(m_delayedReleaseObjects);
{
// We need to drop locks before calling out to arbitrary code.
JSLock::DropAllLocks dropAllLocks(vm());
#if USE(FOUNDATION)
void* context = objc_autoreleasePoolPush();
#endif
objectsToRelease.clear();
#if USE(FOUNDATION)
objc_autoreleasePoolPop(context);
#endif
}
}
}
m_delayedReleaseRecursionCount--;
#endif
}
void Heap::reportExtraMemoryAllocatedPossiblyFromAlreadyMarkedCell(const JSCell* cell, size_t size)
{
ASSERT(cell);
// Increasing extraMemory of already marked objects will not be visible as a retained memory.
// We need to report this additionally to tell GC that we get additional extra memory now,
// and GC needs to consider scheduling GC based on this increase.
// SPEC-congc §5.3(5) (CG-2): mutatorShouldBeFenced() reads the CURRENT
// CLIENT's §5.3(2) copy when C1R (accessor re-point, Heap.h); the
// re-whiten protocol below is unchanged (mutator-count-independent
// single-word CAS, CGA1 A13).
if (mutatorShouldBeFenced()) [[unlikely]] {
// In this case, the barrierThreshold is the tautological threshold, so cell could still be
// not black. But we can't know for sure until we fire off a fence.
WTF::storeLoadFence();
if (cell->cellState() != CellState::PossiblyBlack)
return;
WTF::loadLoadFence();
if (!isMarked(cell)) {
// During a full collection a store into an unmarked object that had surivived past
// collections will manifest as a store to an unmarked PossiblyBlack object. If the
// object gets marked at some time after this then it will go down the normal marking
// path. So, we don't have to remember this object. We could return here. But we go
// further and attempt to re-white the object.
ASSERT(m_collectionScope && m_collectionScope.value() == CollectionScope::Full);
return;
}
} else
ASSERT(isMarked(cell));
// It could be that the object was *just* marked. This means that the collector may set the
// state to DefinitelyGrey and then to PossiblyOldOrBlack at any time. It's OK for us to
// race with the collector here. If we win then this is accurate because the object _will_
// get scanned again. If we lose then someone else will barrier the object again. That would
// be unfortunate but not the end of the world.
reportExtraMemoryVisited(size);
}
void Heap::reportExtraMemoryAllocatedSlowCase(GCDeferralContext* deferralContext, const JSCell* cell, size_t size)
{
didAllocate(size);
if (cell) {
if (isWithinThreshold(cell->cellState(), barrierThreshold())) [[unlikely]]
reportExtraMemoryAllocatedPossiblyFromAlreadyMarkedCell(cell, size);
}
collectIfNecessaryOrDefer(deferralContext);
}
void Heap::deprecatedReportExtraMemorySlowCase(size_t size)
{
// FIXME: Change this to use SaturatedArithmetic when available.
// https://bugs.webkit.org/show_bug.cgi?id=170411
CheckedSize checkedNewSize = m_deprecatedExtraMemorySize;
checkedNewSize += size;
size_t newSize = std::numeric_limits<size_t>::max();
if (!checkedNewSize.hasOverflowed()) [[likely]]
newSize = checkedNewSize.value();
m_deprecatedExtraMemorySize = newSize;
reportExtraMemoryAllocatedSlowCase(nullptr, nullptr, size);
}
ALWAYS_INLINE bool Heap::activityCallbackDispatchAllowed()
{
// T4(c): activity-callback timer state (GCActivityCallback::m_delay and
// friends) is plain data historically guarded by "one mutator thread".
// Once shared, multiple clients reach the didAllocate dispatch sites
// concurrently; the timers are bound to the MAIN VM's run loop and their
// doWork fires on the main client's thread, so restricting mutator-side
// dispatch to that same thread restores the single-writer regime without
// re-disabling the callbacks wholesale (the pre-T4 state, which removed
// every idle-time GC trigger once ISS and helped make capacity
// monotone). World-stopped dispatch sites (updateAllocationLimits) call
// the callbacks directly instead: every mutator is parked there, so no
// concurrent access exists regardless of the conducting thread.
if (!isSharedServer()) [[likely]]
return true;
GCClient::Heap* client = GCClient::Heap::currentThreadClient();
return client && client == m_mainClient;
}
bool Heap::overCriticalMemoryThreshold(MemoryThresholdCallType memoryThresholdCallType)
{
#if USE(MEMORY_FOOTPRINT_API)
if (memoryThresholdCallType == MemoryThresholdCallType::Direct || ++m_percentAvailableMemoryCachedCallCount >= 100) {
m_overCriticalMemoryThreshold = WTF::percentAvailableMemoryInUse() > Options::criticalGCMemoryThreshold();
m_percentAvailableMemoryCachedCallCount = 0;
}
return m_overCriticalMemoryThreshold;
#else
UNUSED_PARAM(memoryThresholdCallType);
return false;
#endif
}
void Heap::reportAbandonedObjectGraph()
{
// Our clients don't know exactly how much memory they
// are abandoning so we just guess for them.
size_t abandonedBytes = static_cast<size_t>(0.1 * capacity());
// We want to accelerate the next collection. Because memory has just
// been abandoned, the next collection has the potential to
// be more profitable. Since allocation is the trigger for collection,
// we hasten the next collection by pretending that we've allocated more memory.
// T4(c): re-enabled when shared (was the §5.4/I15 blanket disable). The
// callback's plain timer state is single-writer-safe here only on the
// main client's thread (the timer is bound to the main VM's run loop and
// doWork runs there); under shared, restrict dispatch to that thread —
// the I15 no-fire-and-forget invariant is preserved by collectAsync's
// ISS reroute to ticketing, not by suppressing the timer.
if (m_fullActivityCallback && activityCallbackDispatchAllowed()) {
m_fullActivityCallback->didAllocate(*this,
m_sizeAfterLastCollect - m_sizeAfterLastFullCollect + totalBytesAllocatedThisCycle() + m_bytesAbandonedSinceLastFullCollect.load(std::memory_order_relaxed));
}
m_bytesAbandonedSinceLastFullCollect.fetch_add(abandonedBytes, std::memory_order_relaxed); // F3.
}
void Heap::protect(JSValue k)
{
ASSERT(k);
// SharedGC (T9): main-VM-only assert (protect/unprotect below) — the
// protect set is server state but the API-lock predicate names the main
// VM; GIL-phase sound (JSLock migration). Post-GIL this becomes an
// access-held predicate (currentThreadClient()), not per-client
// iteration — the set itself stays one-per-server.
ASSERT(vm().currentThreadIsHoldingAPILock());
if (!k.isCell())
return;
m_protectedValues.add(k.asCell());
}
bool Heap::unprotect(JSValue k)
{
ASSERT(k);
// SharedGC (T9): main-VM-only assert — see protect().
ASSERT(vm().currentThreadIsHoldingAPILock());
if (!k.isCell())
return false;
return m_protectedValues.remove(k.asCell());
}
void Heap::pinRetiredCallLinkRecordCodeBlock(void* codeBlock)
{
// See the declaration comment (SPEC-jit §5.8/§4.4 record-named CodeBlock
// identity). Flag-on only; callers guarantee codeBlock is the non-null
// codeBlockToTransfer of a record being PUBLISHED on this (server) heap
// (w16 amend: the pin is taken at publish, while the linking mutator
// provably holds the cell live, and spans the record's whole reachable
// lifetime — live, then retired until epoch expiry. Destructor-context
// inline record deletes skip the unpin: retention, never unsoundness).
ASSERT(Options::useJSThreads());
ASSERT(codeBlock);
Locker locker { m_retiredCallLinkRecordCodeBlocksLock };
m_retiredCallLinkRecordCodeBlocks.add(codeBlock);
}
void Heap::unpinRetiredCallLinkRecordCodeBlock(void* codeBlock)
{
ASSERT(Options::useJSThreads());
ASSERT(codeBlock);
Locker locker { m_retiredCallLinkRecordCodeBlocksLock };
m_retiredCallLinkRecordCodeBlocks.remove(codeBlock);
}
void Heap::addReference(JSCell* cell, ArrayBuffer* buffer)
{
if (m_arrayBuffers.addReference(cell, buffer)) {
collectIfNecessaryOrDefer();
didAllocate(buffer->gcSizeEstimateInBytes());
}
}
template<typename CellType, typename CellSet>
void Heap::finalizeMarkedUnconditionalFinalizers(CellSet& cellSet, CollectionScope collectionScope)
{
// SharedGC (T9): conductor-context OK — end-phase work, world stopped
// (worldIsStopped() / WSAC once shared); vm() is the main mutator VM
// (deviation 3), the only VM whose cells live in this server phase 1.
// No JS runs in unconditional finalizers (§10B.5: no JS finalizers in
// the stop window).
cellSet.forEachMarkedCell(
[&] (HeapCell* cell, HeapCell::Kind) {
static_cast<CellType*>(cell)->finalizeUnconditionally(vm(), collectionScope);
});
}
void Heap::finalizeUnconditionalFinalizers()
{
CollectionScope collectionScope = this->collectionScope().value_or(CollectionScope::Full);
{
// We run this before CodeBlock's unconditional finalizer since CodeBlock looks at the owner executable's installed CodeBlock in its finalizeUnconditionally.
// FunctionExecutable requires all live instances to run finalizers. Thus, we do not use finalizer set.
finalizeMarkedUnconditionalFinalizers<FunctionExecutable>(functionExecutableSpaceAndSet.space, collectionScope);
finalizeMarkedUnconditionalFinalizers<ProgramExecutable>(programExecutableSpaceAndSet.finalizerSet, collectionScope);
if (m_evalExecutableSpace)
finalizeMarkedUnconditionalFinalizers<EvalExecutable>(m_evalExecutableSpace->finalizerSet, collectionScope);
if (m_moduleProgramExecutableSpace)
finalizeMarkedUnconditionalFinalizers<ModuleProgramExecutable>(m_moduleProgramExecutableSpace->finalizerSet, collectionScope);
}
finalizeMarkedUnconditionalFinalizers<SymbolTable>(symbolTableSpace, collectionScope);
forEachCodeBlockSpace(
[&] (auto& space) {
this->finalizeMarkedUnconditionalFinalizers<CodeBlock>(space.set, collectionScope);
});
if (collectionScope == CollectionScope::Full) {
finalizeMarkedUnconditionalFinalizers<Structure>(structureSpace, collectionScope);
finalizeMarkedUnconditionalFinalizers<BrandedStructure>(brandedStructureSpace, collectionScope);
#if ENABLE(WEBASSEMBLY)
finalizeMarkedUnconditionalFinalizers<WebAssemblyGCStructure>(webAssemblyGCStructureSpace, collectionScope);
#endif