Debian Codegraph @

js/src/gc/GCRuntime.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef gc_GCRuntime_h
8 #define gc_GCRuntime_h
9
10 #include "mozilla/Atomics.h"
11 #include "mozilla/DoublyLinkedList.h"
12 #include "mozilla/EnumSet.h"
13 #include "mozilla/Maybe.h"
14 #include "mozilla/TimeStamp.h"
15
16 #include "gc/ArenaList.h"
17 #include "gc/AtomMarking.h"
18 #include "gc/GCContext.h"
19 #include "gc/GCMarker.h"
20 #include "gc/GCParallelTask.h"
21 #include "gc/IteratorUtils.h"
22 #include "gc/Memory.h"
23 #include "gc/Nursery.h"
24 #include "gc/Scheduling.h"
25 #include "gc/Statistics.h"
26 #include "gc/StoreBuffer.h"
27 #include "js/friend/CycleCollector.h"
28 #include "js/friend/PerformanceHint.h"
29 #include "js/GCAnnotations.h"
30 #include "js/UniquePtr.h"
31 #include "vm/AtomsTable.h"
32
33 namespace js {
34
35 class AutoLockGC;
36 class AutoLockGCBgAlloc;
37 class AutoLockHelperThreadState;
38 class FinalizationRegistryObject;
39 class FinalizationRecordObject;
40 class FinalizationQueueObject;
41 class GlobalObject;
42 class VerifyPreTracer;
43 class WeakRefObject;
44
45 namespace gc {
46
47 using BlackGrayEdgeVector = Vector<TenuredCell*, 0, SystemAllocPolicy>;
48 using ZoneVector = Vector<JS::Zone*, 4, SystemAllocPolicy>;
49
50 class AutoCallGCCallbacks;
51 class AutoGCSession;
52 class AutoHeapSession;
53 class AutoTraceSession;
54 class BufferAllocator;
55 class MarkingValidator;
56 struct MovingTracer;
57 class ParallelMarkTask;
58 enum class ShouldCheckThresholds;
59 class SweepGroupsIter;
60
61 // Interface to a sweep action.
62 struct SweepAction {
63 // The arguments passed to each action.
64 struct Args {
65 GCRuntime* gc;
66 JS::GCContext* gcx;
67 JS::SliceBudget& budget;
68 };
69
70 virtual ~SweepAction() = default;
71 virtual IncrementalProgress run(Args& state) = 0;
72 virtual void assertFinished() const = 0;
73 virtual bool shouldSkip() { return false; }
74 };
75
76 class ChunkPool {
77 ArenaChunk* head_;
78 size_t count_;
79
80 public:
81 ChunkPool() : head_(nullptr), count_(0) {}
82 ChunkPool(const ChunkPool& other) = delete;
83 ChunkPool(ChunkPool&& other) { *this = std::move(other); }
84
85 ~ChunkPool() {
86 MOZ_ASSERT(!head_);
87 MOZ_ASSERT(count_ == 0);
88 }
89
90 ChunkPool& operator=(const ChunkPool& other) = delete;
91 ChunkPool& operator=(ChunkPool&& other) {
92 head_ = other.head_;
93 other.head_ = nullptr;
94 count_ = other.count_;
95 other.count_ = 0;
96 return *this;
97 }
98
99 bool empty() const { return !head_; }
100 size_t count() const { return count_; }
101
102 ArenaChunk* head() {
103 MOZ_ASSERT(head_);
104 return head_;
105 }
106 ArenaChunk* pop();
107 void push(ArenaChunk* chunk);
108 ArenaChunk* remove(ArenaChunk* chunk);
109
110 void sort();
111
112 // Linear time, use with caution.
113 bool contains(ArenaChunk* chunk) const;
114
115 private:
116 ArenaChunk* mergeSort(ArenaChunk* list, size_t count);
117 bool isSorted() const;
118
119 #ifdef DEBUG
120 public:
121 bool verify() const;
122 void verifyChunks() const;
123 #endif
124
125 public:
126 // Pool mutation does not invalidate an Iter unless the mutation
127 // is of the ArenaChunk currently being visited by the Iter.
128 class Iter {
129 public:
130 explicit Iter(ChunkPool& pool) : current_(pool.head_) {}
131 bool done() const { return !current_; }
132 void next();
133 ArenaChunk* get() const { return current_; }
134 operator ArenaChunk*() const { return get(); }
135 ArenaChunk* operator->() const { return get(); }
136
137 private:
138 ArenaChunk* current_;
139 };
140 };
141
142 class BackgroundMarkTask : public GCParallelTask {
143 public:
144 explicit BackgroundMarkTask(GCRuntime* gc);
145 void setBudget(const JS::SliceBudget& budget) { this->budget = budget; }
146 void run(AutoLockHelperThreadState& lock) override;
147
148 private:
149 JS::SliceBudget budget;
150 };
151
152 class BackgroundUnmarkTask : public GCParallelTask {
153 public:
154 explicit BackgroundUnmarkTask(GCRuntime* gc);
155 void initZones();
156 void run(AutoLockHelperThreadState& lock) override;
157
158 private:
159 void unmark();
160
161 ZoneVector zones;
162 };
163
164 class BackgroundSweepTask : public GCParallelTask {
165 public:
166 explicit BackgroundSweepTask(GCRuntime* gc);
167 void run(AutoLockHelperThreadState& lock) override;
168 };
169
170 class BackgroundFreeTask : public GCParallelTask {
171 public:
172 explicit BackgroundFreeTask(GCRuntime* gc);
173 void run(AutoLockHelperThreadState& lock) override;
174 };
175
176 // Performs extra allocation off thread so that when memory is required on the
177 // main thread it will already be available and waiting.
178 class BackgroundAllocTask : public GCParallelTask {
179 // Guarded by the GC lock.
180 GCLockData<ChunkPool&> chunkPool_;
181
182 const bool enabled_;
183
184 public:
185 BackgroundAllocTask(GCRuntime* gc, ChunkPool& pool);
186 bool enabled() const { return enabled_; }
187
188 void run(AutoLockHelperThreadState& lock) override;
189 };
190
191 // Search the provided chunks for free arenas and decommit them.
192 class BackgroundDecommitTask : public GCParallelTask {
193 public:
194 explicit BackgroundDecommitTask(GCRuntime* gc);
195 void run(AutoLockHelperThreadState& lock) override;
196 };
197
198 template <typename F>
199 struct Callback {
200 F op;
201 void* data;
202
203 Callback() : op(nullptr), data(nullptr) {}
204 Callback(F op, void* data) : op(op), data(data) {}
205 };
206
207 template <typename F>
208 using CallbackVector = Vector<Callback<F>, 4, SystemAllocPolicy>;
209
210 using RootedValueMap =
211 HashMap<Value*, const char*, DefaultHasher<Value*>, SystemAllocPolicy>;
212
213 using AllocKinds = mozilla::EnumSet<AllocKind, uint64_t>;
214
215 // A singly linked list of zones.
216 class ZoneList {
217 static Zone* const End;
218
219 Zone* head;
220 Zone* tail;
221
222 public:
223 ZoneList();
224 ~ZoneList();
225
226 bool isEmpty() const;
227 Zone* front() const;
228
229 void prepend(Zone* zone);
230 void append(Zone* zone);
231 void prependList(ZoneList&& other);
232 void appendList(ZoneList&& other);
233 Zone* removeFront();
234 void clear();
235
236 private:
237 explicit ZoneList(Zone* singleZone);
238 void check() const;
239
240 ZoneList(const ZoneList& other) = delete;
241 ZoneList& operator=(const ZoneList& other) = delete;
242 };
243
244 struct WeakCacheToSweep {
245 JS::detail::WeakCacheBase* cache;
246 JS::Zone* zone;
247 };
248
249 class WeakCacheSweepIterator {
250 using WeakCacheBase = JS::detail::WeakCacheBase;
251
252 JS::Zone* sweepZone;
253 WeakCacheBase* sweepCache;
254
255 public:
256 explicit WeakCacheSweepIterator(JS::Zone* sweepGroup);
257
258 bool done() const;
259 WeakCacheToSweep get() const;
260 void next();
261
262 private:
263 void settle();
264 };
265
266 struct SweepingTracer final : public GenericTracerImpl<SweepingTracer> {
267 explicit SweepingTracer(JSRuntime* rt);
268
269 private:
270 template <typename T>
271 void onEdge(T** thingp, const char* name);
272 friend class GenericTracerImpl<SweepingTracer>;
273 };
274
275 class GCRuntime {
276 public:
277 explicit GCRuntime(JSRuntime* rt);
278 [[nodiscard]] bool init(uint32_t maxbytes);
279 bool wasInitialized() const { return initialized; }
280 void finishRoots();
281 void finish();
282
283 Zone* atomsZone() {
284 Zone* zone = zones()[0];
285 MOZ_ASSERT(JS::shadow::Zone::from(zone)->isAtomsZone());
286 return zone;
287 }
288 Zone* maybeSharedAtomsZone() { return sharedAtomsZone_; }
289
290 [[nodiscard]] bool freezeSharedAtomsZone();
291 void restoreSharedAtomsZone();
292
293 JS::HeapState heapState() const { return heapState_; }
294
295 bool hasZealMode(ZealMode mode) const;
296 bool hasAnyZealModeOf(mozilla::EnumSet<ZealMode> mode) const;
297 void clearZealMode(ZealMode mode);
298 bool needZealousGC();
299 bool zealModeControlsYieldPoint() const;
300
301 [[nodiscard]] bool addRoot(Value* vp, const char* name);
302 void removeRoot(Value* vp);
303
304 [[nodiscard]] bool setParameter(JSContext* cx, JSGCParamKey key,
305 uint32_t value);
306 void resetParameter(JSContext* cx, JSGCParamKey key);
307 uint32_t getParameter(JSGCParamKey key);
308
309 void setPerformanceHint(PerformanceHint hint);
310 bool isInPageLoad() const { return inPageLoadCount != 0; }
311
312 [[nodiscard]] bool triggerGC(JS::GCReason reason);
313 // Check whether to trigger a zone GC after allocating GC cells.
314 void maybeTriggerGCAfterAlloc(Zone* zone);
315 // Check whether to trigger a zone GC after malloc memory.
316 void maybeTriggerGCAfterMalloc(Zone* zone);
317 bool maybeTriggerGCAfterMalloc(Zone* zone, const HeapSize& heap,
318 const HeapThreshold& threshold,
319 JS::GCReason reason);
320 // The return value indicates if we were able to do the GC.
321 bool triggerZoneGC(Zone* zone, JS::GCReason reason, size_t usedBytes,
322 size_t thresholdBytes);
323
324 void maybeGC();
325
326 // Return whether we want to run a major GC. If eagerOk is true, include eager
327 // triggers (eg EAGER_ALLOC_TRIGGER) in this determination, and schedule all
328 // zones that exceed the eager thresholds.
329 JS::GCReason wantMajorGC(bool eagerOk);
330 bool checkEagerAllocTrigger(const HeapSize& size,
331 const HeapThreshold& threshold);
332
333 // Do a minor GC if requested, followed by a major GC if requested. The return
334 // value indicates whether a major GC was performed.
335 bool gcIfRequested() { return gcIfRequestedImpl(false); }
336
337 // Internal function to do a GC if previously requested. But if not and
338 // eagerOk, do an eager GC for all Zones that have exceeded the eager
339 // thresholds.
340 //
341 // Return whether a major GC was performed or started.
342 bool gcIfRequestedImpl(bool eagerOk);
343
344 void gc(JS::GCOptions options, JS::GCReason reason);
345 void startGC(JS::GCOptions options, JS::GCReason reason,
346 const JS::SliceBudget& budget);
347 void gcSlice(JS::GCReason reason, const JS::SliceBudget& budget);
348 void finishGC(JS::GCReason reason);
349 void abortGC();
350 void startDebugGC(JS::GCOptions options, const JS::SliceBudget& budget);
351 void debugGCSlice(const JS::SliceBudget& budget);
352
353 void runDebugGC();
354 void notifyRootsRemoved();
355
356 enum TraceOrMarkRuntime { TraceRuntime, MarkRuntime };
357 void traceRuntime(JSTracer* trc, AutoHeapSession& session);
358 void traceRuntimeForMinorGC(JSTracer* trc, AutoGCSession& session);
359
360 void purgeRuntimeForMinorGC();
361
362 void shrinkBuffers();
363 void onOutOfMallocMemory();
364 void onOutOfMallocMemory(const AutoLockGC& lock);
365
366 Nursery& nursery() { return nursery_.ref(); }
367 gc::StoreBuffer& storeBuffer() { return storeBuffer_.ref(); }
368
369 void minorGC(JS::GCReason reason,
370 gcstats::PhaseKind phase = gcstats::PhaseKind::MINOR_GC)
371 JS_HAZ_GC_CALL;
372 void evictNursery(JS::GCReason reason = JS::GCReason::EVICT_NURSERY) {
373 minorGC(reason, gcstats::PhaseKind::EVICT_NURSERY);
374 }
375
376 void* addressOfNurseryPosition() {
377 return nursery_.refNoCheck().addressOfPosition();
378 }
379
380 void* addressOfNurseryAllocatedSites() {
381 return nursery_.refNoCheck().addressOfNurseryAllocatedSites();
382 }
383
384 const void* addressOfLastBufferedWholeCell() {
385 return storeBuffer_.refNoCheck().addressOfLastBufferedWholeCell();
386 }
387
388 #ifdef JS_GC_ZEAL
389 const uint32_t* addressOfZealModeBits() { return &zealModeBits.refNoCheck(); }
390 void getZealBits(uint32_t* zealBits, uint32_t* frequency,
391 uint32_t* nextScheduled);
392 void setZeal(uint8_t zeal, uint32_t frequency);
393 void unsetZeal(uint8_t zeal);
394 // Note that currently, different modes cannot have different frequencies.
395 struct ZealSetting {
396 uint8_t mode;
397 uint32_t frequency;
398 };
399 using ZealSettings = js::Vector<ZealSetting, 0, SystemAllocPolicy>;
400 bool parseZeal(const char* str, size_t len, ZealSettings* zeal,
401 bool* invalid);
402 bool parseAndSetZeal(const char* str);
403 void setNextScheduled(uint32_t count);
404 void verifyPreBarriers();
405 void maybeVerifyPreBarriers(bool always);
406 void verifyPostBarriers();
407 bool selectForMarking(JSObject* object);
408 void clearSelectedForMarking();
409 void setDeterministic(bool enable);
410 void setMarkStackLimit(size_t limit, AutoLockGC& lock);
411 #endif
412
413 uint64_t nextCellUniqueId() {
414 MOZ_ASSERT(nextCellUniqueId_ > 0);
415 uint64_t uid = ++nextCellUniqueId_;
416 return uid;
417 }
418
419 void setLowMemoryState(bool newState) { lowMemoryState = newState; }
420 bool systemHasLowMemory() const { return lowMemoryState; }
421
422 public:
423 // Internal public interface
424 ZoneVector& zones() { return zones_.ref(); }
425 gcstats::Statistics& stats() { return stats_.ref(); }
426 const gcstats::Statistics& stats() const { return stats_.ref(); }
427 State state() const { return incrementalState; }
428 bool isHeapCompacting() const { return state() == State::Compact; }
429 bool isForegroundSweeping() const { return state() == State::Sweep; }
430 bool isBackgroundSweeping() const { return sweepTask.wasStarted(); }
431 bool isBackgroundMarking() const { return markTask.wasStarted(); }
432 bool isBackgroundDecommitting() const { return decommitTask.wasStarted(); }
433 void waitBackgroundSweepEnd();
434 void waitBackgroundDecommitEnd();
435 void waitBackgroundAllocEnd() { allocTask.cancelAndWait(); }
436 void waitBackgroundFreeEnd();
437 void waitForBackgroundTasks();
438 bool isWaitingOnBackgroundTask() const;
439
440 void lockGC() { lock.lock(); }
441 void unlockGC() { lock.unlock(); }
442
443 void lockStoreBuffer() { storeBufferLock.lock(); }
444 void unlockStoreBuffer() { storeBufferLock.unlock(); }
445
446 #ifdef DEBUG
447 void assertCurrentThreadHasLockedGC() const {
448 lock.assertOwnedByCurrentThread();
449 }
450 void assertCurrentThreadHasLockedStoreBuffer() const {
451 storeBufferLock.assertOwnedByCurrentThread();
452 }
453 #endif // DEBUG
454
455 void setAlwaysPreserveCode() { alwaysPreserveCode = true; }
456
457 void setIncrementalGCEnabled(bool enabled);
458 void setNurseryEnabled(bool enabled);
459
460 bool isIncrementalGCEnabled() const { return incrementalGCEnabled; }
461 bool isPerZoneGCEnabled() const { return perZoneGCEnabled; }
462 bool isCompactingGCEnabled() const;
463 bool isParallelMarkingEnabled() const { return parallelMarkingEnabled; }
464
465 bool isIncrementalGCInProgress() const {
466 return state() != State::NotActive && !isVerifyPreBarriersEnabled();
467 }
468
469 bool hasForegroundWork() const;
470
471 bool isShrinkingGC() const { return gcOptions() == JS::GCOptions::Shrink; }
472
473 bool isShutdownGC() const { return gcOptions() == JS::GCOptions::Shutdown; }
474
475 #ifdef DEBUG
476 bool isShuttingDown() const { return hadShutdownGC; }
477 #endif
478
479 bool initSweepActions();
480
481 void setGrayRootsTracer(JSGrayRootsTracer traceOp, void* data);
482 [[nodiscard]] bool addBlackRootsTracer(JSTraceDataOp traceOp, void* data);
483 void removeBlackRootsTracer(JSTraceDataOp traceOp, void* data);
484 void clearBlackAndGrayRootTracers();
485
486 void setGCCallback(JSGCCallback callback, void* data);
487 void callGCCallback(JSGCStatus status, JS::GCReason reason) const;
488 void setObjectsTenuredCallback(JSObjectsTenuredCallback callback, void* data);
489 void callObjectsTenuredCallback();
490 [[nodiscard]] bool addFinalizeCallback(JSFinalizeCallback callback,
491 void* data);
492 void removeFinalizeCallback(JSFinalizeCallback callback);
493 void setHostCleanupFinalizationRegistryCallback(
494 JSHostCleanupFinalizationRegistryCallback callback, void* data);
495 void callHostCleanupFinalizationRegistryCallback(JSFunction* doCleanup,
496 JSObject* hostDefinedData);
497 [[nodiscard]] bool addWeakPointerZonesCallback(
498 JSWeakPointerZonesCallback callback, void* data);
499 void removeWeakPointerZonesCallback(JSWeakPointerZonesCallback callback);
500 [[nodiscard]] bool addWeakPointerCompartmentCallback(
501 JSWeakPointerCompartmentCallback callback, void* data);
502 void removeWeakPointerCompartmentCallback(
503 JSWeakPointerCompartmentCallback callback);
504 JS::GCSliceCallback setSliceCallback(JS::GCSliceCallback callback);
505 bool addNurseryCollectionCallback(JS::GCNurseryCollectionCallback callback,
506 void* data);
507 void removeNurseryCollectionCallback(JS::GCNurseryCollectionCallback callback,
508 void* data);
509 JS::DoCycleCollectionCallback setDoCycleCollectionCallback(
510 JS::DoCycleCollectionCallback callback);
511 void callNurseryCollectionCallbacks(JS::GCNurseryProgress progress,
512 JS::GCReason reason);
513
514 bool addFinalizationRegistry(JSContext* cx,
515 Handle<FinalizationRegistryObject*> registry);
516 bool registerWithFinalizationRegistry(JSContext* cx, HandleObject target,
517 HandleObject record);
518 void queueFinalizationRegistryForCleanup(FinalizationQueueObject* queue);
519
520 void nukeFinalizationRecordWrapper(JSObject* wrapper,
521 FinalizationRecordObject* record);
522 void nukeWeakRefWrapper(JSObject* wrapper, WeakRefObject* weakRef);
523
524 void setFullCompartmentChecks(bool enable);
525
526 // Get the main marking tracer.
527 GCMarker& marker() { return *markers[0]; }
528
529 bool haveAllImplicitEdges() const { return haveAllImplicitEdges_; }
530 void clearHaveAllImplicitEdges() { haveAllImplicitEdges_ = false; }
531
532 JS::Zone* getCurrentSweepGroup() { return currentSweepGroup; }
533 unsigned getCurrentSweepGroupIndex() {
534 MOZ_ASSERT_IF(unsigned(state()) < unsigned(State::Sweep),
535 sweepGroupIndex == 0);
536 return sweepGroupIndex;
537 }
538
539 uint64_t gcNumber() const { return number; }
540 void incGcNumber() { ++number; }
541
542 uint64_t minorGCCount() const { return minorGCNumber; }
543 void incMinorGcNumber() { ++minorGCNumber; }
544
545 uint64_t majorGCCount() const { return majorGCNumber; }
546 void incMajorGcNumber() { ++majorGCNumber; }
547
548 uint64_t gcSliceCount() const { return sliceNumber; }
549 void incGcSliceNumber() { ++sliceNumber; }
550
551 int64_t defaultSliceBudgetMS() const { return defaultTimeBudgetMS_; }
552
553 bool isIncrementalGc() const { return isIncremental; }
554 bool isFullGc() const { return isFull; }
555 bool isCompactingGc() const { return isCompacting; }
556 bool didCompactZones() const { return isCompacting && zonesCompacted; }
557
558 bool areGrayBitsValid() const { return grayBitsValid; }
559 void setGrayBitsInvalid() { grayBitsValid = false; }
560
561 mozilla::TimeStamp lastGCStartTime() const { return lastGCStartTime_; }
562 mozilla::TimeStamp lastGCEndTime() const { return lastGCEndTime_; }
563
564 bool majorGCRequested() const {
565 return majorGCTriggerReason != JS::GCReason::NO_REASON;
566 }
567
568 double computeHeapGrowthFactor(size_t lastBytes);
569 size_t computeTriggerBytes(double growthFactor, size_t lastBytes);
570
571 ChunkPool& fullChunks(const AutoLockGC& lock) { return fullChunks_.ref(); }
572 ChunkPool& availableChunks(const AutoLockGC& lock) {
573 return availableChunks_.ref();
574 }
575 ChunkPool& emptyChunks(const AutoLockGC& lock) { return emptyChunks_.ref(); }
576 const ChunkPool& fullChunks(const AutoLockGC& lock) const {
577 return fullChunks_.ref();
578 }
579 const ChunkPool& availableChunks(const AutoLockGC& lock) const {
580 return availableChunks_.ref();
581 }
582 const ChunkPool& emptyChunks(const AutoLockGC& lock) const {
583 return emptyChunks_.ref();
584 }
585 using NonEmptyChunksIter = ChainedIterator<ChunkPool::Iter, 2>;
586 NonEmptyChunksIter allNonEmptyChunks(const AutoLockGC& lock) {
587 clearCurrentChunk(lock);
588 return NonEmptyChunksIter(availableChunks(lock), fullChunks(lock));
589 }
590 uint32_t minEmptyChunkCount(const AutoLockGC& lock) const {
591 return minEmptyChunkCount_;
592 }
593 void setCurrentChunk(ArenaChunk* chunk, const AutoLockGC& lock);
594 void clearCurrentChunk(const AutoLockGC& lock);
595 #ifdef DEBUG
596 bool isCurrentChunk(ArenaChunk* chunk) const {
597 return chunk == currentChunk_;
598 }
599 void verifyAllChunks();
600 #endif
601
602 // Get a free chunk or allocate one if needed. The chunk is left in the empty
603 // chunks pool.
604 ArenaChunk* getOrAllocChunk(StallAndRetry stallAndRetry,
605 AutoLockGCBgAlloc& lock);
606
607 // Get or allocate a free chunk, removing it from the empty chunks pool.
608 ArenaChunk* takeOrAllocChunk(StallAndRetry stallAndRetry,
609 AutoLockGCBgAlloc& lock);
610
611 void recycleChunk(ArenaChunk* chunk, const AutoLockGC& lock);
612
613 #ifdef JS_GC_ZEAL
614 void startVerifyPreBarriers();
615 void endVerifyPreBarriers();
616 void finishVerifier();
617 bool isVerifyPreBarriersEnabled() const { return verifyPreData.refNoCheck(); }
618 bool shouldYieldForZeal(ZealMode mode);
619 void verifyPostBarriers(AutoHeapSession& session);
620 void checkHeapBeforeMinorGC(AutoHeapSession& session);
621 #else
622 bool isVerifyPreBarriersEnabled() const { return false; }
623 #endif
624
625 #ifdef JSGC_HASH_TABLE_CHECKS
626 void checkHashTablesAfterMovingGC();
627 #endif
628
629 // Crawl the heap to check whether an arbitary pointer is within a cell of
630 // the given kind. (TraceKind::Null means to ignore the kind.)
631 bool isPointerWithinTenuredCell(
632 void* ptr, JS::TraceKind traceKind = JS::TraceKind::Null);
633 // Crawl the heap to check whether an arbitary pointer is within a buffer.
634 bool isPointerWithinBufferAlloc(void* ptr);
635
636 #ifdef DEBUG
637 bool hasZone(Zone* target);
638 #endif
639
640 // Queue memory memory to be freed on a background thread if possible.
641 void queueUnusedLifoBlocksForFree(LifoAlloc* lifo);
642 void queueAllLifoBlocksForFreeAfterMinorGC(LifoAlloc* lifo);
643 void queueBuffersForFreeAfterMinorGC(
644 Nursery::BufferSet& buffers, Nursery::StringBufferVector& stringBuffers);
645
646 // Public here for ReleaseArenaLists and FinalizeTypedArenas.
647 void releaseArena(Arena* arena, const AutoLockGC& lock);
648 void releaseArenas(Arena* arena, const AutoLockGC& lock);
649 void releaseArenaList(ArenaList& arenaList, const AutoLockGC& lock);
650
651 Arena* releaseSomeEmptyArenas(Zone* zone, Arena* emptyArenas);
652
653 // Allocator internals.
654 static void* refillFreeListInGC(Zone* zone, AllocKind thingKind);
655
656 // Delayed marking.
657 void delayMarkingChildren(gc::Cell* cell, MarkColor color);
658 bool hasDelayedMarking() const;
659 void markAllDelayedChildren(ShouldReportMarkTime reportTime);
660
661 // If we have yielded to the mutator while foreground finalizing arenas from
662 // zone |zone| with kind |kind| then return a list of the arenas finalized so
663 // far. These will have been removed from the main arena lists at this
664 // point. Otherwise return nullptr.
665 SortedArenaList* maybeGetForegroundFinalizedArenas(Zone* zone,
666 AllocKind kind);
667
668 /*
669 * Concurrent sweep infrastructure.
670 */
671 void startTask(GCParallelTask& task, AutoLockHelperThreadState& lock);
672 void joinTask(GCParallelTask& task, AutoLockHelperThreadState& lock);
673 void updateHelperThreadCount();
674 size_t parallelWorkerCount() const;
675 void maybeRequestGCAfterBackgroundTask(const AutoLockHelperThreadState& lock);
676
677 // GC parallel task dispatch infrastructure.
678 size_t getMaxParallelThreads() const;
679 void dispatchOrQueueParallelTask(GCParallelTask* task,
680 const AutoLockHelperThreadState& lock);
681 void maybeDispatchParallelTasks(const AutoLockHelperThreadState& lock);
682 void onParallelTaskEnd(bool wasDispatched,
683 const AutoLockHelperThreadState& lock);
684
685 // Parallel marking.
686 bool setParallelMarkingEnabled(bool enabled);
687 bool initOrDisableParallelMarking();
688 [[nodiscard]] bool updateMarkersVector();
689 size_t markingWorkerCount() const;
690
691 // WeakRefs
692 bool registerWeakRef(HandleObject target, HandleObject weakRef);
693 void traceKeptObjects(JSTracer* trc);
694
695 void maybeClearWeakRefTargets(JS::ShouldClearWeakRefTargetCallback callback,
696 void* data);
697
698 JS::GCReason lastStartReason() const { return initialReason; }
699
700 void updateAllocationRates();
701
702 // Allocator internals
703 static void* refillFreeList(JS::Zone* zone, AllocKind thingKind);
704 void attemptLastDitchGC();
705
706 // Test mark queue.
707 #ifdef DEBUG
708 const GCVector<HeapPtr<JS::Value>, 0, SystemAllocPolicy>& getTestMarkQueue()
709 const;
710 [[nodiscard]] bool appendTestMarkQueue(const JS::Value& value);
711 void clearTestMarkQueue();
712 size_t testMarkQueuePos() const;
713 size_t testMarkQueueRemaining() const;
714 #endif
715
716 private:
717 enum class IncrementalResult { Reset = 0, Abort, Ok };
718
719 bool hasBuffersForBackgroundFree() const {
720 return !lifoBlocksToFree.ref().isEmpty() ||
721 !buffersToFreeAfterMinorGC.ref().empty() ||
722 !stringBuffersToReleaseAfterMinorGC.ref().empty();
723 }
724
725 // Returns false on failure without raising an exception.
726 [[nodiscard]] bool setParameter(JSGCParamKey key, uint32_t value,
727 AutoLockGC& lock);
728 void resetParameter(JSGCParamKey key, AutoLockGC& lock);
729 uint32_t getParameter(JSGCParamKey key, const AutoLockGC& lock);
730 // Returns false on failure without raising an exception.
731 bool setThreadParameter(JSGCParamKey key, uint32_t value, AutoLockGC& lock);
732 void resetThreadParameter(JSGCParamKey key, AutoLockGC& lock);
733 void updateThreadDataStructures(AutoLockGC& lock);
734
735 JS::GCOptions gcOptions() const { return maybeGcOptions.ref().ref(); }
736
737 TriggerResult checkHeapThreshold(Zone* zone, const HeapSize& heapSize,
738 const HeapThreshold& heapThreshold);
739
740 void updateSchedulingStateOnGCStart();
741 void updateSchedulingStateOnGCEnd(mozilla::TimeStamp currentTime);
742 void updateAllGCStartThresholds();
743
744 // For ArenaLists::allocateFromArena()
745 friend class ArenaLists;
746 ArenaChunk* pickChunk(StallAndRetry stallAndRetry, AutoLockGCBgAlloc& lock);
747 Arena* allocateArena(ArenaChunk* chunk, Zone* zone, AllocKind kind,
748 ShouldCheckThresholds checkThresholds);
749
750 /*
751 * Return the list of chunks that can be released outside the GC lock.
752 * Must be called either during the GC or with the GC lock taken.
753 */
754 friend class BackgroundDecommitTask;
755 bool tooManyEmptyChunks(const AutoLockGC& lock);
756 ChunkPool expireEmptyChunkPool(const AutoLockGC& lock);
757 void freeEmptyChunks(const AutoLockGC& lock);
758 void prepareToFreeChunk(ArenaChunkInfo& info);
759 void setMinEmptyChunkCount(uint32_t value, const AutoLockGC& lock);
760
761 friend class BackgroundAllocTask;
762 bool wantBackgroundAllocation(const AutoLockGC& lock) const;
763 void startBackgroundAllocTaskIfIdle();
764
765 void requestMajorGC(JS::GCReason reason);
766 JS::SliceBudget defaultBudget(JS::GCReason reason, int64_t millis);
767 bool maybeIncreaseSliceBudget(JS::SliceBudget& budget,
768 mozilla::TimeStamp sliceStartTime,
769 mozilla::TimeStamp gcStartTime);
770 bool maybeIncreaseSliceBudgetForLongCollections(
771 JS::SliceBudget& budget, mozilla::TimeStamp sliceStartTime,
772 mozilla::TimeStamp gcStartTime);
773 bool maybeIncreaseSliceBudgetForUrgentCollections(JS::SliceBudget& budget);
774 IncrementalResult budgetIncrementalGC(bool nonincrementalByAPI,
775 JS::GCReason reason,
776 JS::SliceBudget& budget);
777 void checkZoneIsScheduled(Zone* zone, JS::GCReason reason,
778 const char* trigger);
779 IncrementalResult resetIncrementalGC(GCAbortReason reason);
780
781 // Assert if the system state is such that we should never
782 // receive a request to do GC work.
783 void checkCanCallAPI();
784
785 // Check if the system state is such that GC has been supressed
786 // or otherwise delayed.
787 [[nodiscard]] bool checkIfGCAllowedInCurrentState(JS::GCReason reason);
788
789 gcstats::ZoneGCStats scanZonesBeforeGC();
790
791 void setGCOptions(JS::GCOptions options);
792
793 void collect(bool nonincrementalByAPI, const JS::SliceBudget& budget,
794 JS::GCReason reason) JS_HAZ_GC_CALL;
795
796 /*
797 * Run one GC "cycle" (either a slice of incremental GC or an entire
798 * non-incremental GC).
799 *
800 * Returns:
801 * * ResetIncremental if we "reset" an existing incremental GC, which would
802 * force us to run another cycle or
803 * * Ok otherwise.
804 */
805 [[nodiscard]] IncrementalResult gcCycle(bool nonincrementalByAPI,
806 const JS::SliceBudget& budgetArg,
807 JS::GCReason reason);
808 bool shouldRepeatForDeadZone(JS::GCReason reason);
809
810 void incrementalSlice(JS::SliceBudget& budget, JS::GCReason reason,
811 bool budgetWasIncreased);
812
813 bool mightSweepInThisSlice(bool nonIncremental);
814 void collectNurseryFromMajorGC(JS::GCReason reason);
815 void collectNursery(JS::GCOptions options, JS::GCReason reason,
816 gcstats::PhaseKind phase);
817
818 friend class AutoCallGCCallbacks;
819 void maybeCallGCCallback(JSGCStatus status, JS::GCReason reason);
820
821 void startCollection(JS::GCReason reason);
822
823 void purgeRuntime();
824 [[nodiscard]] bool beginPreparePhase(JS::GCReason reason,
825 AutoGCSession& session);
826 bool prepareZonesForCollection(JS::GCReason reason, bool* isFullOut);
827 void unmarkWeakMaps();
828 void endPreparePhase(JS::GCReason reason);
829 void beginMarkPhase(AutoGCSession& session);
830 bool shouldPreserveJITCode(JS::Realm* realm,
831 const mozilla::TimeStamp& currentTime,
832 JS::GCReason reason, bool canAllocateMoreCode,
833 bool isActiveCompartment);
834 void maybeDiscardJitCodeForGC();
835 void startBackgroundFreeAfterMinorGC();
836 void relazifyFunctionsForShrinkingGC();
837 void purgePropMapTablesForShrinkingGC();
838 void purgeSourceURLsForShrinkingGC();
839 void traceRuntimeForMajorGC(JSTracer* trc, AutoGCSession& session);
840 void traceRuntimeAtoms(JSTracer* trc);
841 void traceRuntimeCommon(JSTracer* trc, TraceOrMarkRuntime traceOrMark);
842 void traceEmbeddingBlackRoots(JSTracer* trc);
843 void traceEmbeddingGrayRoots(JSTracer* trc);
844 IncrementalProgress traceEmbeddingGrayRoots(JSTracer* trc,
845 JS::SliceBudget& budget);
846 void checkNoRuntimeRoots(AutoGCSession& session);
847 void maybeDoCycleCollection();
848 void findDeadCompartments();
849
850 friend class BackgroundMarkTask;
851 enum ParallelMarking : bool {
852 SingleThreadedMarking = false,
853 AllowParallelMarking = true
854 };
855 IncrementalProgress markUntilBudgetExhausted(
856 JS::SliceBudget& sliceBudget,
857 ParallelMarking allowParallelMarking = SingleThreadedMarking,
858 ShouldReportMarkTime reportTime = ReportMarkTime);
859 bool canMarkInParallel() const;
860 bool initParallelMarking();
861 void finishParallelMarkers();
862
863 bool reserveMarkingThreads(size_t count);
864 void releaseMarkingThreads();
865
866 bool hasMarkingWork(MarkColor color) const;
867
868 void drainMarkStack();
869
870 #ifdef DEBUG
871 void assertNoMarkingWork() const;
872 #else
873 void assertNoMarkingWork() const {}
874 #endif
875
876 void markDelayedChildren(gc::Arena* arena, MarkColor color);
877 void processDelayedMarkingList(gc::MarkColor color);
878 void rebuildDelayedMarkingList();
879 void appendToDelayedMarkingList(gc::Arena** listTail, gc::Arena* arena);
880 void resetDelayedMarking();
881 template <typename F>
882 void forEachDelayedMarkingArena(F&& f);
883
884 template <class ZoneIterT>
885 IncrementalProgress markWeakReferences(JS::SliceBudget& budget);
886 IncrementalProgress markWeakReferencesInCurrentGroup(JS::SliceBudget& budget);
887 IncrementalProgress markGrayRoots(JS::SliceBudget& budget,
888 gcstats::PhaseKind phase);
889 void markBufferedGrayRoots(JS::Zone* zone);
890 IncrementalProgress markAllWeakReferences();
891 void markAllGrayReferences(gcstats::PhaseKind phase);
892
893 // The mark queue is a testing-only feature for controlling mark ordering and
894 // yield timing.
895 enum MarkQueueProgress {
896 QueueYielded, // End this incremental GC slice, if possible
897 QueueComplete, // Done with the queue
898 QueueSuspended // Continue the GC without ending the slice
899 };
900 MarkQueueProgress processTestMarkQueue();
901
902 // GC Sweeping. Implemented in Sweeping.cpp.
903 void beginSweepPhase(JS::GCReason reason, AutoGCSession& session);
904 void dropStringWrappers();
905 void groupZonesForSweeping(JS::GCReason reason);
906 [[nodiscard]] bool findSweepGroupEdges();
907 [[nodiscard]] bool addEdgesForMarkQueue();
908 void moveToNextSweepGroup();
909 void resetGrayList(Compartment* comp);
910 IncrementalProgress beginMarkingSweepGroup(JS::GCContext* gcx,
911 JS::SliceBudget& budget);
912 IncrementalProgress markGrayRootsInCurrentGroup(JS::GCContext* gcx,
913 JS::SliceBudget& budget);
914 IncrementalProgress markGray(JS::GCContext* gcx, JS::SliceBudget& budget);
915 IncrementalProgress endMarkingSweepGroup(JS::GCContext* gcx,
916 JS::SliceBudget& budget);
917 void markIncomingGrayCrossCompartmentPointers();
918 IncrementalProgress beginSweepingSweepGroup(JS::GCContext* gcx,
919 JS::SliceBudget& budget);
920 void initBackgroundSweep(Zone* zone, JS::GCContext* gcx,
921 const AllocKinds& kinds);
922 IncrementalProgress markDuringSweeping(JS::GCContext* gcx,
923 JS::SliceBudget& budget);
924 void updateAtomsBitmap();
925 void sweepCCWrappers();
926 void sweepRealmGlobals();
927 void sweepEmbeddingWeakPointers(JS::GCContext* gcx);
928 void sweepMisc();
929 void sweepCompressionTasks();
930 void sweepWeakMaps();
931 void sweepUniqueIds();
932 void sweepObjectsWithWeakPointers();
933 void sweepDebuggerOnMainThread(JS::GCContext* gcx);
934 void sweepJitDataOnMainThread(JS::GCContext* gcx);
935 void sweepFinalizationObserversOnMainThread();
936 void traceWeakFinalizationObserverEdges(JSTracer* trc, Zone* zone);
937 void sweepWeakRefs();
938 IncrementalProgress endSweepingSweepGroup(JS::GCContext* gcx,
939 JS::SliceBudget& budget);
940 IncrementalProgress performSweepActions(JS::SliceBudget& sliceBudget);
941 void startSweepingAtomsTable();
942 IncrementalProgress sweepAtomsTable(JS::GCContext* gcx,
943 JS::SliceBudget& budget);
944 IncrementalProgress sweepWeakCaches(JS::GCContext* gcx,
945 JS::SliceBudget& budget);
946 IncrementalProgress finalizeAllocKind(JS::GCContext* gcx,
947 JS::SliceBudget& budget);
948 IncrementalProgress sweepPropMapTree(JS::GCContext* gcx,
949 JS::SliceBudget& budget);
950 void endSweepPhase(bool destroyingRuntime);
951 void queueZonesAndStartBackgroundSweep(ZoneList&& zones);
952 void sweepFromBackgroundThread(AutoLockHelperThreadState& lock);
953 void startBackgroundFree();
954 void freeFromBackgroundThread(AutoLockHelperThreadState& lock);
955 void sweepBackgroundThings(ZoneList& zones);
956 void prepareForSweepSlice(JS::GCReason reason);
957 void assertBackgroundSweepingFinished();
958 #ifdef DEBUG
959 bool zoneInCurrentSweepGroup(Zone* zone) const;
960 #endif
961
962 bool allCCVisibleZonesWereCollected();
963 void sweepZones(JS::GCContext* gcx, bool destroyingRuntime);
964 bool shouldDecommit() const;
965 void startDecommit();
966 void decommitEmptyChunks(const bool& cancel, AutoLockGC& lock);
967 void decommitFreeArenas(const bool& cancel, AutoLockGC& lock);
968 void decommitFreeArenasWithoutUnlocking(const AutoLockGC& lock);
969
970 // Compacting GC. Implemented in Compacting.cpp.
971 bool shouldCompact();
972 void beginCompactPhase();
973 IncrementalProgress compactPhase(JS::GCReason reason,
974 JS::SliceBudget& sliceBudget,
975 AutoGCSession& session);
976 void endCompactPhase();
977 void sweepZoneAfterCompacting(MovingTracer* trc, Zone* zone);
978 bool canRelocateZone(Zone* zone) const;
979 [[nodiscard]] bool relocateArenas(Zone* zone, JS::GCReason reason,
980 Arena*& relocatedListOut,
981 JS::SliceBudget& sliceBudget);
982 void updateCellPointers(Zone* zone, AllocKinds kinds);
983 void updateAllCellPointers(MovingTracer* trc, Zone* zone);
984 void updateZonePointersToRelocatedCells(Zone* zone);
985 void updateRuntimePointersToRelocatedCells(AutoGCSession& session);
986 void clearRelocatedArenas(Arena* arenaList, JS::GCReason reason);
987 void clearRelocatedArenasWithoutUnlocking(Arena* arenaList,
988 JS::GCReason reason,
989 const AutoLockGC& lock);
990 void releaseRelocatedArenas(Arena* arenaList);
991 void releaseRelocatedArenasWithoutUnlocking(Arena* arenaList,
992 const AutoLockGC& lock);
993 #ifdef DEBUG
994 void protectOrReleaseRelocatedArenas(Arena* arenaList, JS::GCReason reason);
995 void protectAndHoldArenas(Arena* arenaList);
996 void unprotectHeldRelocatedArenas(const AutoLockGC& lock);
997 void releaseHeldRelocatedArenas();
998 void releaseHeldRelocatedArenasWithoutUnlocking(const AutoLockGC& lock);
999 #endif
1000
1001 IncrementalProgress waitForBackgroundTask(GCParallelTask& task,
1002 const JS::SliceBudget& budget,
1003 bool shouldPauseMutator);
1004
1005 void cancelRequestedGCAfterBackgroundTask();
1006 void finishCollection(JS::GCReason reason);
1007 void maybeStopPretenuring();
1008 void checkGCStateNotInUse();
1009 IncrementalProgress joinBackgroundMarkTask();
1010
1011 #ifdef JS_GC_ZEAL
1012 void computeNonIncrementalMarkingForValidation(AutoGCSession& session);
1013 void validateIncrementalMarking();
1014 void finishMarkingValidation();
1015 #endif
1016
1017 #ifdef DEBUG
1018 void checkForCompartmentMismatches();
1019 #endif
1020
1021 void callFinalizeCallbacks(JS::GCContext* gcx, JSFinalizeStatus status) const;
1022 void callWeakPointerZonesCallbacks(JSTracer* trc) const;
1023 void callWeakPointerCompartmentCallbacks(JSTracer* trc,
1024 JS::Compartment* comp) const;
1025 void callDoCycleCollectionCallback(JSContext* cx);
1026
1027 public:
1028 JSRuntime* const rt;
1029
1030 // Embedders can use this zone however they wish.
1031 MainThreadData<JS::Zone*> systemZone;
1032
1033 MainThreadData<JS::GCContext> mainThreadContext;
1034
1035 private:
1036 // For parent runtimes, a zone containing atoms that is shared by child
1037 // runtimes.
1038 MainThreadData<Zone*> sharedAtomsZone_;
1039
1040 // All zones in the runtime. The first element is always the atoms zone.
1041 MainThreadOrGCTaskData<ZoneVector> zones_;
1042
1043 // Any activity affecting the heap.
1044 MainThreadOrGCTaskData<JS::HeapState> heapState_;
1045 friend class AutoHeapSession;
1046 friend class JS::AutoEnterCycleCollection;
1047
1048 UnprotectedData<gcstats::Statistics> stats_;
1049
1050 public:
1051 js::StringStats stringStats;
1052
1053 Vector<UniquePtr<GCMarker>, 1, SystemAllocPolicy> markers;
1054
1055 // Delayed marking support in case we OOM pushing work onto the mark stack.
1056 MainThreadOrGCTaskData<js::gc::Arena*> delayedMarkingList;
1057 MainThreadOrGCTaskData<bool> delayedMarkingWorkAdded;
1058 #ifdef DEBUG
1059 /* Count of arenas that are currently in the stack. */
1060 MainThreadOrGCTaskData<size_t> markLaterArenas;
1061 #endif
1062
1063 SweepingTracer sweepingTracer;
1064
1065 /* Track total GC heap size for this runtime. */
1066 HeapSize heapSize;
1067
1068 /* GC scheduling state and parameters. */
1069 GCSchedulingTunables tunables;
1070 GCSchedulingState schedulingState;
1071 MainThreadData<bool> fullGCRequested;
1072
1073 // Helper thread configuration.
1074 MainThreadData<double> helperThreadRatio;
1075 MainThreadData<size_t> maxHelperThreads;
1076 MainThreadOrGCTaskData<size_t> helperThreadCount;
1077 MainThreadData<size_t> maxMarkingThreads;
1078 MainThreadData<size_t> markingThreadCount;
1079
1080 // Per-runtime helper thread task queue. Can be accessed from helper threads
1081 // in maybeDispatchParallelTasks().
1082 HelperThreadLockData<size_t> maxParallelThreads;
1083 HelperThreadLockData<size_t> dispatchedParallelTasks;
1084 HelperThreadLockData<GCParallelTaskList> queuedParallelTasks;
1085
1086 // State used for managing atom mark bitmaps in each zone.
1087 AtomMarkingRuntime atomMarking;
1088
1089 /*
1090 * Pointer to a callback that, if set, will be used to create a
1091 * budget for internally-triggered GCs.
1092 */
1093 MainThreadData<JS::CreateSliceBudgetCallback> createBudgetCallback;
1094
1095 private:
1096 // Arenas used for permanent things created at startup and shared by child
1097 // runtimes.
1098 MainThreadData<ArenaList> permanentAtoms;
1099 MainThreadData<ArenaList> permanentWellKnownSymbols;
1100
1101 // When chunks are empty, they reside in the emptyChunks pool and are
1102 // re-used as needed or eventually expired if not re-used. The emptyChunks
1103 // pool gets refilled from the background allocation task heuristically so
1104 // that empty chunks should always be available for immediate allocation
1105 // without syscalls.
1106 GCLockData<ChunkPool> emptyChunks_;
1107
1108 // Chunks which have had some, but not all, of their arenas allocated live
1109 // in the available chunk lists. When all available arenas in a chunk have
1110 // been allocated, the chunk is removed from the available list and moved
1111 // to the fullChunks pool. During a GC, if all arenas are free, the chunk
1112 // is moved back to the emptyChunks pool and scheduled for eventual
1113 // release.
1114 GCLockData<ChunkPool> availableChunks_;
1115
1116 // When all arenas in a chunk are used, it is moved to the fullChunks pool
1117 // so as to reduce the cost of operations on the available lists.
1118 GCLockData<ChunkPool> fullChunks_;
1119
1120 // The chunk currently being allocated from. If non-null this is at the head
1121 // of the available chunks list and has isCurrentChunk set to true. Can be
1122 // accessed without taking the GC lock.
1123 MainThreadData<ArenaChunk*> currentChunk_;
1124
1125 // Bitmap for arenas in the current chunk that have been freed by background
1126 // sweeping but not yet merged into the chunk's freeCommittedArenas.
1127 GCLockData<ChunkArenaBitmap> pendingFreeCommittedArenas;
1128 friend class ArenaChunk;
1129
1130 /*
1131 * JSGC_MIN_EMPTY_CHUNK_COUNT
1132 *
1133 * Controls the number of empty chunks reserved for future allocation.
1134 *
1135 * They can be read off main thread by the background allocation task and the
1136 * background decommit task.
1137 */
1138 GCLockData<uint32_t> minEmptyChunkCount_;
1139
1140 MainThreadData<RootedValueMap> rootsHash;
1141
1142 // An incrementing id used to assign unique ids to cells that require one.
1143 MainThreadData<uint64_t> nextCellUniqueId_;
1144
1145 MainThreadData<VerifyPreTracer*> verifyPreData;
1146
1147 MainThreadData<mozilla::TimeStamp> lastGCStartTime_;
1148 MainThreadData<mozilla::TimeStamp> lastGCEndTime_;
1149
1150 WriteOnceData<bool> initialized;
1151 MainThreadData<bool> incrementalGCEnabled;
1152 MainThreadData<bool> perZoneGCEnabled;
1153
1154 mozilla::Atomic<size_t, mozilla::ReleaseAcquire> numActiveZoneIters;
1155
1156 /*
1157 * The gray bits can become invalid if UnmarkGray overflows the stack. A
1158 * full GC will reset this bit, since it fills in all the gray bits.
1159 */
1160 UnprotectedData<bool> grayBitsValid;
1161
1162 mozilla::Atomic<JS::GCReason, mozilla::ReleaseAcquire> majorGCTriggerReason;
1163
1164 /* Incremented at the start of every minor GC. */
1165 MainThreadData<uint64_t> minorGCNumber;
1166
1167 /* Incremented at the start of every major GC. */
1168 MainThreadData<uint64_t> majorGCNumber;
1169
1170 /* Incremented on every GC slice or minor collection. */
1171 MainThreadData<uint64_t> number;
1172
1173 /* Incremented on every GC slice. */
1174 MainThreadData<uint64_t> sliceNumber;
1175
1176 /*
1177 * This runtime's current contribution to the global number of helper threads
1178 * 'reserved' for parallel marking. Does not affect other uses of helper
1179 * threads.
1180 */
1181 MainThreadData<size_t> reservedMarkingThreads;
1182
1183 /* Whether the currently running GC can finish in multiple slices. */
1184 MainThreadOrGCTaskData<bool> isIncremental;
1185
1186 /* Whether all zones are being collected in first GC slice. */
1187 MainThreadData<bool> isFull;
1188
1189 /* Whether the heap will be compacted at the end of GC. */
1190 MainThreadData<bool> isCompacting;
1191
1192 /* Whether to use parallel marking. */
1193 MainThreadData<ParallelMarking> useParallelMarking;
1194
1195 /* The invocation kind of the current GC, set at the start of collection. */
1196 MainThreadOrGCTaskData<mozilla::Maybe<JS::GCOptions>> maybeGcOptions;
1197
1198 /* The initial GC reason, taken from the first slice. */
1199 MainThreadData<JS::GCReason> initialReason;
1200
1201 /*
1202 * The current incremental GC phase. This is also used internally in
1203 * non-incremental GC.
1204 */
1205 MainThreadOrGCTaskData<State> incrementalState;
1206
1207 /* The incremental state at the start of this slice. */
1208 MainThreadOrGCTaskData<State> initialState;
1209
1210 /* Whether to pay attention the zeal settings in this incremental slice. */
1211 #ifdef JS_GC_ZEAL
1212 MainThreadData<bool> useZeal;
1213 #else
1214 const bool useZeal;
1215 #endif
1216
1217 /* Indicates that the last incremental slice exhausted the mark stack. */
1218 MainThreadData<bool> lastMarkSlice;
1219
1220 // Whether it's currently safe to yield to the mutator in an incremental GC.
1221 MainThreadData<bool> safeToYield;
1222
1223 // Whether to do any marking caused by barriers on a background thread during
1224 // incremental sweeping, while also sweeping zones which have finished
1225 // marking.
1226 MainThreadData<bool> markOnBackgroundThreadDuringSweeping;
1227
1228 // Whether any sweeping and decommitting will run on a separate GC helper
1229 // thread.
1230 MainThreadData<bool> useBackgroundThreads;
1231
1232 #ifdef DEBUG
1233 /* Shutdown has started. Further collections must be shutdown collections. */
1234 MainThreadData<bool> hadShutdownGC;
1235 #endif
1236
1237 /* Singly linked list of zones to be swept in the background. */
1238 HelperThreadLockData<ZoneList> backgroundSweepZones;
1239
1240 /*
1241 * Whether to trigger a GC slice after a background task is complete, so that
1242 * the collector can continue or finsish collecting. This is only used for the
1243 * tasks that run concurrently with the mutator, which are background
1244 * finalization and background decommit.
1245 */
1246 HelperThreadLockData<bool> requestSliceAfterBackgroundTask;
1247
1248 /*
1249 * Free LIFO blocks are transferred to these allocators before being freed on
1250 * a background thread.
1251 */
1252 HelperThreadLockData<LifoAlloc> lifoBlocksToFree;
1253 MainThreadData<LifoAlloc> lifoBlocksToFreeAfterFullMinorGC;
1254 MainThreadData<LifoAlloc> lifoBlocksToFreeAfterNextMinorGC;
1255 HelperThreadLockData<Nursery::BufferSet> buffersToFreeAfterMinorGC;
1256 HelperThreadLockData<Nursery::StringBufferVector>
1257 stringBuffersToReleaseAfterMinorGC;
1258
1259 /* The number of the minor GC peformed at the start of major GC. */
1260 MainThreadData<uint64_t> initialMinorGCNumber;
1261
1262 /* Index of current sweep group (for stats). */
1263 MainThreadData<unsigned> sweepGroupIndex;
1264
1265 /*
1266 * Incremental sweep state.
1267 */
1268 MainThreadData<JS::Zone*> sweepGroups;
1269 MainThreadOrGCTaskData<JS::Zone*> currentSweepGroup;
1270 MainThreadData<UniquePtr<SweepAction>> sweepActions;
1271 MainThreadOrGCTaskData<JS::Zone*> sweepZone;
1272 MainThreadOrGCTaskData<AllocKind> sweepAllocKind;
1273 MainThreadData<mozilla::Maybe<AtomsTable::SweepIterator>> maybeAtomsToSweep;
1274 MainThreadOrGCTaskData<mozilla::Maybe<WeakCacheSweepIterator>>
1275 weakCachesToSweep;
1276 MainThreadData<bool> abortSweepAfterCurrentGroup;
1277 MainThreadOrGCTaskData<IncrementalProgress> sweepMarkResult;
1278
1279 /*
1280 * During incremental foreground finalization, we may have a list of arenas of
1281 * the current AllocKind and Zone whose contents have been finalized but which
1282 * have not yet been merged back into the main arena lists.
1283 */
1284 MainThreadOrGCTaskData<JS::Zone*> foregroundFinalizedZone;
1285 MainThreadOrGCTaskData<AllocKind> foregroundFinalizedAllocKind;
1286 MainThreadData<mozilla::Maybe<SortedArenaList>> foregroundFinalizedArenas;
1287
1288 #ifdef DEBUG
1289 /*
1290 * List of objects to mark at the beginning of a GC for testing purposes. May
1291 * also contain string directives to change mark color or wait until different
1292 * phases of the GC.
1293 *
1294 * This is a WeakCache because not everything in this list is guaranteed to
1295 * end up marked (eg if you insert an object from an already-processed sweep
1296 * group in the middle of an incremental GC). Also, the mark queue is not
1297 * used during shutdown GCs. In either case, unmarked objects may need to be
1298 * discarded.
1299 */
1300 JS::WeakCache<GCVector<HeapPtr<JS::Value>, 0, SystemAllocPolicy>>
1301 testMarkQueue;
1302
1303 /* Position within the test mark queue. */
1304 size_t queuePos = 0;
1305
1306 /* The test marking queue might want to be marking a particular color. */
1307 mozilla::Maybe<js::gc::MarkColor> queueMarkColor;
1308
1309 // During gray marking, delay AssertCellIsNotGray checks by
1310 // recording the cell pointers here and checking after marking has
1311 // finished.
1312 MainThreadData<Vector<const Cell*, 0, SystemAllocPolicy>>
1313 cellsToAssertNotGray;
1314 friend void js::gc::detail::AssertCellIsNotGray(const Cell*);
1315 #endif
1316
1317 friend class SweepGroupsIter;
1318
1319 /*
1320 * Incremental compacting state.
1321 */
1322 MainThreadData<bool> startedCompacting;
1323 MainThreadData<ZoneList> zonesToMaybeCompact;
1324 MainThreadData<size_t> zonesCompacted;
1325 /* Whether we successfully added all edges to the implicit edges table. */
1326 mozilla::Atomic<bool, mozilla::ReleaseAcquire> haveAllImplicitEdges_{false};
1327
1328 #ifdef DEBUG
1329 GCLockData<Arena*> relocatedArenasToRelease;
1330 #endif
1331
1332 #ifdef JS_GC_ZEAL
1333 MainThreadData<MarkingValidator*> markingValidator;
1334 #endif
1335
1336 /*
1337 * Default budget for incremental GC slice. See js/SliceBudget.h.
1338 *
1339 * JSGC_SLICE_TIME_BUDGET_MS
1340 * pref: javascript.options.mem.gc_incremental_slice_ms,
1341 */
1342 MainThreadData<int64_t> defaultTimeBudgetMS_;
1343
1344 /*
1345 * Whether compacting GC is enabled globally.
1346 *
1347 * JSGC_COMPACTING_ENABLED
1348 * pref: javascript.options.mem.gc_compacting
1349 */
1350 MainThreadData<bool> compactingEnabled;
1351
1352 /*
1353 * Whether generational GC is enabled globally.
1354 *
1355 * JSGC_NURSERY_ENABLED
1356 * pref: javascript.options.mem.gc_generational
1357 */
1358 MainThreadData<bool> nurseryEnabled;
1359
1360 /*
1361 * Whether parallel marking is enabled globally.
1362 *
1363 * JSGC_PARALLEL_MARKING_ENABLED
1364 * pref: javascript.options.mem.gc_parallel_marking
1365 */
1366 MainThreadData<bool> parallelMarkingEnabled;
1367
1368 MainThreadData<bool> rootsRemoved;
1369
1370 /*
1371 * These options control the zealousness of the GC. At every allocation,
1372 * nextScheduled is decremented. When it reaches zero we do a full GC.
1373 *
1374 * At this point, if zeal_ is one of the types that trigger periodic
1375 * collection, then nextScheduled is reset to the value of zealFrequency.
1376 * Otherwise, no additional GCs take place.
1377 *
1378 * You can control these values in several ways:
1379 * - Set the JS_GC_ZEAL environment variable
1380 * - Call gczeal() or schedulegc() from inside shell-executed JS code
1381 * (see the help for details)
1382 *
1383 * If gcZeal_ == 1 then we perform GCs in select places (during MaybeGC and
1384 * whenever we are notified that GC roots have been removed). This option is
1385 * mainly useful to embedders.
1386 *
1387 * We use zeal_ == 4 to enable write barrier verification. See the comment
1388 * in gc/Verifier.cpp for more information about this.
1389 *
1390 * zeal_ values from 8 to 10 periodically run different types of
1391 * incremental GC.
1392 *
1393 * zeal_ value 14 performs periodic shrinking collections.
1394 */
1395 #ifdef JS_GC_ZEAL
1396 static_assert(size_t(ZealMode::Count) <= 32,
1397 "Too many zeal modes to store in a uint32_t");
1398 MainThreadData<uint32_t> zealModeBits;
1399 MainThreadData<int> zealFrequency;
1400 MainThreadData<int> nextScheduled;
1401 MainThreadData<bool> deterministicOnly;
1402 MainThreadData<int> zealSliceBudget;
1403 MainThreadData<size_t> maybeMarkStackLimit;
1404
1405 MainThreadData<PersistentRooted<GCVector<JSObject*, 0, SystemAllocPolicy>>>
1406 selectedForMarking;
1407 #endif
1408
1409 MainThreadData<bool> fullCompartmentChecks;
1410
1411 MainThreadData<uint32_t> gcCallbackDepth;
1412
1413 MainThreadData<Callback<JSGCCallback>> gcCallback;
1414 MainThreadData<Callback<JS::DoCycleCollectionCallback>>
1415 gcDoCycleCollectionCallback;
1416 MainThreadData<Callback<JSObjectsTenuredCallback>> tenuredCallback;
1417 MainThreadData<CallbackVector<JSFinalizeCallback>> finalizeCallbacks;
1418 MainThreadOrGCTaskData<Callback<JSHostCleanupFinalizationRegistryCallback>>
1419 hostCleanupFinalizationRegistryCallback;
1420 MainThreadData<CallbackVector<JSWeakPointerZonesCallback>>
1421 updateWeakPointerZonesCallbacks;
1422 MainThreadData<CallbackVector<JSWeakPointerCompartmentCallback>>
1423 updateWeakPointerCompartmentCallbacks;
1424 MainThreadData<CallbackVector<JS::GCNurseryCollectionCallback>>
1425 nurseryCollectionCallbacks;
1426
1427 /*
1428 * The trace operations to trace embedding-specific GC roots. One is for
1429 * tracing through black roots and the other is for tracing through gray
1430 * roots. The black/gray distinction is only relevant to the cycle
1431 * collector.
1432 */
1433 MainThreadData<CallbackVector<JSTraceDataOp>> blackRootTracers;
1434 MainThreadOrGCTaskData<Callback<JSGrayRootsTracer>> grayRootTracer;
1435
1436 /* Always preserve JIT code during GCs, for testing. */
1437 MainThreadData<bool> alwaysPreserveCode;
1438
1439 /* Count of the number of zones that are currently in page load. */
1440 MainThreadData<size_t> inPageLoadCount;
1441
1442 MainThreadData<bool> lowMemoryState;
1443
1444 /*
1445 * General purpose GC lock, used for synchronising operations on
1446 * arenas and during parallel marking.
1447 */
1448 friend class js::AutoLockGC;
1449 friend class js::AutoLockGCBgAlloc;
1450 Mutex lock MOZ_UNANNOTATED;
1451
1452 /*
1453 * Lock used to synchronise access to the store buffer during parallel
1454 * sweeping.
1455 */
1456 Mutex storeBufferLock MOZ_UNANNOTATED;
1457
1458 /* Lock used to synchronise access to delayed marking state. */
1459 Mutex delayedMarkingLock MOZ_UNANNOTATED;
1460
1461 /*
1462 * Lock used by buffer allocators to synchronise data passed back to the main
1463 * thread by background sweeping.
1464 */
1465 Mutex bufferAllocatorLock MOZ_UNANNOTATED;
1466 friend class BufferAllocator;
1467 friend class AutoLock;
1468
1469 friend class BackgroundSweepTask;
1470 friend class BackgroundFreeTask;
1471
1472 BackgroundAllocTask allocTask;
1473 BackgroundUnmarkTask unmarkTask;
1474 BackgroundMarkTask markTask;
1475 BackgroundSweepTask sweepTask;
1476 BackgroundFreeTask freeTask;
1477 BackgroundDecommitTask decommitTask;
1478
1479 MainThreadData<Nursery> nursery_;
1480
1481 // The store buffer used to track tenured to nursery edges for generational
1482 // GC. This is accessed off main thread when sweeping WeakCaches.
1483 MainThreadOrGCTaskData<gc::StoreBuffer> storeBuffer_;
1484
1485 mozilla::TimeStamp lastLastDitchTime;
1486
1487 // The last time per-zone allocation rates were updated.
1488 MainThreadData<mozilla::TimeStamp> lastAllocRateUpdateTime;
1489
1490 // Total collector time since per-zone allocation rates were last updated.
1491 MainThreadData<mozilla::TimeDuration> collectorTimeSinceAllocRateUpdate;
1492
1493 friend class MarkingValidator;
1494 friend class AutoEnterIteration;
1495 };
1496
1497 #ifndef JS_GC_ZEAL
1498 inline bool GCRuntime::hasZealMode(ZealMode mode) const { return false; }
1499 inline void GCRuntime::clearZealMode(ZealMode mode) {}
1500 inline bool GCRuntime::needZealousGC() { return false; }
1501 inline bool GCRuntime::zealModeControlsYieldPoint() const { return false; }
1502 #endif
1503
1504 /* Prevent compartments and zones from being collected during iteration. */
1505 class MOZ_RAII AutoEnterIteration {
1506 GCRuntime* gc;
1507
1508 public:
1509 explicit AutoEnterIteration(GCRuntime* gc_) : gc(gc_) {
1510 ++gc->numActiveZoneIters;
1511 }
1512
1513 ~AutoEnterIteration() {
1514 MOZ_ASSERT(gc->numActiveZoneIters);
1515 --gc->numActiveZoneIters;
1516 }
1517 };
1518
1519 bool IsCurrentlyAnimating(const mozilla::TimeStamp& lastAnimationTime,
1520 const mozilla::TimeStamp& currentTime);
1521
1522 } /* namespace gc */
1523 } /* namespace js */
1524
1525 #endif