Debian Codegraph @

js/src/gc/Sweeping.cpp

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 /*
8 * Implementation of GC sweeping.
9 *
10 * In the SpiderMonkey GC, 'sweeping' is used to mean two things:
11 * - updating data structures to remove pointers to dead GC things and updating
12 * pointers to moved GC things
13 * - finalizing dead GC things
14 *
15 * Furthermore, the GC carries out gray and weak marking after the start of the
16 * sweep phase. This is also implemented in this file.
17 */
18
19 #include "mozilla/DebugOnly.h"
20 #include "mozilla/Maybe.h"
21 #include "mozilla/ScopeExit.h"
22 #include "mozilla/TimeStamp.h"
23
24 #include "builtin/FinalizationRegistryObject.h"
25 #include "builtin/WeakRefObject.h"
26 #include "debugger/DebugAPI.h"
27 #include "gc/AllocKind.h"
28 #include "gc/BufferAllocator.h"
29 #include "gc/FinalizationObservers.h"
30 #include "gc/GCInternals.h"
31 #include "gc/GCLock.h"
32 #include "gc/GCProbes.h"
33 #include "gc/GCRuntime.h"
34 #include "gc/ParallelWork.h"
35 #include "gc/Statistics.h"
36 #include "gc/TraceKind.h"
37 #include "gc/WeakMap.h"
38 #include "gc/Zone.h"
39 #include "jit/JitFrames.h"
40 #include "jit/JitRuntime.h"
41 #include "jit/JitZone.h"
42 #include "proxy/DeadObjectProxy.h"
43 #include "vm/BigIntType.h"
44 #include "vm/HelperThreads.h"
45 #include "vm/JSContext.h"
46 #include "vm/Probes.h"
47 #include "vm/Time.h"
48 #include "vm/WrapperObject.h"
49
50 #include "gc/PrivateIterators-inl.h"
51 #include "vm/GeckoProfiler-inl.h"
52 #include "vm/JSObject-inl.h"
53 #include "vm/PropMap-inl.h"
54 #include "vm/Shape-inl.h"
55 #include "vm/StringType-inl.h"
56
57 using namespace js;
58 using namespace js::gc;
59
60 using mozilla::DebugOnly;
61 using mozilla::TimeStamp;
62
63 using JS::SliceBudget;
64
65 /*
66 * Sweeping of arenas and possible finalization of dead cells proceeds in a
67 * sequence of phases.
68 *
69 * 1. ForegroundObjectFinalizePhase
70 * JSObjects with finalizers. Swept incrementally on the main thread.
71 *
72 * 2. ForegroundNonObjectFinalizePhase
73 * Non-JSObjects with finalizers. Swept incrementally on the main thread.
74 *
75 * 3. BackgroundObjectFinalizePhase
76 * JSObjects with finalizers that can run off main thread. Swept
77 * non-incrementally on a helper thread.
78 *
79 * 4. BackgroundTrivialFinalizePhase
80 * Everything else. These may or may not have finalizers. Any finalizers
81 * must not delete HeapPtrs. Swept non-incrementally on a helper thread.
82 */
83
84 static constexpr AllocKinds ForegroundObjectFinalizePhase = {
85 AllocKind::OBJECT0_FOREGROUND, AllocKind::OBJECT2_FOREGROUND,
86 AllocKind::OBJECT4_FOREGROUND, AllocKind::OBJECT8_FOREGROUND,
87 AllocKind::OBJECT12_FOREGROUND, AllocKind::OBJECT16_FOREGROUND};
88
89 static constexpr AllocKinds ForegroundNonObjectFinalizePhase = {
90 AllocKind::SCRIPT, AllocKind::JITCODE};
91
92 static constexpr AllocKinds BackgroundObjectFinalizePhase = {
93 AllocKind::OBJECT0_BACKGROUND, AllocKind::OBJECT2_BACKGROUND,
94 AllocKind::ARRAYBUFFER4, AllocKind::OBJECT4_BACKGROUND,
95 AllocKind::ARRAYBUFFER8, AllocKind::OBJECT8_BACKGROUND,
96 AllocKind::ARRAYBUFFER12, AllocKind::OBJECT12_BACKGROUND,
97 AllocKind::ARRAYBUFFER16, AllocKind::OBJECT16_BACKGROUND};
98
99 static constexpr AllocKinds BackgroundTrivialFinalizePhase = {
100 AllocKind::FUNCTION,
101 AllocKind::FUNCTION_EXTENDED,
102 AllocKind::OBJECT0,
103 AllocKind::OBJECT2,
104 AllocKind::OBJECT4,
105 AllocKind::OBJECT8,
106 AllocKind::OBJECT12,
107 AllocKind::OBJECT16,
108 AllocKind::BUFFER16,
109 AllocKind::BUFFER32,
110 AllocKind::BUFFER64,
111 AllocKind::BUFFER128,
112 AllocKind::SCOPE,
113 AllocKind::REGEXP_SHARED,
114 AllocKind::FAT_INLINE_STRING,
115 AllocKind::STRING,
116 AllocKind::EXTERNAL_STRING,
117 AllocKind::FAT_INLINE_ATOM,
118 AllocKind::ATOM,
119 AllocKind::SYMBOL,
120 AllocKind::BIGINT,
121 AllocKind::SHAPE,
122 AllocKind::BASE_SHAPE,
123 AllocKind::GETTER_SETTER,
124 AllocKind::COMPACT_PROP_MAP,
125 AllocKind::NORMAL_PROP_MAP,
126 AllocKind::DICT_PROP_MAP};
127
128 static constexpr AllocKinds AllBackgroundSweptKinds =
129 BackgroundObjectFinalizePhase + BackgroundTrivialFinalizePhase;
130
131 static constexpr size_t ArenaReleaseBatchSize = 32;
132
133 template <typename T, FinalizeKind finalizeKind>
134 inline size_t Arena::finalize(JS::GCContext* gcx, AllocKind thingKind,
135 size_t thingSize) {
136 /* Enforce requirements on size of T. */
137 MOZ_ASSERT(thingSize % CellAlignBytes == 0);
138 MOZ_ASSERT(thingSize >= MinCellSize);
139 MOZ_ASSERT(thingSize <= 255);
140
141 MOZ_ASSERT(allocated());
142 MOZ_ASSERT(thingKind == getAllocKind());
143 MOZ_ASSERT(thingSize == getThingSize());
144 MOZ_ASSERT(!onDelayedMarkingList_);
145
146 MOZ_ASSERT(finalizeKind == GetFinalizeKind(thingKind));
147
148 uint_fast16_t freeStart = firstThingOffset(thingKind);
149
150 // Update the free list as we go along. The cell iterator will always be ahead
151 // of this pointer when it is written through, so the write will not interfere
152 // with the iteration.
153 FreeSpan* newListTail = &firstFreeSpan;
154
155 size_t nmarked = 0;
156 size_t nfinalized = 0;
157
158 for (ArenaCellIterUnderFinalize cell(this); !cell.done(); cell.next()) {
159 T* t = cell.as<T>();
160 if (TenuredThingIsMarkedAny(t)) {
161 uint_fast16_t thing = uintptr_t(t) & ArenaMask;
162 if (thing != freeStart) {
163 // We just finished passing over one or more free things,
164 // so record a new FreeSpan.
165 newListTail->initBounds(freeStart, thing - thingSize, this);
166 newListTail = newListTail->nextSpanUnchecked(this);
167 }
168 freeStart = thing + thingSize;
169 nmarked++;
170 } else {
171 if constexpr (std::is_same_v<T, JSObject>) {
172 js::probes::FinalizeObject(t);
173 }
174 if constexpr (finalizeKind != FinalizeKind::None) {
175 t->finalize(gcx);
176 }
177 AlwaysPoison(t, JS_SWEPT_TENURED_PATTERN, thingSize,
178 MemCheckKind::MakeUndefined);
179 gcprobes::TenuredFinalize(t);
180 nfinalized++;
181 }
182 }
183
184 if constexpr (std::is_same_v<T, JSObject> || std::is_same_v<T, JSString> ||
185 std::is_same_v<T, JS::BigInt>) {
186 if (isNewlyCreated_) {
187 zone()->pretenuring.updateCellCountsInNewlyCreatedArenas(
188 nmarked + nfinalized, nmarked);
189 }
190 }
191 isNewlyCreated_ = 0;
192
193 if (freeStart == ArenaSize) {
194 // If the last thing was marked, we will have already set the bounds of
195 // the final span, and we just need to terminate the list.
196 newListTail->initAsEmpty();
197 } else {
198 // Otherwise, end the list with a span that covers the final stretch of free
199 // things.
200 newListTail->initFinal(freeStart, ArenaSize - thingSize, this);
201 }
202
203 #ifdef DEBUG
204 size_t nfree = numFreeThings(thingSize);
205 MOZ_ASSERT(nfree + nmarked == thingsPerArena(thingKind));
206 #endif
207
208 return nmarked;
209 }
210
211 // Finalize arenas from src list, releasing empty arenas if keepArenas wasn't
212 // specified and inserting the others into the appropriate destination size
213 // bins.
214 template <typename T, FinalizeKind finalizeKind, ReleaseEmpty releaseEmpty>
215 static inline bool FinalizeTypedArenas(JS::GCContext* gcx, ArenaList& src,
216 SortedArenaList& dest,
217 AllocKind thingKind,
218 SliceBudget& budget) {
219 MOZ_ASSERT(gcx->isFinalizing());
220
221 size_t thingSize = Arena::thingSize(thingKind);
222 size_t thingsPerArena = Arena::thingsPerArena(thingKind);
223 size_t markCount = 0;
224 size_t emptyCount = 0;
225
226 GCRuntime* gc = &gcx->runtimeFromAnyThread()->gc;
227 auto updateMarkCount = mozilla::MakeScopeExit(
228 [&] { gc->stats().addCount(gcstats::COUNT_CELLS_MARKED, markCount); });
229
230 while (!src.isEmpty()) {
231 Arena* arena = src.popFront();
232 size_t nmarked =
233 arena->finalize<T, finalizeKind>(gcx, thingKind, thingSize);
234 size_t nfree = thingsPerArena - nmarked;
235
236 markCount += nmarked;
237
238 dest.insertAt(arena, nfree);
239
240 if constexpr (bool(releaseEmpty)) {
241 if (nmarked == 0) {
242 emptyCount++;
243 MOZ_ASSERT(emptyCount <= ArenaReleaseBatchSize);
244 if (emptyCount == ArenaReleaseBatchSize) {
245 Arena* emptyArenas = nullptr;
246 dest.extractEmptyTo(&emptyArenas);
247 emptyArenas =
248 gc->releaseSomeEmptyArenas(emptyArenas->zone(), emptyArenas);
249 MOZ_ASSERT(!emptyArenas);
250 emptyCount = 0;
251 }
252 }
253 }
254
255 budget.step(thingsPerArena);
256 if (budget.isOverBudget()) {
257 return false;
258 }
259 }
260
261 if constexpr (bool(releaseEmpty)) {
262 if (emptyCount) {
263 Arena* emptyArenas = nullptr;
264 dest.extractEmptyTo(&emptyArenas);
265 emptyArenas =
266 gc->releaseSomeEmptyArenas(emptyArenas->zone(), emptyArenas);
267 MOZ_ASSERT(!emptyArenas);
268 }
269 }
270
271 return true;
272 }
273
274 /*
275 * Finalize the list of areans.
276 */
277 template <ReleaseEmpty releaseEmpty>
278 static bool FinalizeArenas(JS::GCContext* gcx, ArenaList& src,
279 SortedArenaList& dest, AllocKind thingKind,
280 SliceBudget& budget) {
281 switch (thingKind) {
282 #define EXPAND_CASE(allocKind, _1, type, _2, finalizeKind, _3, _4) \
283 case AllocKind::allocKind: \
284 return FinalizeTypedArenas<type, FinalizeKind::finalizeKind, \
285 releaseEmpty>(gcx, src, dest, thingKind, \
286 budget);
287 FOR_EACH_ALLOCKIND(EXPAND_CASE)
288 #undef EXPAND_CASE
289
290 default:
291 MOZ_CRASH("Invalid alloc kind");
292 }
293 }
294
295 void GCRuntime::initBackgroundSweep(Zone* zone, JS::GCContext* gcx,
296 const AllocKinds& kinds) {
297 for (AllocKind kind : kinds) {
298 zone->arenas.initBackgroundSweep(kind);
299 }
300 }
301
302 void ArenaLists::initBackgroundSweep(AllocKind thingKind) {
303 MOZ_ASSERT(IsBackgroundSwept(thingKind));
304 MOZ_ASSERT(concurrentUse(thingKind) == ConcurrentUse::None);
305
306 if (!collectingArenaList(thingKind).isEmpty()) {
307 concurrentUse(thingKind) = ConcurrentUse::BackgroundFinalize;
308 }
309 }
310
311 template <ReleaseEmpty releaseEmpty>
312 void ArenaLists::backgroundFinalize(JS::GCContext* gcx, AllocKind kind,
313 Arena** empty) {
314 MOZ_ASSERT(IsBackgroundSwept(kind));
315 MOZ_ASSERT(bool(empty) != bool(releaseEmpty));
316
317 ArenaList& arenas = collectingArenaList(kind);
318 if (arenas.isEmpty()) {
319 MOZ_ASSERT(concurrentUse(kind) == ConcurrentUse::None);
320 return;
321 }
322 MOZ_ASSERT(concurrentUse(kind) == ConcurrentUse::BackgroundFinalize);
323
324 SortedArenaList finalizedSorted(kind);
325
326 auto unlimited = SliceBudget::unlimited();
327 FinalizeArenas<releaseEmpty>(gcx, arenas, finalizedSorted, kind, unlimited);
328 MOZ_ASSERT(arenas.isEmpty());
329
330 if constexpr (!bool(releaseEmpty)) {
331 finalizedSorted.extractEmptyTo(empty);
332 }
333 MOZ_ASSERT(!finalizedSorted.hasEmptyArenas());
334
335 // Set the collectingArenaList to the possibly empty list of swept arenas
336 // while holding the GC lock. Set concurrentUse to indicate to the main thread
337 // that sweeping has finished.
338 ArenaList sweptArenas = finalizedSorted.convertToArenaList();
339
340 AutoLockGC lock(gcx->runtimeFromAnyThread());
341 collectingArenaList(kind) = std::move(sweptArenas);
342 concurrentUse(kind) = ConcurrentUse::BackgroundFinalizeFinished;
343 }
344
345 void ArenaLists::mergeBackgroundSweptArenas() {
346 // Merge swept arenas into main arena lists on the main thread.
347 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
348
349 for (AllocKind kind : AllBackgroundSweptKinds) {
350 maybeMergeSweptArenas(kind);
351 }
352 }
353
354 void ArenaLists::maybeMergeSweptArenas(AllocKind kind) {
355 MOZ_ASSERT(zone_->isGCFinished());
356 MOZ_ASSERT(concurrentUse(kind) != ConcurrentUse::BackgroundFinalize);
357
358 if (concurrentUse(kind) == ConcurrentUse::BackgroundFinalizeFinished) {
359 concurrentUse(kind) = ConcurrentUse::None;
360 mergeSweptArenas(kind, collectingArenaList(kind));
361 }
362
363 MOZ_ASSERT(collectingArenaList(kind).isEmpty());
364 }
365
366 // This methods merges the following to get the final state of an arena
367 // list:
368 // - swept arenas
369 // - arenas allocated during marking
370 // - arenas allocated during sweeping
371 void ArenaLists::mergeSweptArenas(AllocKind kind, ArenaList& sweptArenas) {
372 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
373 MOZ_ASSERT(concurrentUse(kind) == ConcurrentUse::None);
374
375 arenaList(kind).prepend(std::move(sweptArenas));
376 }
377
378 void ArenaLists::queueForegroundThingsForSweep() {
379 gcCompactPropMapArenasToUpdate =
380 collectingArenaList(AllocKind::COMPACT_PROP_MAP).first();
381 gcNormalPropMapArenasToUpdate =
382 collectingArenaList(AllocKind::NORMAL_PROP_MAP).first();
383 }
384
385 void GCRuntime::sweepBackgroundThings(ZoneList& zones) {
386 if (zones.isEmpty()) {
387 return;
388 }
389
390 JS::GCContext* gcx = TlsGCContext.get();
391 MOZ_ASSERT(gcx->isFinalizing());
392
393 // Sweep zones in order. The atoms zone must be finalized last as other
394 // zones may have direct pointers into it.
395 while (!zones.isEmpty()) {
396 Zone* zone = zones.removeFront();
397 MOZ_ASSERT(zone->isGCFinished());
398
399 TimeStamp startTime = TimeStamp::Now();
400
401 ArenaLists& arenaLists = zone->arenas;
402 Arena* emptyArenas = arenaLists.takeSweptEmptyArenas();
403
404 // We must finalize kinds in the order specified at the top of this file.
405
406 for (auto kind : BackgroundObjectFinalizePhase) {
407 MOZ_ASSERT(IsBackgroundFinalized(kind));
408 arenaLists.backgroundFinalize<ReleaseEmpty::No>(gcx, kind, &emptyArenas);
409 }
410
411 // Release any arenas that are now empty.
412 //
413 // Finalizers can still access the zone pointer in now-empty arenas because
414 // of the write barrier in the HeapPtr destructor. This means we can't
415 // release any empty arenas until all such finalizers have been run.
416 //
417 // At this point this has happened and we can release empty arenas
418 // immediately from now on.
419
420 AutoDisallowPreWriteBarrier disallowBarrier(gcx);
421
422 while (emptyArenas) {
423 emptyArenas = releaseSomeEmptyArenas(zone, emptyArenas);
424 }
425
426 // Now everything with a non-trivial finalizer has been finalized we can
427 // sweep buffer memory.
428 //
429 // Note we depend on this happening before the BUFFER alloc kinds in
430 // BackgroundTrivialFinalizePhase are swept!
431 bool decommit = shouldDecommit() && DecommitEnabled();
432 zone->bufferAllocator.sweepForMajorCollection(decommit);
433
434 // TODO: The remaining sweeping work can be parallelised between multiple
435 // threads.
436 for (AllocKind kind : BackgroundTrivialFinalizePhase) {
437 MOZ_ASSERT(IsBackgroundSwept(kind));
438 arenaLists.backgroundFinalize<ReleaseEmpty::Yes>(gcx, kind);
439 }
440
441 // Record time spent sweeping this zone.
442 TimeStamp endTime = TimeStamp::Now();
443 zone->perZoneGCTime += endTime - startTime;
444 }
445 }
446
447 Arena* GCRuntime::releaseSomeEmptyArenas(Zone* zone, Arena* emptyArenas) {
448 // Batch releases so as to periodically drop and reaquire the GC lock to
449 // avoid blocking the main thread from allocating arenas. This is important
450 // for allocation-heavy workloads such as the splay benchmark.
451 //
452 // This block is equivalent to calling GCRuntime::releaseArena on each arena
453 // individually.
454 bool isAtomsZone = zone->isAtomsZone();
455
456 Arena* arenasToRelease[ArenaReleaseBatchSize];
457 size_t atomsBitmapIndexes[ArenaReleaseBatchSize];
458 size_t count = 0;
459
460 size_t gcHeapBytesFreed = 0;
461 size_t mallocHeapBytesFreed = 0;
462
463 // Take up to ArenaReleaseBatchSize arenas from emptyArenas list.
464 for (size_t i = 0; emptyArenas && i < ArenaReleaseBatchSize; i++) {
465 Arena* arena = emptyArenas;
466 emptyArenas = arena->next;
467
468 if (IsBufferAllocKind(arena->getAllocKind())) {
469 mallocHeapBytesFreed += ArenaSize - arena->getFirstThingOffset();
470 } else {
471 gcHeapBytesFreed += ArenaSize;
472 }
473
474 if (isAtomsZone) {
475 atomsBitmapIndexes[i] = arena->atomBitmapStart();
476 #ifdef DEBUG
477 arena->atomBitmapStart() = 0;
478 #endif
479 }
480
481 arena->release();
482 arenasToRelease[i] = arena;
483 count++;
484 }
485
486 zone->mallocHeapSize.removeBytes(mallocHeapBytesFreed, true);
487 zone->gcHeapSize.removeBytes(gcHeapBytesFreed, true, heapSize);
488
489 AutoLockGC lock(this);
490 for (size_t i = 0; i < count; i++) {
491 Arena* arena = arenasToRelease[i];
492 if (isAtomsZone) {
493 atomMarking.freeIndex(atomsBitmapIndexes[i], lock);
494 }
495 arena->chunk()->releaseArena(this, arena, lock);
496 }
497
498 return emptyArenas;
499 }
500
501 void GCRuntime::assertBackgroundSweepingFinished() {
502 #ifdef DEBUG
503 {
504 AutoLockHelperThreadState lock;
505 MOZ_ASSERT(backgroundSweepZones.ref().isEmpty());
506 }
507
508 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
509 for (auto kind : AllAllocKinds()) {
510 MOZ_ASSERT_IF(state() == State::NotActive || state() >= State::Compact,
511 zone->arenas.collectingArenaList(kind).isEmpty());
512 MOZ_ASSERT(zone->arenas.doneBackgroundFinalize(kind));
513 }
514 }
515 #endif
516 }
517
518 void GCRuntime::queueZonesAndStartBackgroundSweep(ZoneList&& zones) {
519 {
520 AutoLockHelperThreadState lock;
521 MOZ_ASSERT(!requestSliceAfterBackgroundTask);
522 backgroundSweepZones.ref().appendList(std::move(zones));
523 if (useBackgroundThreads) {
524 sweepTask.startOrRunIfIdle(lock);
525 }
526 }
527 if (!useBackgroundThreads) {
528 sweepTask.join();
529 sweepTask.runFromMainThread();
530 }
531 }
532
533 BackgroundSweepTask::BackgroundSweepTask(GCRuntime* gc)
534 : GCParallelTask(gc, gcstats::PhaseKind::SWEEP, GCUse::Finalizing) {}
535
536 void BackgroundSweepTask::run(AutoLockHelperThreadState& lock) {
537 gc->sweepFromBackgroundThread(lock);
538 }
539
540 void GCRuntime::sweepFromBackgroundThread(AutoLockHelperThreadState& lock) {
541 do {
542 ZoneList zones;
543 zones.appendList(std::move(backgroundSweepZones.ref()));
544
545 AutoUnlockHelperThreadState unlock(lock);
546 sweepBackgroundThings(zones);
547
548 // The main thread may call queueZonesAndStartBackgroundSweep() while this
549 // is running so we must check there is no more work after releasing the
550 // lock.
551 } while (!backgroundSweepZones.ref().isEmpty());
552
553 maybeRequestGCAfterBackgroundTask(lock);
554 }
555
556 void GCRuntime::waitBackgroundSweepEnd() {
557 sweepTask.join();
558 for (AllZonesIter zone(this); !zone.done(); zone.next()) {
559 if (zone->isGCFinished()) {
560 zone->arenas.mergeBackgroundSweptArenas();
561 }
562 }
563 if (state() != State::Sweep) {
564 assertBackgroundSweepingFinished();
565 }
566 }
567
568 void GCRuntime::waitBackgroundDecommitEnd() { decommitTask.join(); }
569
570 void GCRuntime::startBackgroundFree() {
571 AutoLockHelperThreadState lock;
572
573 if (!hasBuffersForBackgroundFree()) {
574 return;
575 }
576
577 freeTask.startOrRunIfIdle(lock);
578 }
579
580 BackgroundFreeTask::BackgroundFreeTask(GCRuntime* gc)
581 : GCParallelTask(gc, gcstats::PhaseKind::NONE) {
582 // This can occur outside GCs so doesn't have a stats phase.
583 }
584
585 void BackgroundFreeTask::run(AutoLockHelperThreadState& lock) {
586 gc->freeFromBackgroundThread(lock);
587 }
588
589 void GCRuntime::freeFromBackgroundThread(AutoLockHelperThreadState& lock) {
590 do {
591 LifoAlloc lifoBlocks(JSContext::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE,
592 js::BackgroundMallocArena);
593 lifoBlocks.transferFrom(&lifoBlocksToFree.ref());
594
595 Nursery::BufferSet buffers;
596 std::swap(buffers, buffersToFreeAfterMinorGC.ref());
597
598 Nursery::StringBufferVector stringBuffers;
599 std::swap(stringBuffers, stringBuffersToReleaseAfterMinorGC.ref());
600
601 AutoUnlockHelperThreadState unlock(lock);
602
603 lifoBlocks.freeAll();
604
605 JS::GCContext* gcx = TlsGCContext.get();
606 for (Nursery::BufferSet::Range r = buffers.all(); !r.empty();
607 r.popFront()) {
608 // Malloc memory associated with nursery objects is not tracked as these
609 // are assumed to be short lived.
610 gcx->freeUntracked(r.front());
611 }
612
613 for (auto* buffer : stringBuffers) {
614 buffer->Release();
615 }
616 } while (hasBuffersForBackgroundFree());
617 }
618
619 void GCRuntime::waitBackgroundFreeEnd() { freeTask.join(); }
620
621 template <class ZoneIterT>
622 IncrementalProgress GCRuntime::markWeakReferences(
623 SliceBudget& incrementalBudget) {
624 MOZ_ASSERT(!marker().isWeakMarking());
625
626 gcstats::AutoPhase ap1(stats(), gcstats::PhaseKind::MARK_WEAK);
627
628 auto unlimited = SliceBudget::unlimited();
629 SliceBudget& budget =
630 marker().incrementalWeakMapMarkingEnabled ? incrementalBudget : unlimited;
631
632 // Ensure we don't return to the mutator while we're still in weak marking
633 // mode.
634 auto leaveOnExit =
635 mozilla::MakeScopeExit([&] { marker().leaveWeakMarkingMode(); });
636
637 if (marker().enterWeakMarkingMode()) {
638 // If there was an 'enter-weak-marking-mode' token in the queue, then it
639 // and everything after it will still be in the queue so we can process
640 // them now.
641 while (processTestMarkQueue() == QueueYielded) {
642 };
643
644 // Do not rely on the information about not-yet-marked weak keys that have
645 // been collected by barriers. Clear out the gcEphemeronEdges entries and
646 // rebuild the full table. Note that this a cross-zone operation; delegate
647 // zone entries will be populated by map zone traversals, so everything
648 // needs to be cleared first, then populated.
649 if (!marker().incrementalWeakMapMarkingEnabled) {
650 for (ZoneIterT zone(this); !zone.done(); zone.next()) {
651 zone->gcEphemeronEdges().clearAndCompact();
652 }
653 }
654
655 for (ZoneIterT zone(this); !zone.done(); zone.next()) {
656 if (zone->enterWeakMarkingMode(&marker(), budget) == NotFinished) {
657 return NotFinished;
658 }
659 }
660 }
661
662 bool markedAny = true;
663 while (markedAny) {
664 if (!marker().markUntilBudgetExhausted(budget)) {
665 MOZ_ASSERT(marker().incrementalWeakMapMarkingEnabled);
666 return NotFinished;
667 }
668
669 markedAny = false;
670
671 if (!marker().isWeakMarking()) {
672 for (ZoneIterT zone(this); !zone.done(); zone.next()) {
673 markedAny |= WeakMapBase::markZoneIteratively(zone, &marker());
674 }
675 }
676
677 markedAny |= jit::JitRuntime::MarkJitcodeGlobalTableIteratively(&marker());
678 }
679
680 assertNoMarkingWork();
681
682 return Finished;
683 }
684
685 IncrementalProgress GCRuntime::markWeakReferencesInCurrentGroup(
686 SliceBudget& budget) {
687 return markWeakReferences<SweepGroupZonesIter>(budget);
688 }
689
690 IncrementalProgress GCRuntime::markGrayRoots(SliceBudget& budget,
691 gcstats::PhaseKind phase) {
692 MOZ_ASSERT(marker().markColor() == MarkColor::Black);
693
694 gcstats::AutoPhase ap(stats(), phase);
695
696 {
697 AutoSetMarkColor setColorGray(marker(), MarkColor::Gray);
698
699 AutoUpdateLiveCompartments updateLive(this);
700 marker().setRootMarkingMode(true);
701 auto guard = mozilla::MakeScopeExit(
702 [this]() { marker().setRootMarkingMode(false); });
703
704 IncrementalProgress result =
705 traceEmbeddingGrayRoots(marker().tracer(), budget);
706 if (result == NotFinished) {
707 return NotFinished;
708 }
709
710 Compartment::traceIncomingCrossCompartmentEdgesForZoneGC(
711 marker().tracer(), Compartment::GrayEdges);
712 }
713
714 // Also mark any incoming cross compartment edges that were originally gray
715 // but have been marked black by a barrier.
716 Compartment::traceIncomingCrossCompartmentEdgesForZoneGC(
717 marker().tracer(), Compartment::BlackEdges);
718
719 return Finished;
720 }
721
722 IncrementalProgress GCRuntime::markAllWeakReferences() {
723 SliceBudget budget = SliceBudget::unlimited();
724 return markWeakReferences<GCZonesIter>(budget);
725 }
726
727 void GCRuntime::markAllGrayReferences(gcstats::PhaseKind phase) {
728 #ifdef DEBUG
729 // Check zones are in the correct state to be marked.
730 for (GCZonesIter zone(this); !zone.done(); zone.next()) {
731 MOZ_ASSERT(zone->isGCMarkingBlackAndGray());
732 }
733 #endif
734
735 SliceBudget budget = SliceBudget::unlimited();
736 markGrayRoots(budget, phase);
737 drainMarkStack();
738 }
739
740 void GCRuntime::dropStringWrappers() {
741 /*
742 * String "wrappers" are dropped on GC because their presence would require
743 * us to sweep the wrappers in all compartments every time we sweep a
744 * compartment group.
745 */
746 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
747 zone->dropStringWrappersOnGC();
748 }
749 }
750
751 /*
752 * Group zones that must be swept at the same time.
753 *
754 * From the point of view of the mutator, groups of zones transition atomically
755 * from marking to sweeping. If compartment A has an edge to an unmarked object
756 * in compartment B, then we must not start sweeping A in a later slice than we
757 * start sweeping B. That's because a write barrier in A could lead to the
758 * unmarked object in B becoming marked. However, if we had already swept that
759 * object, we would be in trouble.
760 *
761 * If we consider these dependencies as a graph, then all the compartments in
762 * any strongly-connected component of this graph must start sweeping in the
763 * same slice.
764 *
765 * Tarjan's algorithm is used to calculate the components.
766 */
767
768 bool Compartment::findSweepGroupEdges() {
769 Zone* source = zone();
770 for (WrappedObjectCompartmentEnum e(this); !e.empty(); e.popFront()) {
771 Compartment* targetComp = e.front();
772 Zone* target = targetComp->zone();
773
774 if (!target->isGCMarking() || source->hasSweepGroupEdgeTo(target)) {
775 continue;
776 }
777
778 for (ObjectWrapperEnum e(this, targetComp); !e.empty(); e.popFront()) {
779 JSObject* key = e.front().mutableKey();
780 MOZ_ASSERT(key->zone() == target);
781
782 // Add an edge to the wrapped object's zone to ensure that the wrapper
783 // zone is not still being marked when we start sweeping the wrapped zone.
784 // As an optimization, if the wrapped object is already marked black there
785 // is no danger of later marking and we can skip this.
786 if (key->isMarkedBlack()) {
787 continue;
788 }
789
790 if (!source->addSweepGroupEdgeTo(target)) {
791 return false;
792 }
793
794 // We don't need to consider any more wrappers for this target
795 // compartment since we already added an edge.
796 break;
797 }
798 }
799
800 return true;
801 }
802
803 bool Zone::findSweepGroupEdges(Zone* atomsZone) {
804 MOZ_ASSERT_IF(this != atomsZone, !isAtomsZone());
805
806 #ifdef DEBUG
807 if (FinalizationObservers* observers = finalizationObservers()) {
808 observers->checkTables();
809 }
810 #endif
811
812 // Any zone may have a pointer to an atom in the atoms zone, and these aren't
813 // in the cross compartment map.
814 if (atomsZone->wasGCStarted() && !addSweepGroupEdgeTo(atomsZone)) {
815 return false;
816 }
817
818 for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
819 if (!comp->findSweepGroupEdges()) {
820 return false;
821 }
822 }
823
824 return WeakMapBase::findSweepGroupEdgesForZone(atomsZone, this);
825 }
826
827 bool GCRuntime::addEdgesForMarkQueue() {
828 #ifdef DEBUG
829 // For testing only.
830 //
831 // Add edges between all objects mentioned in the test mark queue, since
832 // otherwise they will get marked in a different order than their sweep
833 // groups. Note that this is only done at the beginning of an incremental
834 // collection, so it is possible for objects to be added later that do not
835 // follow the sweep group ordering. These objects will wait until their sweep
836 // group comes up, or will be skipped if their sweep group is already past.
837 JS::Zone* prevZone = nullptr;
838 for (Value val : testMarkQueue) {
839 if (!val.isObject()) {
840 continue;
841 }
842 JSObject* obj = &val.toObject();
843 JS::Zone* zone = obj->zone();
844 if (!zone->isGCMarking()) {
845 continue;
846 }
847 if (prevZone && prevZone != zone) {
848 if (!prevZone->addSweepGroupEdgeTo(zone)) {
849 return false;
850 }
851 }
852 prevZone = zone;
853 }
854 #endif
855 return true;
856 }
857
858 bool GCRuntime::findSweepGroupEdges() {
859 for (GCZonesIter zone(this); !zone.done(); zone.next()) {
860 if (!zone->findSweepGroupEdges(atomsZone())) {
861 return false;
862 }
863 }
864
865 if (!addEdgesForMarkQueue()) {
866 return false;
867 }
868
869 return DebugAPI::findSweepGroupEdges(rt);
870 }
871
872 void GCRuntime::groupZonesForSweeping(JS::GCReason reason) {
873 #ifdef DEBUG
874 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
875 MOZ_ASSERT(zone->gcSweepGroupEdges().empty());
876 }
877 #endif
878
879 JSContext* cx = rt->mainContextFromOwnThread();
880 ZoneComponentFinder finder(cx);
881 if (!isIncremental || !findSweepGroupEdges()) {
882 finder.useOneComponent();
883 }
884
885 // Use one component for zeal modes that yield at specific points.
886 if (useZeal && zealModeControlsYieldPoint()) {
887 finder.useOneComponent();
888 }
889
890 for (GCZonesIter zone(this); !zone.done(); zone.next()) {
891 MOZ_ASSERT(zone->isGCMarking());
892 finder.addNode(zone);
893 }
894 sweepGroups = finder.getResultsList();
895 currentSweepGroup = sweepGroups;
896 sweepGroupIndex = 1;
897
898 for (GCZonesIter zone(this); !zone.done(); zone.next()) {
899 zone->clearSweepGroupEdges();
900 }
901
902 #ifdef DEBUG
903 unsigned idx = sweepGroupIndex;
904 for (Zone* head = currentSweepGroup; head; head = head->nextGroup()) {
905 for (Zone* zone = head; zone; zone = zone->nextNodeInGroup()) {
906 MOZ_ASSERT(zone->isGCMarking());
907 zone->gcSweepGroupIndex = idx;
908 }
909 idx++;
910 }
911
912 MOZ_ASSERT_IF(!isIncremental, !currentSweepGroup->nextGroup());
913 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
914 MOZ_ASSERT(zone->gcSweepGroupEdges().empty());
915 }
916 #endif
917 }
918
919 void GCRuntime::moveToNextSweepGroup() {
920 currentSweepGroup = currentSweepGroup->nextGroup();
921 ++sweepGroupIndex;
922 if (!currentSweepGroup) {
923 abortSweepAfterCurrentGroup = false;
924 return;
925 }
926
927 MOZ_ASSERT_IF(abortSweepAfterCurrentGroup, !isIncremental);
928 if (!isIncremental) {
929 ZoneComponentFinder::mergeGroups(currentSweepGroup);
930 }
931
932 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
933 MOZ_ASSERT(zone->gcState() == zone->initialMarkingState());
934 MOZ_ASSERT(!zone->isQueuedForBackgroundSweep());
935 }
936
937 if (abortSweepAfterCurrentGroup) {
938 markTask.join();
939
940 // Abort collection of subsequent sweep groups.
941 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
942 MOZ_ASSERT(!zone->gcNextGraphComponent);
943 zone->changeGCState(zone->initialMarkingState(), Zone::Finished);
944 zone->arenas.unmarkPreMarkedFreeCells();
945 zone->arenas.mergeArenasFromCollectingLists();
946 zone->clearGCSliceThresholds();
947 }
948
949 for (SweepGroupCompartmentsIter comp(rt); !comp.done(); comp.next()) {
950 resetGrayList(comp);
951 }
952
953 abortSweepAfterCurrentGroup = false;
954 currentSweepGroup = nullptr;
955 }
956 }
957
958 /*
959 * Gray marking:
960 *
961 * At the end of collection, anything reachable from a gray root that has not
962 * otherwise been marked black must be marked gray.
963 *
964 * This means that when marking things gray we must not allow marking to leave
965 * the current compartment group, as that could result in things being marked
966 * gray when they might subsequently be marked black. To achieve this, when we
967 * find a cross compartment pointer we don't mark the referent but add it to a
968 * singly-linked list of incoming gray pointers that is stored with each
969 * compartment.
970 *
971 * The list head is stored in Compartment::gcIncomingGrayPointers and contains
972 * cross compartment wrapper objects. The next pointer is stored in the second
973 * extra slot of the cross compartment wrapper.
974 *
975 * The list is created during gray marking when one of the
976 * MarkCrossCompartmentXXX functions is called for a pointer that leaves the
977 * current compartent group. This calls DelayCrossCompartmentGrayMarking to
978 * push the referring object onto the list.
979 *
980 * The list is traversed and then unlinked in
981 * GCRuntime::markIncomingGrayCrossCompartmentPointers.
982 */
983
984 static bool IsGrayListObject(JSObject* obj) {
985 MOZ_ASSERT(obj);
986 return obj->is<CrossCompartmentWrapperObject>() && !IsDeadProxyObject(obj);
987 }
988
989 /* static */
990 unsigned ProxyObject::grayLinkReservedSlot(JSObject* obj) {
991 MOZ_ASSERT(IsGrayListObject(obj));
992 return CrossCompartmentWrapperObject::GrayLinkReservedSlot;
993 }
994
995 #ifdef DEBUG
996 static void AssertNotOnGrayList(JSObject* obj) {
997 MOZ_ASSERT_IF(
998 IsGrayListObject(obj),
999 GetProxyReservedSlot(obj, ProxyObject::grayLinkReservedSlot(obj))
1000 .isUndefined());
1001 }
1002 #endif
1003
1004 static void AssertNoWrappersInGrayList(JSRuntime* rt) {
1005 #ifdef DEBUG
1006 for (CompartmentsIter c(rt); !c.done(); c.next()) {
1007 MOZ_ASSERT(!c->gcIncomingGrayPointers);
1008 for (Compartment::ObjectWrapperEnum e(c); !e.empty(); e.popFront()) {
1009 AssertNotOnGrayList(e.front().value().unbarrieredGet());
1010 }
1011 }
1012 #endif
1013 }
1014
1015 static JSObject* CrossCompartmentPointerReferent(JSObject* obj) {
1016 MOZ_ASSERT(IsGrayListObject(obj));
1017 return &obj->as<ProxyObject>().private_().toObject();
1018 }
1019
1020 static JSObject* NextIncomingCrossCompartmentPointer(JSObject* prev,
1021 bool unlink) {
1022 unsigned slot = ProxyObject::grayLinkReservedSlot(prev);
1023 JSObject* next = GetProxyReservedSlot(prev, slot).toObjectOrNull();
1024 MOZ_ASSERT_IF(next, IsGrayListObject(next));
1025
1026 if (unlink) {
1027 SetProxyReservedSlot(prev, slot, UndefinedValue());
1028 }
1029
1030 return next;
1031 }
1032
1033 void js::gc::DelayCrossCompartmentGrayMarking(GCMarker* maybeMarker,
1034 JSObject* src) {
1035 MOZ_ASSERT_IF(!maybeMarker, !JS::RuntimeHeapIsBusy());
1036 MOZ_ASSERT(IsGrayListObject(src));
1037 MOZ_ASSERT(src->isMarkedGray());
1038
1039 AutoTouchingGrayThings tgt;
1040
1041 mozilla::Maybe<AutoLockGC> lock;
1042 if (maybeMarker && maybeMarker->isParallelMarking()) {
1043 // Synchronize access to JSCompartment::gcIncomingGrayPointers.
1044 //
1045 // TODO: Instead of building this list we could scan all incoming CCWs and
1046 // mark through gray ones when marking gray roots for a sweep group.
1047 lock.emplace(maybeMarker->runtime());
1048 }
1049
1050 /* Called from MarkCrossCompartmentXXX functions. */
1051 unsigned slot = ProxyObject::grayLinkReservedSlot(src);
1052 JSObject* dest = CrossCompartmentPointerReferent(src);
1053 Compartment* comp = dest->compartment();
1054
1055 if (GetProxyReservedSlot(src, slot).isUndefined()) {
1056 SetProxyReservedSlot(src, slot,
1057 ObjectOrNullValue(comp->gcIncomingGrayPointers));
1058 comp->gcIncomingGrayPointers = src;
1059 } else {
1060 MOZ_ASSERT(GetProxyReservedSlot(src, slot).isObjectOrNull());
1061 }
1062
1063 #ifdef DEBUG
1064 /*
1065 * Assert that the object is in our list, also walking the list to check its
1066 * integrity.
1067 */
1068 JSObject* obj = comp->gcIncomingGrayPointers;
1069 bool found = false;
1070 while (obj) {
1071 if (obj == src) {
1072 found = true;
1073 }
1074 obj = NextIncomingCrossCompartmentPointer(obj, false);
1075 }
1076 MOZ_ASSERT(found);
1077 #endif
1078 }
1079
1080 void GCRuntime::markIncomingGrayCrossCompartmentPointers() {
1081 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK_INCOMING_GRAY);
1082
1083 for (SweepGroupCompartmentsIter c(rt); !c.done(); c.next()) {
1084 MOZ_ASSERT(c->zone()->isGCMarkingBlackAndGray());
1085 MOZ_ASSERT_IF(c->gcIncomingGrayPointers,
1086 IsGrayListObject(c->gcIncomingGrayPointers));
1087
1088 for (JSObject* src = c->gcIncomingGrayPointers; src;
1089 src = NextIncomingCrossCompartmentPointer(src, true)) {
1090 JSObject* dst = CrossCompartmentPointerReferent(src);
1091 MOZ_ASSERT(dst->compartment() == c);
1092 MOZ_ASSERT_IF(src->asTenured().isMarkedBlack(),
1093 dst->asTenured().isMarkedBlack());
1094
1095 if (src->asTenured().isMarkedGray()) {
1096 TraceManuallyBarrieredEdge(marker().tracer(), &dst,
1097 "cross-compartment gray pointer");
1098 }
1099 }
1100
1101 c->gcIncomingGrayPointers = nullptr;
1102 }
1103 }
1104
1105 static bool RemoveFromGrayList(JSObject* wrapper) {
1106 AutoTouchingGrayThings tgt;
1107
1108 if (!IsGrayListObject(wrapper)) {
1109 return false;
1110 }
1111
1112 unsigned slot = ProxyObject::grayLinkReservedSlot(wrapper);
1113 if (GetProxyReservedSlot(wrapper, slot).isUndefined()) {
1114 return false; /* Not on our list. */
1115 }
1116
1117 JSObject* tail = GetProxyReservedSlot(wrapper, slot).toObjectOrNull();
1118 SetProxyReservedSlot(wrapper, slot, UndefinedValue());
1119
1120 Compartment* comp = CrossCompartmentPointerReferent(wrapper)->compartment();
1121 JSObject* obj = comp->gcIncomingGrayPointers;
1122 if (obj == wrapper) {
1123 comp->gcIncomingGrayPointers = tail;
1124 return true;
1125 }
1126
1127 while (obj) {
1128 unsigned slot = ProxyObject::grayLinkReservedSlot(obj);
1129 JSObject* next = GetProxyReservedSlot(obj, slot).toObjectOrNull();
1130 if (next == wrapper) {
1131 js::detail::SetProxyReservedSlotUnchecked(obj, slot,
1132 ObjectOrNullValue(tail));
1133 return true;
1134 }
1135 obj = next;
1136 }
1137
1138 MOZ_CRASH("object not found in gray link list");
1139 }
1140
1141 void GCRuntime::resetGrayList(Compartment* comp) {
1142 JSObject* src = comp->gcIncomingGrayPointers;
1143 while (src) {
1144 src = NextIncomingCrossCompartmentPointer(src, true);
1145 }
1146 comp->gcIncomingGrayPointers = nullptr;
1147 }
1148
1149 #ifdef DEBUG
1150 static bool HasIncomingCrossCompartmentPointers(JSRuntime* rt) {
1151 for (SweepGroupCompartmentsIter c(rt); !c.done(); c.next()) {
1152 if (c->gcIncomingGrayPointers) {
1153 return true;
1154 }
1155 }
1156
1157 return false;
1158 }
1159 #endif
1160
1161 void js::NotifyGCNukeWrapper(JSContext* cx, JSObject* wrapper) {
1162 MOZ_ASSERT(IsCrossCompartmentWrapper(wrapper));
1163
1164 /*
1165 * References to target of wrapper are being removed, we no longer have to
1166 * remember to mark it.
1167 */
1168 RemoveFromGrayList(wrapper);
1169
1170 /*
1171 * Clean up WeakRef maps which might include this wrapper.
1172 */
1173 JSObject* target = UncheckedUnwrapWithoutExpose(wrapper);
1174 if (target->is<WeakRefObject>()) {
1175 WeakRefObject* weakRef = &target->as<WeakRefObject>();
1176 if (weakRef->target()) {
1177 cx->runtime()->gc.nukeWeakRefWrapper(wrapper, weakRef);
1178 }
1179 }
1180
1181 /*
1182 * Clean up FinalizationRecord record objects which might be the target of
1183 * this wrapper.
1184 */
1185 if (target->is<FinalizationRecordObject>()) {
1186 auto* record = &target->as<FinalizationRecordObject>();
1187 cx->runtime()->gc.nukeFinalizationRecordWrapper(wrapper, record);
1188 }
1189 }
1190
1191 enum {
1192 JS_GC_SWAP_OBJECT_A_REMOVED = 1 << 0,
1193 JS_GC_SWAP_OBJECT_B_REMOVED = 1 << 1
1194 };
1195
1196 unsigned js::NotifyGCPreSwap(JSObject* a, JSObject* b) {
1197 /*
1198 * Two objects in the same compartment are about to have had their contents
1199 * swapped. If either of them are in our gray pointer list, then we remove
1200 * them from the lists, returning a bitset indicating what happened.
1201 */
1202 return (RemoveFromGrayList(a) ? JS_GC_SWAP_OBJECT_A_REMOVED : 0) |
1203 (RemoveFromGrayList(b) ? JS_GC_SWAP_OBJECT_B_REMOVED : 0);
1204 }
1205
1206 void js::NotifyGCPostSwap(JSObject* a, JSObject* b, unsigned removedFlags) {
1207 /*
1208 * Two objects in the same compartment have had their contents swapped. If
1209 * either of them were in our gray pointer list, we re-add them again.
1210 */
1211 if (removedFlags & JS_GC_SWAP_OBJECT_A_REMOVED) {
1212 DelayCrossCompartmentGrayMarking(nullptr, b);
1213 }
1214 if (removedFlags & JS_GC_SWAP_OBJECT_B_REMOVED) {
1215 DelayCrossCompartmentGrayMarking(nullptr, a);
1216 }
1217 }
1218
1219 static inline void MaybeCheckWeakMapMarking(GCRuntime* gc) {
1220 #if defined(JS_GC_ZEAL) || defined(DEBUG)
1221
1222 bool shouldCheck;
1223 # if defined(DEBUG)
1224 shouldCheck = true;
1225 # else
1226 shouldCheck = gc->hasZealMode(ZealMode::CheckWeakMapMarking);
1227 # endif
1228
1229 if (shouldCheck) {
1230 for (SweepGroupZonesIter zone(gc); !zone.done(); zone.next()) {
1231 MOZ_RELEASE_ASSERT(WeakMapBase::checkMarkingForZone(zone));
1232 }
1233 }
1234
1235 #endif
1236 }
1237
1238 IncrementalProgress GCRuntime::beginMarkingSweepGroup(JS::GCContext* gcx,
1239 SliceBudget& budget) {
1240 #ifdef DEBUG
1241 MOZ_ASSERT(!markOnBackgroundThreadDuringSweeping);
1242 assertNoMarkingWork();
1243 for (auto& marker : markers) {
1244 MOZ_ASSERT(marker->markColor() == MarkColor::Black);
1245 }
1246 MOZ_ASSERT(cellsToAssertNotGray.ref().empty());
1247 #endif
1248
1249 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK);
1250
1251 // Change state of current group to MarkBlackAndGray to restrict gray marking
1252 // to this group. Note that there may be pointers to the atoms zone, and these
1253 // will be marked through, as they are not marked with
1254 // TraceCrossCompartmentEdge.
1255 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1256 zone->changeGCState(zone->initialMarkingState(), Zone::MarkBlackAndGray);
1257 }
1258
1259 AutoSetMarkColor setColorGray(marker(), MarkColor::Gray);
1260
1261 // Mark incoming gray pointers from previously swept compartments.
1262 markIncomingGrayCrossCompartmentPointers();
1263
1264 return Finished;
1265 }
1266
1267 #ifdef DEBUG
1268 bool GCRuntime::zoneInCurrentSweepGroup(Zone* zone) const {
1269 MOZ_ASSERT_IF(!zone->wasGCStarted(), !zone->gcNextGraphComponent);
1270 return zone->wasGCStarted() &&
1271 zone->gcNextGraphComponent == currentSweepGroup->nextGroup();
1272 }
1273 #endif
1274
1275 IncrementalProgress GCRuntime::markGrayRootsInCurrentGroup(
1276 JS::GCContext* gcx, SliceBudget& budget) {
1277 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK);
1278
1279 // Check that the zone state is set correctly for the current sweep group as
1280 // that determines what gets marked.
1281 MOZ_ASSERT(atomsZone()->wasGCStarted() ==
1282 atomsZone()->isGCMarkingBlackAndGray());
1283 for (NonAtomZonesIter zone(this); !zone.done(); zone.next()) {
1284 MOZ_ASSERT(zone->isGCMarkingBlackAndGray() ==
1285 zoneInCurrentSweepGroup(zone));
1286 }
1287
1288 return markGrayRoots(budget, gcstats::PhaseKind::MARK_GRAY);
1289 }
1290
1291 IncrementalProgress GCRuntime::markGray(JS::GCContext* gcx,
1292 SliceBudget& budget) {
1293 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK);
1294
1295 if (markUntilBudgetExhausted(budget, useParallelMarking) == NotFinished) {
1296 return NotFinished;
1297 }
1298
1299 return Finished;
1300 }
1301
1302 IncrementalProgress GCRuntime::endMarkingSweepGroup(JS::GCContext* gcx,
1303 SliceBudget& budget) {
1304 #ifdef DEBUG
1305 MOZ_ASSERT(!markOnBackgroundThreadDuringSweeping);
1306 assertNoMarkingWork();
1307 for (auto& marker : markers) {
1308 MOZ_ASSERT(marker->markColor() == MarkColor::Black);
1309 }
1310 MOZ_ASSERT(!HasIncomingCrossCompartmentPointers(rt));
1311 #endif
1312
1313 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK);
1314
1315 if (markWeakReferencesInCurrentGroup(budget) == NotFinished) {
1316 return NotFinished;
1317 }
1318
1319 AutoSetMarkColor setColorGray(marker(), MarkColor::Gray);
1320
1321 // Mark transitively inside the current compartment group.
1322 if (markWeakReferencesInCurrentGroup(budget) == NotFinished) {
1323 return NotFinished;
1324 }
1325
1326 MOZ_ASSERT(marker().isDrained());
1327
1328 // We must not yield after this point before we start sweeping the group.
1329 safeToYield = false;
1330
1331 MaybeCheckWeakMapMarking(this);
1332
1333 return Finished;
1334 }
1335
1336 // Causes the given WeakCache to be swept when run.
1337 class ImmediateSweepWeakCacheTask : public GCParallelTask {
1338 Zone* zone;
1339 JS::detail::WeakCacheBase& cache;
1340
1341 public:
1342 ImmediateSweepWeakCacheTask(GCRuntime* gc, Zone* zone,
1343 JS::detail::WeakCacheBase& wc)
1344 : GCParallelTask(gc, gcstats::PhaseKind::SWEEP_WEAK_CACHES),
1345 zone(zone),
1346 cache(wc) {}
1347
1348 ImmediateSweepWeakCacheTask(ImmediateSweepWeakCacheTask&& other) noexcept
1349 : GCParallelTask(std::move(other)),
1350 zone(other.zone),
1351 cache(other.cache) {}
1352
1353 ImmediateSweepWeakCacheTask(const ImmediateSweepWeakCacheTask&) = delete;
1354
1355 void run(AutoLockHelperThreadState& lock) override {
1356 AutoUnlockHelperThreadState unlock(lock);
1357 AutoSetThreadIsSweeping threadIsSweeping(zone);
1358 SweepingTracer trc(gc->rt);
1359 cache.traceWeak(&trc, JS::detail::WeakCacheBase::LockStoreBuffer);
1360 }
1361 };
1362
1363 void GCRuntime::updateAtomsBitmap() {
1364 size_t collectedZones = 0;
1365 size_t uncollectedZones = 0;
1366 for (ZonesIter zone(this, SkipAtoms); !zone.done(); zone.next()) {
1367 if (zone->isCollecting()) {
1368 collectedZones++;
1369 } else {
1370 uncollectedZones++;
1371 }
1372 }
1373
1374 atomMarking.refineZoneBitmapsForCollectedZones(this, collectedZones);
1375
1376 atomMarking.markAtomsUsedByUncollectedZones(this, uncollectedZones);
1377
1378 // For convenience sweep these tables non-incrementally as part of bitmap
1379 // sweeping; they are likely to be much smaller than the main atoms table.
1380 SweepingTracer trc(rt);
1381 rt->symbolRegistry().traceWeak(&trc);
1382 }
1383
1384 void GCRuntime::sweepCCWrappers() {
1385 SweepingTracer trc(rt);
1386 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1387 zone->traceWeakCCWEdges(&trc);
1388 }
1389 }
1390
1391 void GCRuntime::sweepRealmGlobals() {
1392 SweepingTracer trc(rt);
1393 for (SweepGroupRealmsIter r(this); !r.done(); r.next()) {
1394 AutoSetThreadIsSweeping threadIsSweeping(r->zone());
1395 r->traceWeakGlobalEdge(&trc);
1396 }
1397 }
1398
1399 void GCRuntime::sweepMisc() {
1400 SweepingTracer trc(rt);
1401 for (SweepGroupRealmsIter r(this); !r.done(); r.next()) {
1402 AutoSetThreadIsSweeping threadIsSweeping(r->zone());
1403 r->traceWeakSavedStacks(&trc);
1404 }
1405 for (SweepGroupCompartmentsIter c(this); !c.done(); c.next()) {
1406 AutoSetThreadIsSweeping threadIsSweeping(c->zone());
1407 c->traceWeakNativeIterators(&trc);
1408 }
1409 }
1410
1411 void GCRuntime::sweepCompressionTasks() {
1412 JSRuntime* runtime = rt;
1413
1414 // Attach finished compression tasks.
1415 AutoLockHelperThreadState lock;
1416 AttachFinishedCompressions(runtime, lock);
1417 SweepPendingCompressions(lock);
1418 }
1419
1420 void GCRuntime::sweepWeakMaps() {
1421 SweepingTracer trc(rt);
1422 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1423 /* No need to look up any more weakmap keys from this sweep group. */
1424 zone->gcEphemeronEdges().clearAndCompact();
1425
1426 // Lock the storebuffer since this may access it when rehashing or resizing
1427 // the tables.
1428 AutoLockStoreBuffer lock(rt);
1429 zone->sweepWeakMaps(&trc);
1430 }
1431 }
1432
1433 void GCRuntime::sweepUniqueIds() {
1434 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1435 AutoSetThreadIsSweeping threadIsSweeping(zone);
1436 zone->sweepUniqueIds();
1437 }
1438 }
1439
1440 void JS::Zone::sweepUniqueIds() {
1441 SweepingTracer trc(runtimeFromAnyThread());
1442 uniqueIds().traceWeak(&trc);
1443 }
1444
1445 /* static */
1446 bool UniqueIdGCPolicy::traceWeak(JSTracer* trc, Cell** keyp, uint64_t* valuep) {
1447 // Since this is only ever used for sweeping, we can optimize it for that
1448 // case. (Compacting GC updates this table manually when it moves a cell.)
1449 MOZ_ASSERT(trc->kind() == JS::TracerKind::Sweeping);
1450 return (*keyp)->isMarkedAny();
1451 }
1452
1453 void GCRuntime::sweepFinalizationObserversOnMainThread() {
1454 // This calls back into the browser which expects to be called from the main
1455 // thread.
1456 gcstats::AutoPhase ap1(stats(), gcstats::PhaseKind::SWEEP_COMPARTMENTS);
1457 gcstats::AutoPhase ap2(stats(),
1458 gcstats::PhaseKind::SWEEP_FINALIZATION_OBSERVERS);
1459 SweepingTracer trc(rt);
1460 AutoLockStoreBuffer lock(rt);
1461 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1462 traceWeakFinalizationObserverEdges(&trc, zone);
1463 }
1464 }
1465
1466 void GCRuntime::startTask(GCParallelTask& task,
1467 AutoLockHelperThreadState& lock) {
1468 if (!CanUseExtraThreads()) {
1469 AutoUnlockHelperThreadState unlock(lock);
1470 task.runFromMainThread();
1471 stats().recordParallelPhase(task.phaseKind, task.duration());
1472 return;
1473 }
1474
1475 task.startWithLockHeld(lock);
1476 }
1477
1478 void GCRuntime::joinTask(GCParallelTask& task,
1479 AutoLockHelperThreadState& lock) {
1480 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::JOIN_PARALLEL_TASKS);
1481 task.joinWithLockHeld(lock);
1482 }
1483
1484 void GCRuntime::sweepDebuggerOnMainThread(JS::GCContext* gcx) {
1485 SweepingTracer trc(rt);
1486 AutoLockStoreBuffer lock(rt);
1487
1488 // Detach unreachable debuggers and global objects from each other.
1489 // This can modify weakmaps and so must happen before weakmap sweeping.
1490 DebugAPI::sweepAll(gcx);
1491
1492 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_COMPARTMENTS);
1493
1494 // Sweep debug environment information. This performs lookups in the Zone's
1495 // unique IDs table and so must not happen in parallel with sweeping that
1496 // table.
1497 {
1498 gcstats::AutoPhase ap2(stats(), gcstats::PhaseKind::SWEEP_MISC);
1499 for (SweepGroupRealmsIter r(rt); !r.done(); r.next()) {
1500 r->traceWeakDebugEnvironmentEdges(&trc);
1501 }
1502 }
1503 }
1504
1505 void GCRuntime::sweepJitDataOnMainThread(JS::GCContext* gcx) {
1506 SweepingTracer trc(rt);
1507 {
1508 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_JIT_DATA);
1509
1510 // Bug 1071218: the following method has not yet been refactored to
1511 // work on a single zone-group at once.
1512
1513 // Sweep entries containing about-to-be-finalized JitCode in the
1514 // JitcodeGlobalTable.
1515 jit::JitRuntime::TraceWeakJitcodeGlobalTable(rt, &trc);
1516 }
1517
1518 // Trace weak edges in JitScripts to remove edges to dying GC things.
1519 {
1520 gcstats::AutoPhase apdc(stats(), gcstats::PhaseKind::SWEEP_JIT_SCRIPTS);
1521 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1522 zone->traceWeakJitScripts(&trc);
1523 }
1524 }
1525
1526 // JitZone must be swept *after* sweeping JitScripts, because
1527 // Zone::traceWeakJitScripts might access CacheIRStubInfos deleted here.
1528 {
1529 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_JIT_DATA);
1530
1531 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1532 if (jit::JitZone* jitZone = zone->jitZone()) {
1533 jitZone->traceWeak(&trc, zone);
1534 }
1535 }
1536
1537 JSContext* cx = rt->mainContextFromOwnThread();
1538 jit::TraceWeakJitActivationsInSweepingZones(cx, &trc);
1539 }
1540 }
1541
1542 void GCRuntime::sweepObjectsWithWeakPointers() {
1543 SweepingTracer trc(rt);
1544 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1545 AutoSetThreadIsSweeping threadIsSweeping(zone);
1546 zone->sweepObjectsWithWeakPointers(&trc);
1547 }
1548 }
1549
1550 void JS::Zone::sweepObjectsWithWeakPointers(JSTracer* trc) {
1551 MOZ_ASSERT(trc->traceWeakEdges());
1552
1553 objectsWithWeakPointers.ref().mutableEraseIf([&](JSObject*& obj) {
1554 if (!TraceManuallyBarrieredWeakEdge(trc, &obj, "objectsWithWeakPointers")) {
1555 // Object itself is dead.
1556 return true;
1557 }
1558
1559 // Call trace hook to sweep weak pointers.
1560 obj->getClass()->doTrace(trc, obj);
1561 return false;
1562 });
1563 }
1564
1565 using WeakCacheTaskVector =
1566 mozilla::Vector<ImmediateSweepWeakCacheTask, 0, SystemAllocPolicy>;
1567
1568 // Call a functor for all weak caches that need to be swept in the current
1569 // sweep group.
1570 template <typename Functor>
1571 static inline bool IterateWeakCaches(JSRuntime* rt, Functor f) {
1572 for (SweepGroupZonesIter zone(rt); !zone.done(); zone.next()) {
1573 for (JS::detail::WeakCacheBase* cache : zone->weakCaches()) {
1574 if (!f(cache, zone.get())) {
1575 return false;
1576 }
1577 }
1578 }
1579
1580 for (JS::detail::WeakCacheBase* cache : rt->weakCaches()) {
1581 if (!f(cache, nullptr)) {
1582 return false;
1583 }
1584 }
1585
1586 return true;
1587 }
1588
1589 static bool PrepareWeakCacheTasks(JSRuntime* rt,
1590 WeakCacheTaskVector* immediateTasks) {
1591 // Start incremental sweeping for caches that support it or add to a vector
1592 // of sweep tasks to run on a helper thread.
1593
1594 MOZ_ASSERT(immediateTasks->empty());
1595
1596 GCRuntime* gc = &rt->gc;
1597 bool ok =
1598 IterateWeakCaches(rt, [&](JS::detail::WeakCacheBase* cache, Zone* zone) {
1599 if (cache->empty()) {
1600 return true;
1601 }
1602
1603 // Caches that support incremental sweeping will be swept later.
1604 if (zone && cache->setIncrementalBarrierTracer(&gc->sweepingTracer)) {
1605 return true;
1606 }
1607
1608 return immediateTasks->emplaceBack(gc, zone, *cache);
1609 });
1610
1611 if (!ok) {
1612 immediateTasks->clearAndFree();
1613 }
1614
1615 return ok;
1616 }
1617
1618 static void SweepAllWeakCachesOnMainThread(JSRuntime* rt) {
1619 // If we ran out of memory, do all the work on the main thread.
1620 gcstats::AutoPhase ap(rt->gc.stats(), gcstats::PhaseKind::SWEEP_WEAK_CACHES);
1621 SweepingTracer trc(rt);
1622 IterateWeakCaches(rt, [&](JS::detail::WeakCacheBase* cache, Zone* zone) {
1623 if (cache->needsIncrementalBarrier()) {
1624 cache->setIncrementalBarrierTracer(nullptr);
1625 }
1626 cache->traceWeak(&trc, JS::detail::WeakCacheBase::LockStoreBuffer);
1627 return true;
1628 });
1629 }
1630
1631 void GCRuntime::sweepEmbeddingWeakPointers(JS::GCContext* gcx) {
1632 using namespace gcstats;
1633
1634 AutoLockStoreBuffer lock(rt);
1635
1636 AutoPhase ap(stats(), PhaseKind::FINALIZE_START);
1637 callFinalizeCallbacks(gcx, JSFINALIZE_GROUP_PREPARE);
1638 {
1639 AutoPhase ap2(stats(), PhaseKind::WEAK_ZONES_CALLBACK);
1640 callWeakPointerZonesCallbacks(&sweepingTracer);
1641 }
1642 {
1643 AutoPhase ap2(stats(), PhaseKind::WEAK_COMPARTMENT_CALLBACK);
1644 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1645 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
1646 callWeakPointerCompartmentCallbacks(&sweepingTracer, comp);
1647 }
1648 }
1649 }
1650 callFinalizeCallbacks(gcx, JSFINALIZE_GROUP_START);
1651 }
1652
1653 IncrementalProgress GCRuntime::beginSweepingSweepGroup(JS::GCContext* gcx,
1654 SliceBudget& budget) {
1655 /*
1656 * Begin sweeping the group of zones in currentSweepGroup, performing
1657 * actions that must be done before yielding to caller.
1658 */
1659
1660 using namespace gcstats;
1661
1662 AutoSCC scc(stats(), sweepGroupIndex);
1663
1664 bool sweepingAtoms = false;
1665 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1666 /* Set the GC state to sweeping. */
1667 zone->changeGCState(Zone::MarkBlackAndGray, Zone::Sweep);
1668
1669 /* Purge the ArenaLists before sweeping. */
1670 zone->arenas.checkSweepStateNotInUse();
1671 zone->arenas.unmarkPreMarkedFreeCells();
1672 zone->arenas.clearFreeLists();
1673
1674 if (zone->isAtomsZone()) {
1675 sweepingAtoms = true;
1676 }
1677 }
1678
1679 #ifdef DEBUG
1680 for (const auto* cell : cellsToAssertNotGray.ref()) {
1681 JS::AssertCellIsNotGray(cell);
1682 }
1683 cellsToAssertNotGray.ref().clearAndFree();
1684 #endif
1685
1686 // Updating the atom marking bitmaps. This marks atoms referenced by
1687 // uncollected zones so cannot be done in parallel with the other sweeping
1688 // work below.
1689 if (sweepingAtoms) {
1690 AutoPhase ap(stats(), PhaseKind::UPDATE_ATOMS_BITMAP);
1691 updateAtomsBitmap();
1692 }
1693
1694 #ifdef JS_GC_ZEAL
1695 validateIncrementalMarking();
1696 #endif
1697
1698 AutoSetThreadIsSweeping threadIsSweeping;
1699
1700 // This must happen before sweeping realm globals.
1701 sweepDebuggerOnMainThread(gcx);
1702
1703 // FinalizationRegistry sweeping touches weak maps and so must not run in
1704 // parallel with that. This triggers a read barrier and can add marking work
1705 // for zones that are still marking. Must happen before sweeping realm
1706 // globals.
1707 sweepFinalizationObserversOnMainThread();
1708
1709 // This must happen before updating embedding weak pointers.
1710 sweepRealmGlobals();
1711
1712 sweepEmbeddingWeakPointers(gcx);
1713
1714 {
1715 AutoLockHelperThreadState lock;
1716
1717 AutoPhase ap(stats(), PhaseKind::SWEEP_COMPARTMENTS);
1718
1719 AutoRunParallelTask sweepCCWrappers(this, &GCRuntime::sweepCCWrappers,
1720 PhaseKind::SWEEP_CC_WRAPPER,
1721 GCUse::Sweeping, lock);
1722 AutoRunParallelTask sweepMisc(this, &GCRuntime::sweepMisc,
1723 PhaseKind::SWEEP_MISC, GCUse::Sweeping, lock);
1724 AutoRunParallelTask sweepCompTasks(this, &GCRuntime::sweepCompressionTasks,
1725 PhaseKind::SWEEP_COMPRESSION,
1726 GCUse::Sweeping, lock);
1727 AutoRunParallelTask sweepWeakMaps(this, &GCRuntime::sweepWeakMaps,
1728 PhaseKind::SWEEP_WEAKMAPS,
1729 GCUse::Sweeping, lock);
1730 AutoRunParallelTask sweepUniqueIds(this, &GCRuntime::sweepUniqueIds,
1731 PhaseKind::SWEEP_UNIQUEIDS,
1732 GCUse::Sweeping, lock);
1733 AutoRunParallelTask sweepWeakPointers(
1734 this, &GCRuntime::sweepObjectsWithWeakPointers,
1735 PhaseKind::SWEEP_WEAK_POINTERS, GCUse::Sweeping, lock);
1736
1737 WeakCacheTaskVector sweepCacheTasks;
1738 bool canSweepWeakCachesOffThread =
1739 PrepareWeakCacheTasks(rt, &sweepCacheTasks);
1740 if (canSweepWeakCachesOffThread) {
1741 weakCachesToSweep.ref().emplace(currentSweepGroup);
1742 for (auto& task : sweepCacheTasks) {
1743 startTask(task, lock);
1744 }
1745 }
1746
1747 {
1748 AutoUnlockHelperThreadState unlock(lock);
1749 sweepJitDataOnMainThread(gcx);
1750
1751 if (!canSweepWeakCachesOffThread) {
1752 MOZ_ASSERT(sweepCacheTasks.empty());
1753 SweepAllWeakCachesOnMainThread(rt);
1754 }
1755 }
1756
1757 for (auto& task : sweepCacheTasks) {
1758 joinTask(task, lock);
1759 }
1760 }
1761
1762 if (sweepingAtoms) {
1763 startSweepingAtomsTable();
1764 }
1765
1766 // Queue all GC things in all zones for sweeping, either on the foreground
1767 // or on the background thread.
1768
1769 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1770 zone->arenas.queueForegroundThingsForSweep();
1771 constexpr AllocKinds backgroundKinds =
1772 BackgroundObjectFinalizePhase + BackgroundTrivialFinalizePhase;
1773 initBackgroundSweep(zone, gcx, backgroundKinds);
1774 }
1775
1776 MOZ_ASSERT(!sweepZone);
1777
1778 safeToYield = true;
1779 markOnBackgroundThreadDuringSweeping = CanUseExtraThreads();
1780
1781 return Finished;
1782 }
1783
1784 #ifdef JS_GC_ZEAL
1785 bool GCRuntime::shouldYieldForZeal(ZealMode mode) {
1786 bool yield = useZeal && hasZealMode(mode);
1787
1788 // Only yield on the first sweep slice for this mode.
1789 bool firstSweepSlice = initialState != State::Sweep;
1790 if (mode == ZealMode::IncrementalMultipleSlices && !firstSweepSlice) {
1791 yield = false;
1792 }
1793
1794 return yield;
1795 }
1796 #endif
1797
1798 IncrementalProgress GCRuntime::endSweepingSweepGroup(JS::GCContext* gcx,
1799 SliceBudget& budget) {
1800 // This is to prevent a race between markTask checking the zone state and
1801 // us changing it below.
1802 if (joinBackgroundMarkTask() == NotFinished) {
1803 return NotFinished;
1804 }
1805
1806 assertNoMarkingWork();
1807
1808 // Disable background marking during sweeping until we start sweeping the next
1809 // zone group.
1810 markOnBackgroundThreadDuringSweeping = false;
1811
1812 {
1813 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::FINALIZE_END);
1814 AutoLockStoreBuffer lock(rt);
1815 callFinalizeCallbacks(gcx, JSFINALIZE_GROUP_END);
1816 }
1817
1818 /* Free LIFO blocks on a background thread if possible. */
1819 startBackgroundFree();
1820
1821 /* Update the GC state for zones we have swept. */
1822 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1823 if (jit::JitZone* jitZone = zone->jitZone()) {
1824 // Clear out any small pools that we're hanging on to.
1825 jitZone->execAlloc().purge();
1826 }
1827 AutoLockGC lock(this);
1828 zone->changeGCState(Zone::Sweep, Zone::Finished);
1829 zone->arenas.unmarkPreMarkedFreeCells();
1830 zone->arenas.checkNoArenasToUpdate();
1831 zone->pretenuring.clearCellCountsInNewlyCreatedArenas();
1832 }
1833
1834 /* Ensure the initial minor GC has finished sweeping. */
1835 MOZ_ASSERT(minorGCNumber >= initialMinorGCNumber);
1836 if (minorGCNumber == initialMinorGCNumber) {
1837 nursery().joinSweepTask();
1838 }
1839
1840 /*
1841 * Start background thread to sweep zones if required, sweeping any atoms
1842 * zones last if present.
1843 */
1844 ZoneList zones;
1845 {
1846 BufferAllocator::MaybeLock lock;
1847 for (SweepGroupZonesIter zone(this); !zone.done(); zone.next()) {
1848 if (zone->isAtomsZone()) {
1849 zones.append(zone);
1850 } else {
1851 zones.prepend(zone);
1852 }
1853
1854 zone->bufferAllocator.startMajorSweeping(lock);
1855 }
1856 }
1857 queueZonesAndStartBackgroundSweep(std::move(zones));
1858
1859 return Finished;
1860 }
1861
1862 IncrementalProgress GCRuntime::markDuringSweeping(JS::GCContext* gcx,
1863 SliceBudget& budget) {
1864 MOZ_ASSERT(markTask.isIdle());
1865
1866 if (markOnBackgroundThreadDuringSweeping) {
1867 if (!marker().isDrained() || hasDelayedMarking()) {
1868 AutoLockHelperThreadState lock;
1869 MOZ_ASSERT(markTask.isIdle(lock));
1870 markTask.setBudget(budget);
1871 markTask.startOrRunIfIdle(lock);
1872 }
1873 return Finished; // This means don't yield to the mutator here.
1874 }
1875
1876 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK);
1877 return markUntilBudgetExhausted(budget, useParallelMarking);
1878 }
1879
1880 void GCRuntime::beginSweepPhase(JS::GCReason reason, AutoGCSession& session) {
1881 /*
1882 * Sweep phase.
1883 *
1884 * Finalize as we sweep, outside of lock but with RuntimeHeapIsBusy()
1885 * true so that any attempt to allocate a GC-thing from a finalizer will
1886 * fail, rather than nest badly and leave the unmarked newborn to be swept.
1887 */
1888
1889 MOZ_ASSERT(!abortSweepAfterCurrentGroup);
1890 MOZ_ASSERT(!markOnBackgroundThreadDuringSweeping);
1891
1892 #ifdef DEBUG
1893 releaseHeldRelocatedArenas();
1894 verifyAllChunks();
1895 #endif
1896
1897 #ifdef JS_GC_ZEAL
1898 computeNonIncrementalMarkingForValidation(session);
1899 #endif
1900
1901 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP);
1902
1903 AssertNoWrappersInGrayList(rt);
1904 dropStringWrappers();
1905
1906 groupZonesForSweeping(reason);
1907
1908 sweepActions->assertFinished();
1909 }
1910
1911 bool ArenaLists::foregroundFinalize(JS::GCContext* gcx, AllocKind thingKind,
1912 SliceBudget& sliceBudget,
1913 SortedArenaList& sweepList) {
1914 checkNoArenasToUpdateForKind(thingKind);
1915
1916 // Non-empty arenas are reused for use for new allocations as soon as the
1917 // finalizers for that allocation kind have run. Empty arenas are only
1918 // released when everything in the zone has been swept (see
1919 // GCRuntime::sweepBackgroundThings for more details).
1920 ArenaList& arenas = collectingArenaList(thingKind);
1921 if (!FinalizeArenas<ReleaseEmpty::No>(gcx, arenas, sweepList, thingKind,
1922 sliceBudget)) {
1923 return false;
1924 }
1925
1926 sweepList.extractEmptyTo(&savedEmptyArenas.ref());
1927 ArenaList sweptArenas = sweepList.convertToArenaList();
1928 mergeSweptArenas(thingKind, sweptArenas);
1929 return true;
1930 }
1931
1932 BackgroundMarkTask::BackgroundMarkTask(GCRuntime* gc)
1933 : GCParallelTask(gc, gcstats::PhaseKind::MARK, GCUse::Marking),
1934 budget(SliceBudget::unlimited()) {}
1935
1936 void js::gc::BackgroundMarkTask::run(AutoLockHelperThreadState& lock) {
1937 AutoUnlockHelperThreadState unlock(lock);
1938
1939 // Time reporting is handled separately for parallel tasks.
1940 gc->sweepMarkResult = gc->markUntilBudgetExhausted(
1941 this->budget, GCRuntime::SingleThreadedMarking, DontReportMarkTime);
1942 }
1943
1944 IncrementalProgress GCRuntime::joinBackgroundMarkTask() {
1945 AutoLockHelperThreadState lock;
1946 if (markTask.isIdle(lock)) {
1947 return Finished;
1948 }
1949
1950 joinTask(markTask, lock);
1951
1952 IncrementalProgress result = sweepMarkResult;
1953 sweepMarkResult = Finished;
1954 return result;
1955 }
1956
1957 template <typename T>
1958 static void SweepThing(JS::GCContext* gcx, T* thing) {
1959 if (!TenuredThingIsMarkedAny(thing)) {
1960 thing->sweep(gcx);
1961 }
1962 }
1963
1964 template <typename T>
1965 static bool SweepArenaList(JS::GCContext* gcx, ArenaList& arenaList,
1966 Arena** arenasToSweep, SliceBudget& sliceBudget) {
1967 if (!*arenasToSweep) {
1968 return true;
1969 }
1970
1971 DebugOnly<Zone*> zone = (*arenasToSweep)->zone();
1972 MOZ_ASSERT(zone->isGCSweeping());
1973
1974 AllocKind kind = MapTypeToAllocKind<T>::kind;
1975 size_t steps = Arena::thingsPerArena(kind);
1976
1977 for (auto arena = arenaList.iterFrom(*arenasToSweep); !arena.done();
1978 arena.next()) {
1979 MOZ_ASSERT(arena->zone() == zone);
1980 MOZ_ASSERT(arena->getAllocKind() == kind);
1981
1982 if (sliceBudget.isOverBudget()) {
1983 *arenasToSweep = arena.get();
1984 return false;
1985 }
1986
1987 for (ArenaCellIterUnderGC cell(arena.get()); !cell.done(); cell.next()) {
1988 SweepThing(gcx, cell.as<T>());
1989 }
1990
1991 sliceBudget.step(steps);
1992 }
1993
1994 *arenasToSweep = nullptr;
1995 return true;
1996 }
1997
1998 void GCRuntime::startSweepingAtomsTable() {
1999 auto& maybeAtoms = maybeAtomsToSweep.ref();
2000 MOZ_ASSERT(maybeAtoms.isNothing());
2001
2002 AtomsTable* atomsTable = rt->atomsForSweeping();
2003 if (!atomsTable) {
2004 return;
2005 }
2006
2007 // Create secondary tables to hold new atoms added while we're sweeping the
2008 // main tables incrementally.
2009 if (!atomsTable->startIncrementalSweep(maybeAtoms)) {
2010 SweepingTracer trc(rt);
2011 atomsTable->traceWeak(&trc);
2012 }
2013 }
2014
2015 IncrementalProgress GCRuntime::sweepAtomsTable(JS::GCContext* gcx,
2016 SliceBudget& budget) {
2017 if (!atomsZone()->isGCSweeping()) {
2018 return Finished;
2019 }
2020
2021 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_ATOMS_TABLE);
2022
2023 auto& maybeAtoms = maybeAtomsToSweep.ref();
2024 if (!maybeAtoms) {
2025 return Finished;
2026 }
2027
2028 if (!rt->atomsForSweeping()->sweepIncrementally(maybeAtoms.ref(), budget)) {
2029 return NotFinished;
2030 }
2031
2032 maybeAtoms.reset();
2033
2034 return Finished;
2035 }
2036
2037 static size_t IncrementalSweepWeakCache(GCRuntime* gc,
2038 const WeakCacheToSweep& item) {
2039 AutoSetThreadIsSweeping threadIsSweeping(item.zone);
2040
2041 JS::detail::WeakCacheBase* cache = item.cache;
2042 MOZ_ASSERT(cache->needsIncrementalBarrier());
2043
2044 SweepingTracer trc(gc->rt);
2045 size_t steps =
2046 cache->traceWeak(&trc, JS::detail::WeakCacheBase::LockStoreBuffer);
2047 cache->setIncrementalBarrierTracer(nullptr);
2048
2049 return steps;
2050 }
2051
2052 WeakCacheSweepIterator::WeakCacheSweepIterator(JS::Zone* sweepGroup)
2053 : sweepZone(sweepGroup), sweepCache(sweepZone->weakCaches().getFirst()) {
2054 settle();
2055 }
2056
2057 bool WeakCacheSweepIterator::done() const { return !sweepZone; }
2058
2059 WeakCacheToSweep WeakCacheSweepIterator::get() const {
2060 MOZ_ASSERT(!done());
2061
2062 return {sweepCache, sweepZone};
2063 }
2064
2065 void WeakCacheSweepIterator::next() {
2066 MOZ_ASSERT(!done());
2067
2068 sweepCache = sweepCache->getNext();
2069 settle();
2070 }
2071
2072 void WeakCacheSweepIterator::settle() {
2073 while (sweepZone) {
2074 while (sweepCache && !sweepCache->needsIncrementalBarrier()) {
2075 sweepCache = sweepCache->getNext();
2076 }
2077
2078 if (sweepCache) {
2079 break;
2080 }
2081
2082 sweepZone = sweepZone->nextNodeInGroup();
2083 if (sweepZone) {
2084 sweepCache = sweepZone->weakCaches().getFirst();
2085 }
2086 }
2087
2088 MOZ_ASSERT((!sweepZone && !sweepCache) ||
2089 (sweepCache && sweepCache->needsIncrementalBarrier()));
2090 }
2091
2092 IncrementalProgress GCRuntime::sweepWeakCaches(JS::GCContext* gcx,
2093 SliceBudget& budget) {
2094 if (weakCachesToSweep.ref().isNothing()) {
2095 return Finished;
2096 }
2097
2098 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_COMPARTMENTS);
2099
2100 WeakCacheSweepIterator& work = weakCachesToSweep.ref().ref();
2101
2102 AutoLockHelperThreadState lock;
2103
2104 {
2105 AutoRunParallelWork runWork(this, IncrementalSweepWeakCache,
2106 gcstats::PhaseKind::SWEEP_WEAK_CACHES,
2107 GCUse::Sweeping, work, budget, lock);
2108 AutoUnlockHelperThreadState unlock(lock);
2109 }
2110
2111 if (work.done()) {
2112 weakCachesToSweep.ref().reset();
2113 return Finished;
2114 }
2115
2116 return NotFinished;
2117 }
2118
2119 IncrementalProgress GCRuntime::finalizeAllocKind(JS::GCContext* gcx,
2120 SliceBudget& budget) {
2121 MOZ_ASSERT(sweepZone->isGCSweeping());
2122
2123 auto& finalizedArenas = foregroundFinalizedArenas.ref();
2124 if (!finalizedArenas) {
2125 finalizedArenas.emplace(sweepAllocKind);
2126 foregroundFinalizedZone = sweepZone;
2127 foregroundFinalizedAllocKind = sweepAllocKind;
2128 } else {
2129 MOZ_ASSERT(finalizedArenas->allocKind() == sweepAllocKind);
2130 MOZ_ASSERT(foregroundFinalizedZone == sweepZone);
2131 MOZ_ASSERT(foregroundFinalizedAllocKind == sweepAllocKind);
2132 }
2133
2134 AutoSetThreadIsFinalizing threadIsFinalizing(gcx);
2135 ArenaLists& arenaLists = sweepZone->arenas;
2136 if (!arenaLists.foregroundFinalize(gcx, sweepAllocKind, budget,
2137 finalizedArenas.ref())) {
2138 return NotFinished;
2139 }
2140
2141 finalizedArenas.reset();
2142 foregroundFinalizedZone = nullptr;
2143 foregroundFinalizedAllocKind = AllocKind::LIMIT;
2144
2145 return Finished;
2146 }
2147
2148 SortedArenaList* GCRuntime::maybeGetForegroundFinalizedArenas(Zone* zone,
2149 AllocKind kind) {
2150 MOZ_ASSERT(zone);
2151 MOZ_ASSERT(IsValidAllocKind(kind));
2152
2153 auto& finalizedArenas = foregroundFinalizedArenas.ref();
2154
2155 if (finalizedArenas.isNothing() || zone != foregroundFinalizedZone ||
2156 kind != foregroundFinalizedAllocKind) {
2157 return nullptr;
2158 }
2159
2160 return finalizedArenas.ptr();
2161 }
2162
2163 IncrementalProgress GCRuntime::sweepPropMapTree(JS::GCContext* gcx,
2164 SliceBudget& budget) {
2165 // Remove dead SharedPropMaps from the tree. This happens incrementally on the
2166 // main thread. PropMaps are finalized later on the a background thread.
2167
2168 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP_PROP_MAP);
2169
2170 ArenaLists& al = sweepZone->arenas;
2171
2172 if (!SweepArenaList<CompactPropMap>(
2173 gcx, al.collectingArenaList(AllocKind::COMPACT_PROP_MAP),
2174 &al.gcCompactPropMapArenasToUpdate.ref(), budget)) {
2175 return NotFinished;
2176 }
2177 if (!SweepArenaList<NormalPropMap>(
2178 gcx, al.collectingArenaList(AllocKind::NORMAL_PROP_MAP),
2179 &al.gcNormalPropMapArenasToUpdate.ref(), budget)) {
2180 return NotFinished;
2181 }
2182
2183 return Finished;
2184 }
2185
2186 // An iterator for a standard container that provides an STL-like begin()/end()
2187 // interface. This iterator provides a done()/get()/next() style interface.
2188 template <typename Container>
2189 class ContainerIter {
2190 using Iter = decltype(std::declval<const Container>().begin());
2191 using Elem = decltype(*std::declval<Iter>());
2192
2193 Iter iter;
2194 const Iter end;
2195
2196 public:
2197 explicit ContainerIter(const Container& container)
2198 : iter(container.begin()), end(container.end()) {}
2199
2200 bool done() const { return iter == end; }
2201
2202 Elem get() const { return *iter; }
2203
2204 void next() {
2205 MOZ_ASSERT(!done());
2206 ++iter;
2207 }
2208 };
2209
2210 // IncrementalIter is a template class that makes a normal iterator into one
2211 // that can be used to perform incremental work by using external state that
2212 // persists between instantiations. The state is only initialised on the first
2213 // use and subsequent uses carry on from the previous state.
2214 template <typename Iter>
2215 struct IncrementalIter {
2216 using State = mozilla::Maybe<Iter>;
2217 using Elem = decltype(std::declval<Iter>().get());
2218
2219 private:
2220 State& maybeIter;
2221
2222 public:
2223 template <typename... Args>
2224 explicit IncrementalIter(State& maybeIter, Args&&... args)
2225 : maybeIter(maybeIter) {
2226 if (maybeIter.isNothing()) {
2227 maybeIter.emplace(std::forward<Args>(args)...);
2228 }
2229 }
2230
2231 ~IncrementalIter() {
2232 if (done()) {
2233 maybeIter.reset();
2234 }
2235 }
2236
2237 bool done() const { return maybeIter.ref().done(); }
2238
2239 Elem get() const { return maybeIter.ref().get(); }
2240
2241 void next() { maybeIter.ref().next(); }
2242 };
2243
2244 // Iterate through the sweep groups created by
2245 // GCRuntime::groupZonesForSweeping().
2246 class js::gc::SweepGroupsIter {
2247 GCRuntime* gc;
2248
2249 public:
2250 explicit SweepGroupsIter(JSRuntime* rt) : gc(&rt->gc) {
2251 MOZ_ASSERT(gc->currentSweepGroup);
2252 }
2253
2254 bool done() const { return !gc->currentSweepGroup; }
2255
2256 Zone* get() const { return gc->currentSweepGroup; }
2257
2258 void next() {
2259 MOZ_ASSERT(!done());
2260 gc->moveToNextSweepGroup();
2261 }
2262 };
2263
2264 namespace sweepaction {
2265
2266 // Implementation of the SweepAction interface that calls a method on GCRuntime.
2267 class SweepActionCall final : public SweepAction {
2268 using Method = IncrementalProgress (GCRuntime::*)(JS::GCContext* gcx,
2269 SliceBudget& budget);
2270
2271 Method method;
2272
2273 public:
2274 explicit SweepActionCall(Method m) : method(m) {}
2275 IncrementalProgress run(Args& args) override {
2276 return (args.gc->*method)(args.gcx, args.budget);
2277 }
2278 void assertFinished() const override {}
2279 };
2280
2281 // Implementation of the SweepAction interface that yields in a specified zeal
2282 // mode.
2283 class SweepActionMaybeYield final : public SweepAction {
2284 #ifdef JS_GC_ZEAL
2285 ZealMode mode;
2286 bool isYielding;
2287 #endif
2288
2289 public:
2290 explicit SweepActionMaybeYield(ZealMode mode)
2291 #ifdef JS_GC_ZEAL
2292 : mode(mode),
2293 isYielding(false)
2294 #endif
2295 {
2296 }
2297
2298 IncrementalProgress run(Args& args) override {
2299 #ifdef JS_GC_ZEAL
2300 if (!isYielding && args.gc->shouldYieldForZeal(mode)) {
2301 isYielding = true;
2302 return NotFinished;
2303 }
2304
2305 isYielding = false;
2306 #endif
2307 return Finished;
2308 }
2309
2310 void assertFinished() const override { MOZ_ASSERT(!isYielding); }
2311
2312 // These actions should be skipped if GC zeal is not configured.
2313 #ifndef JS_GC_ZEAL
2314 bool shouldSkip() override { return true; }
2315 #endif
2316 };
2317
2318 // Implementation of the SweepAction interface that calls a list of actions in
2319 // sequence.
2320 class SweepActionSequence final : public SweepAction {
2321 using ActionVector = Vector<UniquePtr<SweepAction>, 0, SystemAllocPolicy>;
2322 using Iter = IncrementalIter<ContainerIter<ActionVector>>;
2323
2324 ActionVector actions;
2325 typename Iter::State iterState;
2326
2327 public:
2328 bool init(UniquePtr<SweepAction>* acts, size_t count) {
2329 for (size_t i = 0; i < count; i++) {
2330 auto& action = acts[i];
2331 if (!action) {
2332 return false;
2333 }
2334 if (action->shouldSkip()) {
2335 continue;
2336 }
2337 if (!actions.emplaceBack(std::move(action))) {
2338 return false;
2339 }
2340 }
2341 return true;
2342 }
2343
2344 IncrementalProgress run(Args& args) override {
2345 for (Iter iter(iterState, actions); !iter.done(); iter.next()) {
2346 if (iter.get()->run(args) == NotFinished) {
2347 return NotFinished;
2348 }
2349 }
2350 return Finished;
2351 }
2352
2353 void assertFinished() const override {
2354 MOZ_ASSERT(iterState.isNothing());
2355 for (const auto& action : actions) {
2356 action->assertFinished();
2357 }
2358 }
2359 };
2360
2361 template <typename Iter, typename Init>
2362 class SweepActionForEach final : public SweepAction {
2363 using Elem = decltype(std::declval<Iter>().get());
2364 using IncrIter = IncrementalIter<Iter>;
2365
2366 Init iterInit;
2367 Elem* elemOut;
2368 UniquePtr<SweepAction> action;
2369 typename IncrIter::State iterState;
2370
2371 public:
2372 SweepActionForEach(const Init& init, Elem* maybeElemOut,
2373 UniquePtr<SweepAction> action)
2374 : iterInit(init), elemOut(maybeElemOut), action(std::move(action)) {}
2375
2376 IncrementalProgress run(Args& args) override {
2377 MOZ_ASSERT_IF(elemOut, *elemOut == Elem());
2378 auto clearElem = mozilla::MakeScopeExit([&] { setElem(Elem()); });
2379 for (IncrIter iter(iterState, iterInit); !iter.done(); iter.next()) {
2380 setElem(iter.get());
2381 if (action->run(args) == NotFinished) {
2382 return NotFinished;
2383 }
2384 }
2385 return Finished;
2386 }
2387
2388 void assertFinished() const override {
2389 MOZ_ASSERT(iterState.isNothing());
2390 MOZ_ASSERT_IF(elemOut, *elemOut == Elem());
2391 action->assertFinished();
2392 }
2393
2394 private:
2395 void setElem(const Elem& value) {
2396 if (elemOut) {
2397 *elemOut = value;
2398 }
2399 }
2400 };
2401
2402 static UniquePtr<SweepAction> Call(IncrementalProgress (GCRuntime::*method)(
2403 JS::GCContext* gcx, SliceBudget& budget)) {
2404 return MakeUnique<SweepActionCall>(method);
2405 }
2406
2407 static UniquePtr<SweepAction> MaybeYield(ZealMode zealMode) {
2408 return MakeUnique<SweepActionMaybeYield>(zealMode);
2409 }
2410
2411 template <typename... Rest>
2412 static UniquePtr<SweepAction> Sequence(UniquePtr<SweepAction> first,
2413 Rest... rest) {
2414 UniquePtr<SweepAction> actions[] = {std::move(first), std::move(rest)...};
2415 auto seq = MakeUnique<SweepActionSequence>();
2416 if (!seq || !seq->init(actions, std::size(actions))) {
2417 return nullptr;
2418 }
2419
2420 return UniquePtr<SweepAction>(std::move(seq));
2421 }
2422
2423 static UniquePtr<SweepAction> RepeatForSweepGroup(
2424 JSRuntime* rt, UniquePtr<SweepAction> action) {
2425 if (!action) {
2426 return nullptr;
2427 }
2428
2429 using Action = SweepActionForEach<SweepGroupsIter, JSRuntime*>;
2430 return js::MakeUnique<Action>(rt, nullptr, std::move(action));
2431 }
2432
2433 static UniquePtr<SweepAction> ForEachZoneInSweepGroup(
2434 JSRuntime* rt, Zone** zoneOut, UniquePtr<SweepAction> action) {
2435 if (!action) {
2436 return nullptr;
2437 }
2438
2439 using Action = SweepActionForEach<SweepGroupZonesIter, JSRuntime*>;
2440 return js::MakeUnique<Action>(rt, zoneOut, std::move(action));
2441 }
2442
2443 static UniquePtr<SweepAction> ForEachAllocKind(const AllocKinds& kinds,
2444 AllocKind* kindOut,
2445 UniquePtr<SweepAction> action) {
2446 if (!action) {
2447 return nullptr;
2448 }
2449
2450 using Action = SweepActionForEach<ContainerIter<AllocKinds>, AllocKinds>;
2451 return js::MakeUnique<Action>(kinds, kindOut, std::move(action));
2452 }
2453
2454 } // namespace sweepaction
2455
2456 bool GCRuntime::initSweepActions() {
2457 using namespace sweepaction;
2458 using sweepaction::Call;
2459
2460 sweepActions.ref() = RepeatForSweepGroup(
2461 rt,
2462 Sequence(
2463 Call(&GCRuntime::beginMarkingSweepGroup),
2464 Call(&GCRuntime::markGrayRootsInCurrentGroup),
2465 MaybeYield(ZealMode::YieldWhileGrayMarking),
2466 Call(&GCRuntime::markGray), Call(&GCRuntime::endMarkingSweepGroup),
2467 Call(&GCRuntime::beginSweepingSweepGroup),
2468 MaybeYield(ZealMode::IncrementalMultipleSlices),
2469 MaybeYield(ZealMode::YieldBeforeSweepingAtoms),
2470 Call(&GCRuntime::sweepAtomsTable),
2471 MaybeYield(ZealMode::YieldBeforeSweepingCaches),
2472 Call(&GCRuntime::sweepWeakCaches),
2473 ForEachZoneInSweepGroup(
2474 rt, &sweepZone.ref(),
2475 Sequence(MaybeYield(ZealMode::YieldBeforeSweepingObjects),
2476 ForEachAllocKind(ForegroundObjectFinalizePhase,
2477 &sweepAllocKind.ref(),
2478 Call(&GCRuntime::finalizeAllocKind)),
2479 MaybeYield(ZealMode::YieldBeforeSweepingNonObjects),
2480 ForEachAllocKind(ForegroundNonObjectFinalizePhase,
2481 &sweepAllocKind.ref(),
2482 Call(&GCRuntime::finalizeAllocKind)),
2483 MaybeYield(ZealMode::YieldBeforeSweepingPropMapTrees),
2484 Call(&GCRuntime::sweepPropMapTree))),
2485 Call(&GCRuntime::endSweepingSweepGroup)));
2486
2487 return sweepActions != nullptr;
2488 }
2489
2490 void GCRuntime::prepareForSweepSlice(JS::GCReason reason) {
2491 // Work that must be done at the start of each slice where we sweep.
2492 //
2493 // Since this must happen at the start of the slice, it must be called in
2494 // marking slices before any sweeping happens. Therefore it is called
2495 // conservatively since we may not always transition to sweeping from marking.
2496
2497 // Clear out whole cell store buffer entries to unreachable cells.
2498 if (storeBuffer().mayHavePointersToDeadCells()) {
2499 collectNurseryFromMajorGC(reason);
2500 }
2501
2502 // Trace wrapper rooters before marking if we might start sweeping in
2503 // this slice.
2504 rt->mainContextFromOwnThread()->traceWrapperGCRooters(marker().tracer());
2505 }
2506
2507 IncrementalProgress GCRuntime::performSweepActions(SliceBudget& budget) {
2508 MOZ_ASSERT_IF(storeBuffer().isEnabled(),
2509 !storeBuffer().mayHavePointersToDeadCells());
2510
2511 AutoMajorGCProfilerEntry s(this);
2512 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP);
2513
2514 JS::GCContext* gcx = rt->gcContext();
2515 AutoSetThreadIsSweeping threadIsSweeping(gcx);
2516 AutoPoisonFreedJitCode pjc(gcx);
2517
2518 // Don't trigger pre-barriers when finalizing.
2519 AutoDisableBarriers disableBarriers(this);
2520
2521 // Drain the mark stack, possibly in a parallel task if we're in a part of
2522 // sweeping that allows it.
2523 //
2524 // The first time we enter the sweep phase we must not yield to the mutator
2525 // until we've starting sweeping a sweep group but in that case the stack must
2526 // be empty already.
2527
2528 MOZ_ASSERT(initialState <= State::Sweep);
2529 bool startOfSweeping = initialState < State::Sweep;
2530
2531 if (startOfSweeping) {
2532 assertNoMarkingWork();
2533 } else {
2534 if (markDuringSweeping(gcx, budget) == NotFinished) {
2535 return NotFinished;
2536 }
2537 }
2538
2539 // Then continue running sweep actions.
2540
2541 SweepAction::Args args{this, gcx, budget};
2542 IncrementalProgress sweepProgress = sweepActions->run(args);
2543 IncrementalProgress markProgress = joinBackgroundMarkTask();
2544
2545 if (sweepProgress == Finished && markProgress == Finished) {
2546 return Finished;
2547 }
2548
2549 MOZ_ASSERT(isIncremental);
2550 return NotFinished;
2551 }
2552
2553 bool GCRuntime::allCCVisibleZonesWereCollected() {
2554 // Calculate whether the gray marking state is now valid.
2555 //
2556 // The gray bits change from invalid to valid if we finished a full GC from
2557 // the point of view of the cycle collector. We ignore the following:
2558 //
2559 // - Helper thread zones, as these are not reachable from the main heap.
2560 // - The atoms zone, since strings and symbols are never marked gray.
2561 // - Empty zones.
2562 //
2563 // These exceptions ensure that when the CC requests a full GC the gray mark
2564 // state ends up valid even it we don't collect all of the zones.
2565
2566 for (ZonesIter zone(this, SkipAtoms); !zone.done(); zone.next()) {
2567 if (!zone->isCollecting() && !zone->arenas.arenaListsAreEmpty()) {
2568 return false;
2569 }
2570 }
2571
2572 return true;
2573 }
2574
2575 void GCRuntime::endSweepPhase(bool destroyingRuntime) {
2576 MOZ_ASSERT(!markOnBackgroundThreadDuringSweeping);
2577
2578 sweepActions->assertFinished();
2579
2580 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::SWEEP);
2581
2582 MOZ_ASSERT_IF(destroyingRuntime, !useBackgroundThreads);
2583
2584 // Release parallel marking threads for worker runtimes now we've finished
2585 // marking. The main thread keeps the reservation as long as parallel marking
2586 // is enabled.
2587 if (!rt->isMainRuntime()) {
2588 MOZ_ASSERT_IF(useParallelMarking, reservedMarkingThreads != 0);
2589 releaseMarkingThreads();
2590 }
2591
2592 {
2593 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::DESTROY);
2594
2595 // Sweep shared script bytecode now all zones have been swept and finalizers
2596 // for BaseScripts have released their references.
2597 SweepScriptData(rt);
2598 }
2599
2600 {
2601 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::FINALIZE_END);
2602 AutoLockStoreBuffer lock(rt);
2603 callFinalizeCallbacks(rt->gcContext(), JSFINALIZE_COLLECTION_END);
2604
2605 if (allCCVisibleZonesWereCollected()) {
2606 grayBitsValid = true;
2607 }
2608 }
2609
2610 if (isIncremental) {
2611 findDeadCompartments();
2612 }
2613
2614 #ifdef JS_GC_ZEAL
2615 finishMarkingValidation();
2616 #endif
2617
2618 AssertNoWrappersInGrayList(rt);
2619 }