-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathGCRuntime.h
1115 lines (915 loc) · 37.9 KB
/
GCRuntime.h
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef gc_GCRuntime_h
#define gc_GCRuntime_h
#include "mozilla/Atomics.h"
#include "mozilla/EnumSet.h"
#include "mozilla/Maybe.h"
#include "mozilla/TimeStamp.h"
#include "gc/ArenaList.h"
#include "gc/AtomMarking.h"
#include "gc/GCMarker.h"
#include "gc/GCParallelTask.h"
#include "gc/Nursery.h"
#include "gc/Scheduling.h"
#include "gc/Statistics.h"
#include "gc/StoreBuffer.h"
#include "js/GCAnnotations.h"
#include "js/UniquePtr.h"
#include "vm/AtomsTable.h"
namespace js {
class AutoAccessAtomsZone;
class AutoLockGC;
class AutoLockGCBgAlloc;
class AutoLockHelperThreadState;
class VerifyPreTracer;
namespace gc {
using BlackGrayEdgeVector = Vector<TenuredCell*, 0, SystemAllocPolicy>;
using ZoneVector = Vector<JS::Zone*, 4, SystemAllocPolicy>;
class AutoCallGCCallbacks;
class AutoGCSession;
class AutoRunParallelTask;
class AutoTraceSession;
class MarkingValidator;
struct MovingTracer;
enum class ShouldCheckThresholds;
class SweepGroupsIter;
class WeakCacheSweepIterator;
enum IncrementalProgress { NotFinished = 0, Finished };
// Interface to a sweep action.
//
// Note that we don't need perfect forwarding for args here because the
// types are not deduced but come ultimately from the type of a function pointer
// passed to SweepFunc.
template <typename... Args>
struct SweepAction {
virtual ~SweepAction() {}
virtual IncrementalProgress run(Args... args) = 0;
virtual void assertFinished() const = 0;
virtual bool shouldSkip() { return false; }
};
class ChunkPool {
Chunk* head_;
size_t count_;
public:
ChunkPool() : head_(nullptr), count_(0) {}
~ChunkPool() {
// TODO: We should be able to assert that the chunk pool is empty but
// this causes XPCShell test failures on Windows 2012. See bug 1379232.
}
bool empty() const { return !head_; }
size_t count() const { return count_; }
Chunk* head() {
MOZ_ASSERT(head_);
return head_;
}
Chunk* pop();
void push(Chunk* chunk);
Chunk* remove(Chunk* chunk);
#ifdef DEBUG
bool contains(Chunk* chunk) const;
bool verify() const;
#endif
// Pool mutation does not invalidate an Iter unless the mutation
// is of the Chunk currently being visited by the Iter.
class Iter {
public:
explicit Iter(ChunkPool& pool) : current_(pool.head_) {}
bool done() const { return !current_; }
void next();
Chunk* get() const { return current_; }
operator Chunk*() const { return get(); }
Chunk* operator->() const { return get(); }
private:
Chunk* current_;
};
};
class BackgroundSweepTask : public GCParallelTaskHelper<BackgroundSweepTask> {
public:
explicit BackgroundSweepTask(JSRuntime* rt) : GCParallelTaskHelper(rt) {}
void run();
};
class BackgroundFreeTask : public GCParallelTaskHelper<BackgroundFreeTask> {
public:
explicit BackgroundFreeTask(JSRuntime* rt) : GCParallelTaskHelper(rt) {}
void run();
};
// Performs extra allocation off thread so that when memory is required on the
// main thread it will already be available and waiting.
class BackgroundAllocTask : public GCParallelTaskHelper<BackgroundAllocTask> {
// Guarded by the GC lock.
GCLockData<ChunkPool&> chunkPool_;
const bool enabled_;
public:
BackgroundAllocTask(JSRuntime* rt, ChunkPool& pool);
bool enabled() const { return enabled_; }
void run();
};
// Search the provided Chunks for free arenas and decommit them.
class BackgroundDecommitTask
: public GCParallelTaskHelper<BackgroundDecommitTask> {
public:
using ChunkVector = mozilla::Vector<Chunk*>;
explicit BackgroundDecommitTask(JSRuntime* rt) : GCParallelTaskHelper(rt) {}
void setChunksToScan(ChunkVector& chunks);
void run();
private:
MainThreadOrGCTaskData<ChunkVector> toDecommit;
};
template <typename F>
struct Callback {
MainThreadOrGCTaskData<F> op;
MainThreadOrGCTaskData<void*> data;
Callback() : op(nullptr), data(nullptr) {}
Callback(F op, void* data) : op(op), data(data) {}
};
template <typename F>
using CallbackVector =
MainThreadData<Vector<Callback<F>, 4, SystemAllocPolicy>>;
template <typename T, typename Iter0, typename Iter1>
class ChainedIter {
Iter0 iter0_;
Iter1 iter1_;
public:
ChainedIter(const Iter0& iter0, const Iter1& iter1)
: iter0_(iter0), iter1_(iter1) {}
bool done() const { return iter0_.done() && iter1_.done(); }
void next() {
MOZ_ASSERT(!done());
if (!iter0_.done()) {
iter0_.next();
} else {
MOZ_ASSERT(!iter1_.done());
iter1_.next();
}
}
T get() const {
MOZ_ASSERT(!done());
if (!iter0_.done()) {
return iter0_.get();
}
MOZ_ASSERT(!iter1_.done());
return iter1_.get();
}
operator T() const { return get(); }
T operator->() const { return get(); }
};
typedef HashMap<Value*, const char*, DefaultHasher<Value*>, SystemAllocPolicy>
RootedValueMap;
using AllocKinds = mozilla::EnumSet<AllocKind, uint32_t>;
// A singly linked list of zones.
class ZoneList {
static Zone* const End;
Zone* head;
Zone* tail;
public:
ZoneList();
~ZoneList();
bool isEmpty() const;
Zone* front() const;
void append(Zone* zone);
void transferFrom(ZoneList& other);
Zone* removeFront();
void clear();
private:
explicit ZoneList(Zone* singleZone);
void check() const;
ZoneList(const ZoneList& other) = delete;
ZoneList& operator=(const ZoneList& other) = delete;
};
class GCRuntime {
public:
explicit GCRuntime(JSRuntime* rt);
MOZ_MUST_USE bool init(uint32_t maxbytes, uint32_t maxNurseryBytes);
void finishRoots();
void finish();
inline bool hasZealMode(ZealMode mode);
inline void clearZealMode(ZealMode mode);
inline bool upcomingZealousGC();
inline bool needZealousGC();
inline bool hasIncrementalTwoSliceZealMode();
MOZ_MUST_USE bool addRoot(Value* vp, const char* name);
void removeRoot(Value* vp);
void setMarkStackLimit(size_t limit, AutoLockGC& lock);
MOZ_MUST_USE bool setParameter(JSGCParamKey key, uint32_t value,
AutoLockGC& lock);
void resetParameter(JSGCParamKey key, AutoLockGC& lock);
uint32_t getParameter(JSGCParamKey key, const AutoLockGC& lock);
MOZ_MUST_USE bool triggerGC(JS::GCReason reason);
void maybeAllocTriggerZoneGC(Zone* zone, const AutoLockGC& lock);
// The return value indicates if we were able to do the GC.
bool triggerZoneGC(Zone* zone, JS::GCReason reason, size_t usedBytes,
size_t thresholdBytes);
void maybeGC(Zone* zone);
// The return value indicates whether a major GC was performed.
bool gcIfRequested();
void gc(JSGCInvocationKind gckind, JS::GCReason reason);
void startGC(JSGCInvocationKind gckind, JS::GCReason reason,
int64_t millis = 0);
void gcSlice(JS::GCReason reason, int64_t millis = 0);
void finishGC(JS::GCReason reason);
void abortGC();
void startDebugGC(JSGCInvocationKind gckind, SliceBudget& budget);
void debugGCSlice(SliceBudget& budget);
void triggerFullGCForAtoms(JSContext* cx);
void runDebugGC();
void notifyRootsRemoved();
enum TraceOrMarkRuntime { TraceRuntime, MarkRuntime };
void traceRuntime(JSTracer* trc, AutoTraceSession& session);
void traceRuntimeForMinorGC(JSTracer* trc, AutoGCSession& session);
void purgeRuntimeForMinorGC();
void shrinkBuffers();
void onOutOfMallocMemory();
void onOutOfMallocMemory(const AutoLockGC& lock);
#ifdef JS_GC_ZEAL
const uint32_t* addressOfZealModeBits() { return &zealModeBits.refNoCheck(); }
void getZealBits(uint32_t* zealBits, uint32_t* frequency,
uint32_t* nextScheduled);
void setZeal(uint8_t zeal, uint32_t frequency);
void unsetZeal(uint8_t zeal);
bool parseAndSetZeal(const char* str);
void setNextScheduled(uint32_t count);
void verifyPreBarriers();
void maybeVerifyPreBarriers(bool always);
bool selectForMarking(JSObject* object);
void clearSelectedForMarking();
void setDeterministic(bool enable);
#endif
uint64_t nextCellUniqueId() {
MOZ_ASSERT(nextCellUniqueId_ > 0);
uint64_t uid = ++nextCellUniqueId_;
return uid;
}
#ifdef DEBUG
bool shutdownCollectedEverything() const { return arenasEmptyAtShutdown; }
#endif
public:
// Internal public interface
State state() const { return incrementalState; }
bool isHeapCompacting() const { return state() == State::Compact; }
bool isForegroundSweeping() const { return state() == State::Sweep; }
bool isBackgroundSweeping() { return sweepTask.isRunning(); }
void waitBackgroundSweepEnd();
void waitBackgroundSweepOrAllocEnd() {
waitBackgroundSweepEnd();
allocTask.cancelAndWait();
}
void waitBackgroundFreeEnd();
void lockGC() { lock.lock(); }
void unlockGC() { lock.unlock(); }
#ifdef DEBUG
bool currentThreadHasLockedGC() const { return lock.ownedByCurrentThread(); }
#endif // DEBUG
void setAlwaysPreserveCode() { alwaysPreserveCode = true; }
bool isIncrementalGCAllowed() const { return incrementalAllowed; }
void disallowIncrementalGC() { incrementalAllowed = false; }
bool isIncrementalGCEnabled() const {
return mode == JSGC_MODE_INCREMENTAL && incrementalAllowed;
}
bool isIncrementalGCInProgress() const { return state() != State::NotActive; }
bool isCompactingGCEnabled() const;
bool isShrinkingGC() const { return invocationKind == GC_SHRINK; }
bool initSweepActions();
void setGrayRootsTracer(JSTraceDataOp traceOp, void* data);
MOZ_MUST_USE bool addBlackRootsTracer(JSTraceDataOp traceOp, void* data);
void removeBlackRootsTracer(JSTraceDataOp traceOp, void* data);
int32_t getMallocBytes() const { return mallocCounter.bytes(); }
size_t maxMallocBytesAllocated() const { return mallocCounter.maxBytes(); }
void setMaxMallocBytes(size_t value, const AutoLockGC& lock);
bool updateMallocCounter(size_t nbytes) {
mallocCounter.update(nbytes);
TriggerKind trigger = mallocCounter.shouldTriggerGC(tunables);
if (MOZ_LIKELY(trigger == NoTrigger) ||
trigger <= mallocCounter.triggered()) {
return false;
}
if (!triggerGC(JS::GCReason::TOO_MUCH_MALLOC)) {
return false;
}
// Even though this method may be called off the main thread it is safe
// to access mallocCounter here since triggerGC() will return false in
// that case.
stats().recordTrigger(mallocCounter.bytes(), mallocCounter.maxBytes());
mallocCounter.recordTrigger(trigger);
return true;
}
void updateMallocCountersOnGCStart();
void setGCCallback(JSGCCallback callback, void* data);
void callGCCallback(JSGCStatus status) const;
void setObjectsTenuredCallback(JSObjectsTenuredCallback callback, void* data);
void callObjectsTenuredCallback();
MOZ_MUST_USE bool addFinalizeCallback(JSFinalizeCallback callback,
void* data);
void removeFinalizeCallback(JSFinalizeCallback func);
MOZ_MUST_USE bool addWeakPointerZonesCallback(
JSWeakPointerZonesCallback callback, void* data);
void removeWeakPointerZonesCallback(JSWeakPointerZonesCallback callback);
MOZ_MUST_USE bool addWeakPointerCompartmentCallback(
JSWeakPointerCompartmentCallback callback, void* data);
void removeWeakPointerCompartmentCallback(
JSWeakPointerCompartmentCallback callback);
JS::GCSliceCallback setSliceCallback(JS::GCSliceCallback callback);
JS::GCNurseryCollectionCallback setNurseryCollectionCallback(
JS::GCNurseryCollectionCallback callback);
JS::DoCycleCollectionCallback setDoCycleCollectionCallback(
JS::DoCycleCollectionCallback callback);
void callDoCycleCollectionCallback(JSContext* cx);
void setFullCompartmentChecks(bool enable);
JS::Zone* getCurrentSweepGroup() { return currentSweepGroup; }
uint64_t gcNumber() const { return number; }
uint64_t minorGCCount() const { return minorGCNumber; }
void incMinorGcNumber() {
++minorGCNumber;
++number;
}
uint64_t majorGCCount() const { return majorGCNumber; }
void incMajorGcNumber() { ++majorGCNumber; }
int64_t defaultSliceBudget() const { return defaultTimeBudget_; }
bool isIncrementalGc() const { return isIncremental; }
bool isFullGc() const { return isFull; }
bool isCompactingGc() const { return isCompacting; }
bool areGrayBitsValid() const { return grayBitsValid; }
void setGrayBitsInvalid() { grayBitsValid = false; }
bool majorGCRequested() const {
return majorGCTriggerReason != JS::GCReason::NO_REASON;
}
bool fullGCForAtomsRequested() const { return fullGCForAtomsRequested_; }
double computeHeapGrowthFactor(size_t lastBytes);
size_t computeTriggerBytes(double growthFactor, size_t lastBytes);
JSGCMode gcMode() const { return mode; }
void setGCMode(JSGCMode m) {
mode = m;
marker.setGCMode(mode);
}
inline void updateOnFreeArenaAlloc(const ChunkInfo& info);
inline void updateOnArenaFree();
ChunkPool& fullChunks(const AutoLockGC& lock) { return fullChunks_.ref(); }
ChunkPool& availableChunks(const AutoLockGC& lock) {
return availableChunks_.ref();
}
ChunkPool& emptyChunks(const AutoLockGC& lock) { return emptyChunks_.ref(); }
const ChunkPool& fullChunks(const AutoLockGC& lock) const {
return fullChunks_.ref();
}
const ChunkPool& availableChunks(const AutoLockGC& lock) const {
return availableChunks_.ref();
}
const ChunkPool& emptyChunks(const AutoLockGC& lock) const {
return emptyChunks_.ref();
}
typedef ChainedIter<Chunk*, ChunkPool::Iter, ChunkPool::Iter>
NonEmptyChunksIter;
NonEmptyChunksIter allNonEmptyChunks(const AutoLockGC& lock) {
return NonEmptyChunksIter(ChunkPool::Iter(availableChunks(lock)),
ChunkPool::Iter(fullChunks(lock)));
}
Chunk* getOrAllocChunk(AutoLockGCBgAlloc& lock);
void recycleChunk(Chunk* chunk, const AutoLockGC& lock);
#ifdef JS_GC_ZEAL
void startVerifyPreBarriers();
void endVerifyPreBarriers();
void finishVerifier();
bool isVerifyPreBarriersEnabled() const { return !!verifyPreData; }
bool shouldYieldForZeal(ZealMode mode);
#else
bool isVerifyPreBarriersEnabled() const { return false; }
#endif
// Queue memory memory to be freed on a background thread if possible.
void queueUnusedLifoBlocksForFree(LifoAlloc* lifo);
void queueAllLifoBlocksForFree(LifoAlloc* lifo);
void queueAllLifoBlocksForFreeAfterMinorGC(LifoAlloc* lifo);
void queueBuffersForFreeAfterMinorGC(Nursery::BufferSet& buffers);
// Public here for ReleaseArenaLists and FinalizeTypedArenas.
void releaseArena(Arena* arena, const AutoLockGC& lock);
void releaseHeldRelocatedArenas();
void releaseHeldRelocatedArenasWithoutUnlocking(const AutoLockGC& lock);
// Allocator
template <AllowGC allowGC>
MOZ_MUST_USE bool checkAllocatorState(JSContext* cx, AllocKind kind);
template <AllowGC allowGC>
JSObject* tryNewNurseryObject(JSContext* cx, size_t thingSize,
size_t nDynamicSlots, const Class* clasp);
template <AllowGC allowGC>
static JSObject* tryNewTenuredObject(JSContext* cx, AllocKind kind,
size_t thingSize, size_t nDynamicSlots);
template <typename T, AllowGC allowGC>
static T* tryNewTenuredThing(JSContext* cx, AllocKind kind, size_t thingSize);
template <AllowGC allowGC>
JSString* tryNewNurseryString(JSContext* cx, size_t thingSize,
AllocKind kind);
static TenuredCell* refillFreeListInGC(Zone* zone, AllocKind thingKind);
void setParallelAtomsAllocEnabled(bool enabled);
void bufferGrayRoots();
/*
* Concurrent sweep infrastructure.
*/
void startTask(GCParallelTask& task, gcstats::PhaseKind phase,
AutoLockHelperThreadState& locked);
void joinTask(GCParallelTask& task, gcstats::PhaseKind phase,
AutoLockHelperThreadState& locked);
void mergeRealms(JS::Realm* source, JS::Realm* target);
private:
enum IncrementalResult { ResetIncremental = 0, Ok };
// Delete an empty zone after its contents have been merged.
void deleteEmptyZone(Zone* zone);
// For ArenaLists::allocateFromArena()
friend class ArenaLists;
Chunk* pickChunk(AutoLockGCBgAlloc& lock);
Arena* allocateArena(Chunk* chunk, Zone* zone, AllocKind kind,
ShouldCheckThresholds checkThresholds,
const AutoLockGC& lock);
// Allocator internals
MOZ_MUST_USE bool gcIfNeededAtAllocation(JSContext* cx);
template <typename T>
static void checkIncrementalZoneState(JSContext* cx, T* t);
static TenuredCell* refillFreeListFromAnyThread(JSContext* cx,
AllocKind thingKind);
static TenuredCell* refillFreeListFromMainThread(JSContext* cx,
AllocKind thingKind);
static TenuredCell* refillFreeListFromHelperThread(JSContext* cx,
AllocKind thingKind);
/*
* Return the list of chunks that can be released outside the GC lock.
* Must be called either during the GC or with the GC lock taken.
*/
friend class BackgroundDecommitTask;
ChunkPool expireEmptyChunkPool(const AutoLockGC& lock);
void freeEmptyChunks(const AutoLockGC& lock);
void prepareToFreeChunk(ChunkInfo& info);
friend class BackgroundAllocTask;
bool wantBackgroundAllocation(const AutoLockGC& lock) const;
bool startBackgroundAllocTaskIfIdle();
void requestMajorGC(JS::GCReason reason);
SliceBudget defaultBudget(JS::GCReason reason, int64_t millis);
IncrementalResult budgetIncrementalGC(bool nonincrementalByAPI,
JS::GCReason reason,
SliceBudget& budget);
IncrementalResult resetIncrementalGC(AbortReason reason);
// Assert if the system state is such that we should never
// receive a request to do GC work.
void checkCanCallAPI();
// Check if the system state is such that GC has been supressed
// or otherwise delayed.
MOZ_MUST_USE bool checkIfGCAllowedInCurrentState(JS::GCReason reason);
gcstats::ZoneGCStats scanZonesBeforeGC();
void collect(bool nonincrementalByAPI, SliceBudget budget,
JS::GCReason reason) JS_HAZ_GC_CALL;
/*
* Run one GC "cycle" (either a slice of incremental GC or an entire
* non-incremental GC).
*
* Returns:
* * ResetIncremental if we "reset" an existing incremental GC, which would
* force us to run another cycle or
* * Ok otherwise.
*/
MOZ_MUST_USE IncrementalResult gcCycle(bool nonincrementalByAPI,
SliceBudget budget,
JS::GCReason reason);
bool shouldRepeatForDeadZone(JS::GCReason reason);
void incrementalSlice(SliceBudget& budget, JS::GCReason reason,
AutoGCSession& session);
MOZ_MUST_USE bool shouldCollectNurseryForSlice(bool nonincrementalByAPI,
SliceBudget& budget);
friend class AutoCallGCCallbacks;
void maybeCallGCCallback(JSGCStatus status);
void pushZealSelectedObjects();
void purgeRuntime();
MOZ_MUST_USE bool beginMarkPhase(JS::GCReason reason, AutoGCSession& session);
bool prepareZonesForCollection(JS::GCReason reason, bool* isFullOut);
bool shouldPreserveJITCode(JS::Realm* realm,
const mozilla::TimeStamp& currentTime,
JS::GCReason reason, bool canAllocateMoreCode);
void startBackgroundFreeAfterMinorGC();
void traceRuntimeForMajorGC(JSTracer* trc, AutoGCSession& session);
void traceRuntimeAtoms(JSTracer* trc, const AutoAccessAtomsZone& atomsAccess);
void traceKeptAtoms(JSTracer* trc);
void traceRuntimeCommon(JSTracer* trc, TraceOrMarkRuntime traceOrMark);
void maybeDoCycleCollection();
void markCompartments();
IncrementalProgress markUntilBudgetExhausted(SliceBudget& sliceBudget,
gcstats::PhaseKind phase);
void drainMarkStack();
template <class ZoneIterT>
void markWeakReferences(gcstats::PhaseKind phase);
void markWeakReferencesInCurrentGroup(gcstats::PhaseKind phase);
template <class ZoneIterT>
void markGrayRoots(gcstats::PhaseKind phase);
void markBufferedGrayRoots(JS::Zone* zone);
void markAllWeakReferences(gcstats::PhaseKind phase);
void markAllGrayReferences(gcstats::PhaseKind phase);
void beginSweepPhase(JS::GCReason reason, AutoGCSession& session);
void groupZonesForSweeping(JS::GCReason reason);
MOZ_MUST_USE bool findSweepGroupEdges();
void getNextSweepGroup();
IncrementalProgress markGrayReferencesInCurrentGroup(FreeOp* fop,
SliceBudget& budget);
IncrementalProgress endMarkingSweepGroup(FreeOp* fop, SliceBudget& budget);
void markIncomingCrossCompartmentPointers(MarkColor color);
IncrementalProgress beginSweepingSweepGroup(FreeOp* fop, SliceBudget& budget);
void sweepDebuggerOnMainThread(FreeOp* fop);
void sweepJitDataOnMainThread(FreeOp* fop);
IncrementalProgress endSweepingSweepGroup(FreeOp* fop, SliceBudget& budget);
IncrementalProgress performSweepActions(SliceBudget& sliceBudget);
IncrementalProgress sweepTypeInformation(FreeOp* fop, SliceBudget& budget,
Zone* zone);
IncrementalProgress releaseSweptEmptyArenas(FreeOp* fop, SliceBudget& budget,
Zone* zone);
void startSweepingAtomsTable();
IncrementalProgress sweepAtomsTable(FreeOp* fop, SliceBudget& budget);
IncrementalProgress sweepWeakCaches(FreeOp* fop, SliceBudget& budget);
IncrementalProgress finalizeAllocKind(FreeOp* fop, SliceBudget& budget,
Zone* zone, AllocKind kind);
IncrementalProgress sweepShapeTree(FreeOp* fop, SliceBudget& budget,
Zone* zone);
void endSweepPhase(bool lastGC);
bool allCCVisibleZonesWereCollected() const;
void sweepZones(FreeOp* fop, bool destroyingRuntime);
void decommitAllWithoutUnlocking(const AutoLockGC& lock);
void startDecommit();
void queueZonesAndStartBackgroundSweep(ZoneList& zones);
void sweepFromBackgroundThread(AutoLockHelperThreadState& lock);
void startBackgroundFree();
void freeFromBackgroundThread(AutoLockHelperThreadState& lock);
void sweepBackgroundThings(ZoneList& zones, LifoAlloc& freeBlocks);
void assertBackgroundSweepingFinished();
bool shouldCompact();
void beginCompactPhase();
IncrementalProgress compactPhase(JS::GCReason reason,
SliceBudget& sliceBudget,
AutoGCSession& session);
void endCompactPhase();
void sweepTypesAfterCompacting(Zone* zone);
void sweepZoneAfterCompacting(Zone* zone);
MOZ_MUST_USE bool relocateArenas(Zone* zone, JS::GCReason reason,
Arena*& relocatedListOut,
SliceBudget& sliceBudget);
void updateTypeDescrObjects(MovingTracer* trc, Zone* zone);
void updateCellPointers(Zone* zone, AllocKinds kinds, size_t bgTaskCount);
void updateAllCellPointers(MovingTracer* trc, Zone* zone);
void updateZonePointersToRelocatedCells(Zone* zone);
void updateRuntimePointersToRelocatedCells(AutoGCSession& session);
void protectAndHoldArenas(Arena* arenaList);
void unprotectHeldRelocatedArenas();
void releaseRelocatedArenas(Arena* arenaList);
void releaseRelocatedArenasWithoutUnlocking(Arena* arenaList,
const AutoLockGC& lock);
void finishCollection();
void computeNonIncrementalMarkingForValidation(AutoGCSession& session);
void validateIncrementalMarking();
void finishMarkingValidation();
#ifdef DEBUG
void checkForCompartmentMismatches();
#endif
void callFinalizeCallbacks(FreeOp* fop, JSFinalizeStatus status) const;
void callWeakPointerZonesCallbacks() const;
void callWeakPointerCompartmentCallbacks(JS::Compartment* comp) const;
public:
JSRuntime* const rt;
/* Embedders can use this zone and group however they wish. */
UnprotectedData<JS::Zone*> systemZone;
// All zones in the runtime, except the atoms zone.
private:
MainThreadOrGCTaskData<ZoneVector> zones_;
public:
ZoneVector& zones() { return zones_.ref(); }
// The unique atoms zone.
WriteOnceData<Zone*> atomsZone;
private:
UnprotectedData<gcstats::Statistics> stats_;
public:
gcstats::Statistics& stats() { return stats_.ref(); }
GCMarker marker;
Vector<JS::GCCellPtr, 0, SystemAllocPolicy> unmarkGrayStack;
/* Track heap size for this runtime. */
HeapSize heapSize;
/* GC scheduling state and parameters. */
GCSchedulingTunables tunables;
GCSchedulingState schedulingState;
// State used for managing atom mark bitmaps in each zone.
AtomMarkingRuntime atomMarking;
private:
// When chunks are empty, they reside in the emptyChunks pool and are
// re-used as needed or eventually expired if not re-used. The emptyChunks
// pool gets refilled from the background allocation task heuristically so
// that empty chunks should always be available for immediate allocation
// without syscalls.
GCLockData<ChunkPool> emptyChunks_;
// Chunks which have had some, but not all, of their arenas allocated live
// in the available chunk lists. When all available arenas in a chunk have
// been allocated, the chunk is removed from the available list and moved
// to the fullChunks pool. During a GC, if all arenas are free, the chunk
// is moved back to the emptyChunks pool and scheduled for eventual
// release.
GCLockData<ChunkPool> availableChunks_;
// When all arenas in a chunk are used, it is moved to the fullChunks pool
// so as to reduce the cost of operations on the available lists.
GCLockData<ChunkPool> fullChunks_;
MainThreadData<RootedValueMap> rootsHash;
// An incrementing id used to assign unique ids to cells that require one.
mozilla::Atomic<uint64_t, mozilla::ReleaseAcquire,
mozilla::recordreplay::Behavior::DontPreserve>
nextCellUniqueId_;
/*
* Number of the committed arenas in all GC chunks including empty chunks.
*/
mozilla::Atomic<uint32_t, mozilla::ReleaseAcquire,
mozilla::recordreplay::Behavior::DontPreserve>
numArenasFreeCommitted;
MainThreadData<VerifyPreTracer*> verifyPreData;
private:
UnprotectedData<bool> chunkAllocationSinceLastGC;
MainThreadData<mozilla::TimeStamp> lastGCTime;
/*
* JSGC_MODE
* prefs: javascript.options.mem.gc_per_zone and
* javascript.options.mem.gc_incremental.
*/
MainThreadData<JSGCMode> mode;
mozilla::Atomic<size_t, mozilla::ReleaseAcquire,
mozilla::recordreplay::Behavior::DontPreserve>
numActiveZoneIters;
/* During shutdown, the GC needs to clean up every possible object. */
MainThreadData<bool> cleanUpEverything;
// Gray marking must be done after all black marking is complete. However,
// we do not have write barriers on XPConnect roots. Therefore, XPConnect
// roots must be accumulated in the first slice of incremental GC. We
// accumulate these roots in each zone's gcGrayRoots vector and then mark
// them later, after black marking is complete for each compartment. This
// accumulation can fail, but in that case we switch to non-incremental GC.
enum class GrayBufferState { Unused, Okay, Failed };
MainThreadOrGCTaskData<GrayBufferState> grayBufferState;
bool hasValidGrayRootsBuffer() const {
return grayBufferState == GrayBufferState::Okay;
}
// Clear each zone's gray buffers, but do not change the current state.
void resetBufferedGrayRoots() const;
// Reset the gray buffering state to Unused.
void clearBufferedGrayRoots() {
grayBufferState = GrayBufferState::Unused;
resetBufferedGrayRoots();
}
/*
* The gray bits can become invalid if UnmarkGray overflows the stack. A
* full GC will reset this bit, since it fills in all the gray bits.
*/
UnprotectedData<bool> grayBitsValid;
mozilla::Atomic<JS::GCReason, mozilla::Relaxed,
mozilla::recordreplay::Behavior::DontPreserve>
majorGCTriggerReason;
private:
/* Perform full GC if rt->keepAtoms() becomes false. */
MainThreadData<bool> fullGCForAtomsRequested_;
/* Incremented at the start of every minor GC. */
MainThreadData<uint64_t> minorGCNumber;
/* Incremented at the start of every major GC. */
MainThreadData<uint64_t> majorGCNumber;
/* Incremented on every GC slice or minor collection. */
MainThreadData<uint64_t> number;
/* Whether the currently running GC can finish in multiple slices. */
MainThreadData<bool> isIncremental;
/* Whether all zones are being collected in first GC slice. */
MainThreadData<bool> isFull;
/* Whether the heap will be compacted at the end of GC. */
MainThreadData<bool> isCompacting;
/* The invocation kind of the current GC, taken from the first slice. */
MainThreadData<JSGCInvocationKind> invocationKind;
/* The initial GC reason, taken from the first slice. */
MainThreadData<JS::GCReason> initialReason;
/*
* The current incremental GC phase. This is also used internally in
* non-incremental GC.
*/
MainThreadOrGCTaskData<State> incrementalState;
/* The incremental state at the start of this slice. */
MainThreadData<State> initialState;
#ifdef JS_GC_ZEAL
/* Whether to pay attention the zeal settings in this incremental slice. */
MainThreadData<bool> useZeal;
#endif
/* Indicates that the last incremental slice exhausted the mark stack. */
MainThreadData<bool> lastMarkSlice;
// Whether it's currently safe to yield to the mutator in an incremental GC.
MainThreadData<bool> safeToYield;
/* Whether any sweeping will take place in the separate GC helper thread. */
MainThreadData<bool> sweepOnBackgroundThread;
/* Singly linked list of zones to be swept in the background. */
HelperThreadLockData<ZoneList> backgroundSweepZones;
/*
* Free LIFO blocks are transferred to these allocators before being freed on
* a background thread.
*/
HelperThreadLockData<LifoAlloc> lifoBlocksToFree;
MainThreadData<LifoAlloc> lifoBlocksToFreeAfterMinorGC;
HelperThreadLockData<Nursery::BufferSet> buffersToFreeAfterMinorGC;
/* Index of current sweep group (for stats). */
MainThreadData<unsigned> sweepGroupIndex;
/*
* Incremental sweep state.
*/
MainThreadData<JS::Zone*> sweepGroups;
MainThreadOrGCTaskData<JS::Zone*> currentSweepGroup;
MainThreadData<UniquePtr<SweepAction<GCRuntime*, FreeOp*, SliceBudget&>>>
sweepActions;
MainThreadOrGCTaskData<JS::Zone*> sweepZone;
MainThreadData<mozilla::Maybe<AtomsTable::SweepIterator>> maybeAtomsToSweep;
MainThreadOrGCTaskData<JS::detail::WeakCacheBase*> sweepCache;
MainThreadData<bool> hasMarkedGrayRoots;
MainThreadData<bool> abortSweepAfterCurrentGroup;
#ifdef DEBUG
// During gray marking, delay AssertCellIsNotGray checks by
// recording the cell pointers here and checking after marking has
// finished.
MainThreadData<Vector<const Cell*, 0, SystemAllocPolicy>>
cellsToAssertNotGray;
friend void js::gc::detail::AssertCellIsNotGray(const Cell*);
#endif
friend class SweepGroupsIter;
friend class WeakCacheSweepIterator;
/*
* Incremental compacting state.
*/
MainThreadData<bool> startedCompacting;
MainThreadData<ZoneList> zonesToMaybeCompact;
MainThreadData<Arena*> relocatedArenasToRelease;
#ifdef JS_GC_ZEAL
MainThreadData<MarkingValidator*> markingValidator;
#endif
/*
* Default budget for incremental GC slice. See js/SliceBudget.h.
*
* JSGC_SLICE_TIME_BUDGET
* pref: javascript.options.mem.gc_incremental_slice_ms,
*/
MainThreadData<int64_t> defaultTimeBudget_;
/*
* We disable incremental GC if we encounter a Class with a trace hook
* that does not implement write barriers.
*/
MainThreadData<bool> incrementalAllowed;
/*
* Whether compacting GC can is enabled globally.
*
* JSGC_COMPACTING_ENABLED
* pref: javascript.options.mem.gc_compacting
*/
MainThreadData<bool> compactingEnabled;
MainThreadData<bool> rootsRemoved;
/*
* These options control the zealousness of the GC. At every allocation,
* nextScheduled is decremented. When it reaches zero we do a full GC.
*
* At this point, if zeal_ is one of the types that trigger periodic
* collection, then nextScheduled is reset to the value of zealFrequency.
* Otherwise, no additional GCs take place.
*
* You can control these values in several ways:
* - Set the JS_GC_ZEAL environment variable
* - Call gczeal() or schedulegc() from inside shell-executed JS code
* (see the help for details)
*
* If gcZeal_ == 1 then we perform GCs in select places (during MaybeGC and
* whenever we are notified that GC roots have been removed). This option is
* mainly useful to embedders.
*
* We use zeal_ == 4 to enable write barrier verification. See the comment
* in gc/Verifier.cpp for more information about this.
*
* zeal_ values from 8 to 10 periodically run different types of
* incremental GC.
*
* zeal_ value 14 performs periodic shrinking collections.
*/
#ifdef JS_GC_ZEAL
static_assert(size_t(ZealMode::Count) <= 32,
"Too many zeal modes to store in a uint32_t");
MainThreadData<uint32_t> zealModeBits;
MainThreadData<int> zealFrequency;
MainThreadData<int> nextScheduled;
MainThreadData<bool> deterministicOnly;
MainThreadData<int> incrementalLimit;
MainThreadData<Vector<JSObject*, 0, SystemAllocPolicy>> selectedForMarking;
#endif
MainThreadData<bool> fullCompartmentChecks;
MainThreadData<uint32_t> gcCallbackDepth;
Callback<JSGCCallback> gcCallback;
Callback<JS::DoCycleCollectionCallback> gcDoCycleCollectionCallback;
Callback<JSObjectsTenuredCallback> tenuredCallback;
CallbackVector<JSFinalizeCallback> finalizeCallbacks;
CallbackVector<JSWeakPointerZonesCallback> updateWeakPointerZonesCallbacks;
CallbackVector<JSWeakPointerCompartmentCallback>
updateWeakPointerCompartmentCallbacks;
MemoryCounter mallocCounter;
/*
* The trace operations to trace embedding-specific GC roots. One is for
* tracing through black roots and the other is for tracing through gray
* roots. The black/gray distinction is only relevant to the cycle
* collector.
*/
CallbackVector<JSTraceDataOp> blackRootTracers;
Callback<JSTraceDataOp> grayRootTracer;
/* Always preserve JIT code during GCs, for testing. */
MainThreadData<bool> alwaysPreserveCode;
#ifdef DEBUG
MainThreadData<bool> arenasEmptyAtShutdown;
#endif
/* Synchronize GC heap access among GC helper threads and the main thread. */
friend class js::AutoLockGC;