Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/js/src/gc/GCRuntime.h
Warning:line 268, column 7
Excessive padding in 'class js::gc::GCRuntime' (84 padding bytes, where 4 is optimal). Optimal fields order: rt, numActiveZoneIters, queuePos, lastLastDitchTime, systemZone, sharedAtomsZone_, delayedMarkingList, markLaterArenas, helperThreadRatio, maxHelperThreads, helperThreadCount, maxMarkingThreads, markingThreadCount, maxParallelThreads, dispatchedParallelTasks, createBudgetCallback, nextCellUniqueId_, verifyPreData, lastGCStartTime_, lastGCEndTime_, initialized, minorGCNumber, majorGCNumber, number, sliceNumber, reservedMarkingThreads, sweepGroups, currentSweepGroup, sweepActions, sweepZone, foregroundFinalizedZone, zonesCompacted, relocatedArenasToRelease, markingValidator, defaultTimeBudgetMS_, maybeMarkStackLimit, inPageLoadCount, lastAllocRateUpdateTime, collectorTimeSinceAllocRateUpdate, permanentAtoms, permanentWellKnownSymbols, emptyChunks_, availableChunks_, fullChunks_, backgroundSweepZones, zonesToMaybeCompact, gcCallback, gcDoCycleCollectionCallback, tenuredCallback, hostCleanupFinalizationRegistryCallback, grayRootTracer, stringStats, heapSize, queuedParallelTasks, weakCachesToSweep, markers, sweepingTracer, rootsHash, buffersToFreeAfterMinorGC, cellsToAssertNotGray, atomMarking, testMarkQueue, mainThreadContext, zones_, selectedForMarking, lock, storeBufferLock, delayedMarkingLock, maybeAtomsToSweep, sweepTask, freeTask, decommitTask, lifoBlocksToFree, lifoBlocksToFreeAfterFullMinorGC, lifoBlocksToFreeAfterNextMinorGC, finalizeCallbacks, updateWeakPointerZonesCallbacks, updateWeakPointerCompartmentCallbacks, nurseryCollectionCallbacks, blackRootTracers, allocTask, markTask, unmarkTask, tunables, storeBuffer_, foregroundFinalizedArenas, nursery_, stats_, schedulingState, numArenasFreeCommitted, majorGCTriggerReason, heapState_, minEmptyChunkCount_, maxEmptyChunkCount_, initialReason, incrementalState, initialState, sweepGroupIndex, sweepMarkResult, zealModeBits, zealFrequency, nextScheduled, zealSliceBudget, gcCallbackDepth, maybeGcOptions, delayedMarkingWorkAdded, fullGCRequested, incrementalGCEnabled, perZoneGCEnabled, cleanUpEverything, grayBitsValid, isIncremental, isFull, isCompacting, useParallelMarking, useZeal, lastMarkSlice, safeToYield, markOnBackgroundThreadDuringSweeping, useBackgroundThreads, haveDiscardedJITCodeThisSlice, hadShutdownGC, requestSliceAfterBackgroundTask, sweepAllocKind, abortSweepAfterCurrentGroup, foregroundFinalizedAllocKind, queueMarkColor, startedCompacting, compactingEnabled, parallelMarkingEnabled, rootsRemoved, deterministicOnly, fullCompartmentChecks, alwaysPreserveCode, lowMemoryState, consider reordering the fields or adding explicit padding members

Annotated Source Code

Press '?' to see keyboard shortcuts

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