Debian Codegraph @

js/src/gc/Compacting.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 compacting GC.
9 */
10
11 #include "mozilla/Maybe.h"
12
13 #include "debugger/DebugAPI.h"
14 #include "gc/ArenaList.h"
15 #include "gc/GCInternals.h"
16 #include "gc/GCLock.h"
17 #include "gc/ParallelWork.h"
18 #include "gc/Zone.h"
19 #include "jit/JitCode.h"
20 #include "jit/JitRuntime.h"
21 #include "jit/JitZone.h"
22 #include "js/GCAPI.h"
23 #include "vm/HelperThreads.h"
24 #include "vm/Realm.h"
25 #include "wasm/WasmGcObject.h"
26
27 #include "gc/Heap-inl.h"
28 #include "gc/Marking-inl.h"
29 #include "gc/PrivateIterators-inl.h"
30 #include "gc/StableCellHasher-inl.h"
31 #include "gc/TraceMethods-inl.h"
32 #include "vm/GeckoProfiler-inl.h"
33
34 using namespace js;
35 using namespace js::gc;
36
37 using mozilla::Maybe;
38
39 using JS::SliceBudget;
40
41 bool GCRuntime::canRelocateZone(Zone* zone) const {
42 return !zone->isAtomsZone();
43 }
44
45 void GCRuntime::beginCompactPhase() {
46 MOZ_ASSERT(!isBackgroundSweeping());
47 assertBackgroundSweepingFinished();
48
49 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::COMPACT);
50
51 MOZ_ASSERT(zonesToMaybeCompact.ref().isEmpty());
52 for (GCZonesIter zone(this); !zone.done(); zone.next()) {
53 if (canRelocateZone(zone)) {
54 zonesToMaybeCompact.ref().append(zone);
55 }
56 }
57
58 startedCompacting = true;
59 zonesCompacted = 0;
60
61 #ifdef DEBUG
62 AutoLockGC lock(this);
63 MOZ_ASSERT(!relocatedArenasToRelease);
64 #endif
65 }
66
67 IncrementalProgress GCRuntime::compactPhase(JS::GCReason reason,
68 SliceBudget& sliceBudget,
69 AutoGCSession& session) {
70 assertBackgroundSweepingFinished();
71 MOZ_ASSERT(startedCompacting);
72
73 AutoMajorGCProfilerEntry s(this);
74 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::COMPACT);
75
76 // TODO: JSScripts can move. If the sampler interrupts the GC in the
77 // middle of relocating an arena, invalid JSScript pointers may be
78 // accessed. Suppress all sampling until a finer-grained solution can be
79 // found. See bug 1295775.
80 AutoSuppressProfilerSampling suppressSampling(rt->mainContextFromOwnThread());
81
82 ZoneList relocatedZones;
83 Arena* relocatedArenas = nullptr;
84 while (!zonesToMaybeCompact.ref().isEmpty()) {
85 Zone* zone = zonesToMaybeCompact.ref().front();
86 zonesToMaybeCompact.ref().removeFront();
87
88 MOZ_ASSERT(nursery().isEmpty());
89 zone->changeGCState(Zone::Finished, Zone::Compact);
90
91 if (relocateArenas(zone, reason, relocatedArenas, sliceBudget)) {
92 updateZonePointersToRelocatedCells(zone);
93 relocatedZones.append(zone);
94 zonesCompacted++;
95 } else {
96 zone->changeGCState(Zone::Compact, Zone::Finished);
97 }
98
99 if (sliceBudget.isOverBudget()) {
100 break;
101 }
102 }
103
104 if (!relocatedZones.isEmpty()) {
105 updateRuntimePointersToRelocatedCells(session);
106
107 do {
108 Zone* zone = relocatedZones.front();
109 relocatedZones.removeFront();
110 zone->changeGCState(Zone::Compact, Zone::Finished);
111 } while (!relocatedZones.isEmpty());
112 }
113
114 clearRelocatedArenas(relocatedArenas, reason);
115
116 #ifdef DEBUG
117 protectOrReleaseRelocatedArenas(relocatedArenas, reason);
118 #else
119 releaseRelocatedArenas(relocatedArenas);
120 #endif
121
122 // Clear caches that can contain cell pointers.
123 rt->caches().purgeForCompaction();
124
125 #ifdef DEBUG
126 checkHashTablesAfterMovingGC();
127 #endif
128
129 return zonesToMaybeCompact.ref().isEmpty() ? Finished : NotFinished;
130 }
131
132 void GCRuntime::endCompactPhase() { startedCompacting = false; }
133
134 static bool ShouldRelocateAllArenas(JS::GCReason reason) {
135 return reason == JS::GCReason::DEBUG_GC;
136 }
137
138 /*
139 * Choose which arenas to relocate all cells from.
140 *
141 * Return a pair of arena pointers indicating the arenas to relocate that can be
142 * passed to removeRange(), or null pointers if nothing can be relocated.
143 */
144 std::pair<Arena*, Arena*> ArenaList::pickArenasToRelocate(
145 AllocKind kind, size_t& arenaTotalOut, size_t& relocTotalOut) {
146 // Relocate the greatest number of arenas such that the number of used cells
147 // in relocated arenas is less than or equal to the number of free cells in
148 // unrelocated arenas. In other words we only relocate cells we can move
149 // into existing arenas, and we choose the least full areans to relocate.
150 //
151 // This is made easier by the fact that the start of the arena list has been
152 // sorted in descending order of number of used cells, so we will always
153 // relocate a sublist of the arena list. All we need to do is find the points
154 // at which to start and end relocating.
155
156 if (!hasNonFullArenas()) {
157 // All arenas are full so no compacting is possible.
158 return {nullptr, nullptr};
159 }
160
161 // Count non-full and full arenas and total used cells, and find the last
162 // non-full arena.
163 size_t fullArenaCount = 0; // Number of full arenas (not relocated).
164 size_t nonFullArenaCount = 0; // Number of non-full arenas to consider.
165 size_t totalUsedCells = 0; // Total used cells in non-full arenas.
166 Arena* lastNonFullArena = nullptr;
167
168 Iterator arena = iter();
169 for (; !arena.done(); arena.next()) {
170 if (arena->isFull()) {
171 break;
172 }
173
174 MOZ_ASSERT(!arena->isFull());
175 nonFullArenaCount++;
176 totalUsedCells += arena->countUsedCells();
177 lastNonFullArena = arena.get();
178 }
179 for (; !arena.done(); arena.next()) {
180 // It's likely that the final arena is not full but we ignore that.
181 fullArenaCount++;
182 }
183
184 size_t previousFreeCells = 0; // Total free cells before arena.
185 size_t followingUsedCells =
186 totalUsedCells; // Total used cells in non full arenas afterwards.
187 size_t relocCount = nonFullArenaCount; // Number of arenas to relocate.
188 Arena* prev = nullptr; // The previous arena considered.
189
190 const size_t cellsPerArena = Arena::thingsPerArena(kind);
191
192 // Examine the initial part of the list containing non-full arenas.
193 for (arena = iter(); prev != lastNonFullArena;
194 prev = arena.get(), arena.next()) {
195 if (followingUsedCells <= previousFreeCells) {
196 // We have found the point where cells in the following non-full arenas
197 // can be relocated into the free space in previous arenas. We're done.
198 break;
199 }
200
201 size_t freeCells = arena->countFreeCells();
202 MOZ_ASSERT(freeCells != 0);
203 size_t usedCells = cellsPerArena - freeCells;
204 followingUsedCells -= usedCells;
205 previousFreeCells += freeCells;
206 MOZ_ASSERT(relocCount != 0);
207 relocCount--;
208 }
209
210 MOZ_ASSERT((relocCount == 0) == (prev == lastNonFullArena));
211 arenaTotalOut += fullArenaCount + nonFullArenaCount;
212 relocTotalOut += relocCount;
213
214 if (relocCount == 0) {
215 return {nullptr, nullptr};
216 }
217
218 return {prev, lastNonFullArena};
219 }
220
221 #ifdef DEBUG
222 inline bool PtrIsInRange(const void* ptr, const void* start, size_t length) {
223 return uintptr_t(ptr) - uintptr_t(start) < length;
224 }
225 #endif
226
227 static void RelocateCell(Zone* zone, TenuredCell* src, AllocKind thingKind,
228 size_t thingSize) {
229 JS::AutoSuppressGCAnalysis nogc;
230
231 // Allocate a new cell.
232 MOZ_ASSERT(zone == src->zone());
233 TenuredCell* dst =
234 reinterpret_cast<TenuredCell*>(AllocateTenuredCellInGC(zone, thingKind));
235
236 // Copy source cell contents to destination.
237 memcpy(dst, src, thingSize);
238
239 // Move any uid attached to the object.
240 gc::TransferUniqueId(dst, src);
241
242 if (IsObjectAllocKind(thingKind)) {
243 auto* srcObj = static_cast<JSObject*>(static_cast<Cell*>(src));
244 auto* dstObj = static_cast<JSObject*>(static_cast<Cell*>(dst));
245
246 if (srcObj->is<NativeObject>()) {
247 NativeObject* srcNative = &srcObj->as<NativeObject>();
248 NativeObject* dstNative = &dstObj->as<NativeObject>();
249
250 // Fixup the pointer to inline object elements if necessary.
251 if (srcNative->hasFixedElements()) {
252 uint32_t numShifted =
253 srcNative->getElementsHeader()->numShiftedElements();
254 dstNative->setFixedElements(numShifted);
255 }
256 } else if (srcObj->is<ProxyObject>()) {
257 if (srcObj->as<ProxyObject>().usingInlineValueArray()) {
258 dstObj->as<ProxyObject>().setInlineValueArray();
259 }
260 }
261
262 // Call object moved hook if present.
263 if (JSObjectMovedOp op = srcObj->getClass()->extObjectMovedOp()) {
264 op(dstObj, srcObj);
265 }
266
267 MOZ_ASSERT_IF(
268 dstObj->is<NativeObject>(),
269 !PtrIsInRange(
270 (const Value*)dstObj->as<NativeObject>().getDenseElements(), src,
271 thingSize));
272 }
273
274 // Copy the mark bits.
275 dst->copyMarkBitsFrom(src);
276
277 // Poison the source cell contents except for the forwarding flag and pointer
278 // which will be stored in the first word. We can't do this for buffer
279 // allocations as these can be used as native object dynamic elements and this
280 // would overwrite the elements flags which are needed when updating the
281 // dynamic elements pointer.
282 #ifdef DEBUG
283 bool poison = true;
284 if (IsObjectAllocKind(thingKind)) {
285 JSObject* srcObj = static_cast<JSObject*>(static_cast<Cell*>(src));
286 poison = !(srcObj->is<WasmArrayObject>() &&
287 srcObj->as<WasmArrayObject>().isDataInline());
288 } else if (IsBufferAllocKind(thingKind)) {
289 poison = false;
290 }
291 if (poison) {
292 AlwaysPoison(reinterpret_cast<uint8_t*>(src) + sizeof(uintptr_t),
293 JS_MOVED_TENURED_PATTERN, thingSize - sizeof(uintptr_t),
294 MemCheckKind::MakeNoAccess);
295 }
296 #endif
297
298 // Mark source cell as forwarded and leave a pointer to the destination.
299 RelocationOverlay::forwardCell(src, dst);
300 }
301
302 static void RelocateArena(Arena* arena, SliceBudget& sliceBudget) {
303 MOZ_ASSERT(arena->allocated());
304 MOZ_ASSERT(!arena->onDelayedMarkingList());
305 MOZ_ASSERT(arena->bufferedCells()->isEmpty());
306
307 Zone* zone = arena->zone();
308
309 AllocKind thingKind = arena->getAllocKind();
310 size_t thingSize = arena->getThingSize();
311
312 for (ArenaCellIterUnderGC cell(arena); !cell.done(); cell.next()) {
313 RelocateCell(zone, cell, thingKind, thingSize);
314 sliceBudget.step();
315 }
316
317 #ifdef DEBUG
318 for (ArenaCellIterUnderGC cell(arena); !cell.done(); cell.next()) {
319 TenuredCell* src = cell;
320 MOZ_ASSERT(src->isForwarded());
321 TenuredCell* dest = Forwarded(src);
322 MOZ_ASSERT(src->isMarkedBlack() == dest->isMarkedBlack());
323 MOZ_ASSERT(src->isMarkedGray() == dest->isMarkedGray());
324 }
325 #endif
326 }
327
328 /*
329 * Relocate all arenas identified by pickArenasToRelocate: for each arena,
330 * relocate each cell within it, then add it to a list of relocated arenas.
331 */
332 Arena* ArenaList::relocateArenas(Arena* toRelocate, Arena* relocated,
333 SliceBudget& sliceBudget,
334 gcstats::Statistics& stats) {
335 while (Arena* arena = toRelocate) {
336 toRelocate = arena->next;
337 RelocateArena(arena, sliceBudget);
338 // Prepend to list of relocated arenas
339 arena->next = relocated;
340 relocated = arena;
341 stats.count(gcstats::COUNT_ARENA_RELOCATED);
342 }
343
344 return relocated;
345 }
346
347 // Skip compacting zones unless we can free a certain proportion of their GC
348 // heap memory.
349 static const double MIN_ZONE_RECLAIM_PERCENT = 2.0;
350
351 static bool ShouldRelocateZone(size_t arenaCount, size_t relocCount,
352 JS::GCReason reason) {
353 if (relocCount == 0) {
354 return false;
355 }
356
357 if (IsOOMReason(reason)) {
358 return true;
359 }
360
361 double relocFraction = double(relocCount) / double(arenaCount);
362 return relocFraction * 100.0 >= MIN_ZONE_RECLAIM_PERCENT;
363 }
364
365 static AllocKinds CompactingAllocKinds() {
366 AllocKinds result;
367 for (AllocKind kind : AllAllocKinds()) {
368 if (IsCompactingKind(kind)) {
369 result += kind;
370 }
371 }
372 return result;
373 }
374
375 bool ArenaLists::relocateArenas(Arena*& relocatedListOut, JS::GCReason reason,
376 SliceBudget& sliceBudget,
377 gcstats::Statistics& stats) {
378 // This is only called from the main thread while we are doing a GC, so
379 // there is no need to lock.
380 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
381 MOZ_ASSERT(runtime()->gc.isHeapCompacting());
382 MOZ_ASSERT(!runtime()->gc.isBackgroundSweeping());
383
384 // Relocate all compatible kinds
385 AllocKinds allocKindsToRelocate = CompactingAllocKinds();
386
387 // Clear all the free lists.
388 clearFreeLists();
389
390 if (ShouldRelocateAllArenas(reason)) {
391 zone_->prepareForMovingGC();
392 for (auto kind : allocKindsToRelocate) {
393 ArenaList& al = arenaList(kind);
394 Arena* allArenas = al.release();
395 relocatedListOut =
396 al.relocateArenas(allArenas, relocatedListOut, sliceBudget, stats);
397 }
398 } else {
399 size_t arenaCount = 0;
400 size_t relocCount = 0;
401 AllAllocKindArray<std::pair<Arena*, Arena*>> rangeToRelocate;
402
403 for (auto kind : allocKindsToRelocate) {
404 rangeToRelocate[kind] =
405 arenaList(kind).pickArenasToRelocate(kind, arenaCount, relocCount);
406 }
407
408 if (!ShouldRelocateZone(arenaCount, relocCount, reason)) {
409 return false;
410 }
411
412 zone_->prepareForMovingGC();
413 for (auto kind : allocKindsToRelocate) {
414 if (rangeToRelocate[kind].first) {
415 ArenaList& al = arenaList(kind);
416 const auto& range = rangeToRelocate[kind];
417 Arena* arenas = al.removeRange(range.first, range.second);
418 relocatedListOut =
419 al.relocateArenas(arenas, relocatedListOut, sliceBudget, stats);
420 }
421 }
422 }
423
424 return true;
425 }
426
427 bool GCRuntime::relocateArenas(Zone* zone, JS::GCReason reason,
428 Arena*& relocatedListOut,
429 SliceBudget& sliceBudget) {
430 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::COMPACT_MOVE);
431
432 MOZ_ASSERT(!zone->isPreservingCode());
433 MOZ_ASSERT(canRelocateZone(zone));
434
435 js::CancelOffThreadCompile(rt, JS::Zone::Compact);
436
437 if (!zone->arenas.relocateArenas(relocatedListOut, reason, sliceBudget,
438 stats())) {
439 return false;
440 }
441
442 #ifdef DEBUG
443 // Check that we did as much compaction as we should have. There
444 // should always be less than one arena's worth of free cells.
445 for (auto kind : CompactingAllocKinds()) {
446 ArenaList& al = zone->arenas.arenaList(kind);
447 size_t freeCells = 0;
448 for (auto arena = al.iter(); !arena.done(); arena.next()) {
449 if (arena->isFull()) {
450 break;
451 }
452 freeCells += arena->countFreeCells();
453 }
454 MOZ_ASSERT(freeCells < Arena::thingsPerArena(kind));
455 }
456 #endif
457
458 return true;
459 }
460
461 MovingTracer::MovingTracer(JSRuntime* rt)
462 : GenericTracerImpl(rt, JS::TracerKind::Moving,
463 JS::WeakMapTraceAction::TraceKeysAndValues) {}
464
465 template <typename T>
466 inline void MovingTracer::onEdge(T** thingp, const char* name) {
467 T* thing = *thingp;
468 if (IsForwarded(thing)) {
469 MOZ_ASSERT(thing->runtimeFromAnyThread() == runtime());
470 *thingp = Forwarded(thing);
471 }
472 }
473
474 void GCRuntime::sweepZoneAfterCompacting(MovingTracer* trc, Zone* zone) {
475 MOZ_ASSERT(zone->isGCCompacting());
476
477 zone->traceWeakMaps(trc);
478 zone->sweepObjectsWithWeakPointers(trc);
479
480 traceWeakFinalizationObserverEdges(trc, zone);
481
482 for (auto* cache : zone->weakCaches()) {
483 cache->traceWeak(trc, JS::detail::WeakCacheBase::DontLockStoreBuffer);
484 }
485
486 if (jit::JitZone* jitZone = zone->jitZone()) {
487 jitZone->traceWeak(trc, zone);
488 }
489
490 for (CompartmentsInZoneIter c(zone); !c.done(); c.next()) {
491 c->traceWeakNativeIterators(trc);
492
493 for (RealmsInCompartmentIter r(c); !r.done(); r.next()) {
494 r->traceWeakSavedStacks(trc);
495 r->traceWeakGlobalEdge(trc);
496 r->traceWeakDebugEnvironmentEdges(trc);
497 }
498 }
499 }
500
501 template <typename T>
502 static inline void UpdateCellPointers(MovingTracer* trc, T* cell) {
503 // We only update unmoved GC things or the new copy of moved GC things, never
504 // the old copy. If this happened it could clear the forwarded flag which
505 // could lead to pointers to the old copy not being updated.
506 MOZ_ASSERT(!cell->isForwarded());
507
508 cell->fixupAfterMovingGC();
509 cell->traceChildren(trc);
510 }
511
512 template <typename T>
513 static void UpdateArenaPointersTyped(MovingTracer* trc, Arena* arena) {
514 for (ArenaCellIterUnderGC cell(arena); !cell.done(); cell.next()) {
515 UpdateCellPointers(trc, cell.as<T>());
516 }
517 }
518
519 static bool CanUpdateKindInBackground(AllocKind kind) {
520 // We try to update as many GC things in parallel as we can, but there are
521 // kinds for which this might not be safe:
522 // - we assume JSObjects that are foreground finalized are not safe to
523 // update in parallel
524 // - updating a SharedPropMap touches child maps in
525 // SharedPropMap::fixupAfterMovingGC
526 return js::gc::IsBackgroundFinalized(kind) && !IsShapeAllocKind(kind) &&
527 kind != AllocKind::BASE_SHAPE;
528 }
529
530 /*
531 * Update the internal pointers for all cells in an arena.
532 */
533 static void UpdateArenaPointers(MovingTracer* trc, Arena* arena) {
534 AllocKind kind = arena->getAllocKind();
535
536 MOZ_ASSERT_IF(!CanUpdateKindInBackground(kind),
537 CurrentThreadCanAccessRuntime(trc->runtime()));
538
539 switch (kind) {
540 #define EXPAND_CASE(allocKind, traceKind, type, sizedType, bgFinal, nursery, \
541 compact) \
542 case AllocKind::allocKind: \
543 UpdateArenaPointersTyped<type>(trc, arena); \
544 return;
545 FOR_EACH_ALLOCKIND(EXPAND_CASE)
546 #undef EXPAND_CASE
547
548 default:
549 MOZ_CRASH("Invalid alloc kind for UpdateArenaPointers");
550 }
551 }
552
553 struct ArenaListSegment {
554 Arena* begin;
555 Arena* end;
556 };
557
558 /*
559 * Update the internal pointers for all arenas in a segment of an arena list.
560 *
561 * Returns the number of steps to count against the slice budget.
562 */
563 static size_t UpdateArenaListSegmentPointers(GCRuntime* gc,
564 const ArenaListSegment& arenas) {
565 MOZ_ASSERT(arenas.begin);
566 MovingTracer trc(gc->rt);
567 size_t count = 0;
568 Arena* arena = arenas.begin;
569 do {
570 UpdateArenaPointers(&trc, arena);
571 count++;
572 arena = arena->next;
573 } while (arena != arenas.end);
574 return count * 256;
575 }
576
577 class ArenasToUpdate {
578 // Maximum number of arenas to update in one block.
579 #ifdef DEBUG
580 static const unsigned MaxArenasToProcess = 16;
581 #else
582 static const unsigned MaxArenasToProcess = 256;
583 #endif
584
585 public:
586 ArenasToUpdate(Zone* zone, const AllocKinds& kinds)
587 : kinds(kinds), zone(zone) {
588 settle();
589 }
590
591 bool done() const {
592 MOZ_ASSERT_IF(!segmentBegin, endOfArenaList);
593 return !segmentBegin;
594 }
595
596 ArenaListSegment get() const {
597 MOZ_ASSERT(!done());
598 return {segmentBegin, segmentEnd};
599 }
600
601 void next();
602
603 private:
604 AllocKinds kinds; // Selects which thing kinds to update.
605 Zone* zone; // Zone to process.
606 AllocKind kind = AllocKind::FIRST; // Current alloc kind to process.
607 Arena* segmentBegin = nullptr;
608 Arena* segmentEnd = nullptr;
609 bool endOfArenaList = true;
610
611 static AllocKind nextAllocKind(AllocKind i) {
612 return AllocKind(uint8_t(i) + 1);
613 }
614
615 void settle();
616 void findSegmentEnd();
617 };
618
619 void ArenasToUpdate::settle() {
620 // Called when we have set |kind| to a new kind. Sets |arena| to the next
621 // arena or null if there are no more arenas to update.
622
623 MOZ_ASSERT(!segmentBegin);
624 MOZ_ASSERT(endOfArenaList);
625
626 for (; kind < AllocKind::LIMIT; kind = nextAllocKind(kind)) {
627 if (!kinds.contains(kind)) {
628 continue;
629 }
630
631 Arena* arena = zone->arenas.getFirstArena(kind);
632 if (arena) {
633 segmentBegin = arena;
634 endOfArenaList = false;
635 findSegmentEnd();
636 break;
637 }
638 }
639 }
640
641 void ArenasToUpdate::findSegmentEnd() {
642 // Take up to MaxArenasToProcess arenas from the list starting at
643 // |segmentBegin| and set |segmentEnd| and |endOfArenaList|.
644 MOZ_ASSERT(segmentBegin);
645 MOZ_ASSERT(!endOfArenaList);
646
647 Arena* arena = segmentBegin;
648 Arena* firstArena = zone->arenas.getFirstArena(kind);
649 for (size_t i = 0; i < MaxArenasToProcess; i++) {
650 arena = arena->next;
651 if (arena == firstArena) {
652 // We have reached the end of the circular linked list.
653 endOfArenaList = true;
654 break;
655 }
656 }
657 segmentEnd = arena;
658 }
659
660 void ArenasToUpdate::next() {
661 MOZ_ASSERT(!done());
662
663 if (!endOfArenaList) {
664 segmentBegin = segmentEnd;
665 findSegmentEnd();
666 return;
667 }
668
669 segmentBegin = nullptr;
670 kind = nextAllocKind(kind);
671 settle();
672 }
673
674 static AllocKinds ForegroundUpdateKinds(AllocKinds kinds) {
675 AllocKinds result;
676 for (AllocKind kind : kinds) {
677 if (!CanUpdateKindInBackground(kind)) {
678 result += kind;
679 }
680 }
681 return result;
682 }
683
684 void GCRuntime::updateCellPointers(Zone* zone, AllocKinds kinds) {
685 AllocKinds fgKinds = ForegroundUpdateKinds(kinds);
686 AllocKinds bgKinds = kinds - fgKinds;
687
688 ArenasToUpdate fgArenas(zone, fgKinds);
689 ArenasToUpdate bgArenas(zone, bgKinds);
690
691 AutoLockHelperThreadState lock;
692
693 AutoRunParallelWork bgTasks(this, UpdateArenaListSegmentPointers,
694 gcstats::PhaseKind::COMPACT_UPDATE_CELLS,
695 GCUse::Unspecified, bgArenas,
696 SliceBudget::unlimited(), lock);
697
698 AutoUnlockHelperThreadState unlock(lock);
699
700 for (; !fgArenas.done(); fgArenas.next()) {
701 UpdateArenaListSegmentPointers(this, fgArenas.get());
702 }
703 }
704
705 // After cells have been relocated any pointers to a cell's old locations must
706 // be updated to point to the new location. This happens by iterating through
707 // all cells in heap and tracing their children (non-recursively) to update
708 // them.
709 //
710 // This is complicated by the fact that updating a GC thing sometimes depends on
711 // making use of other GC things. After a moving GC these things may not be in a
712 // valid state since they may contain pointers which have not been updated yet.
713 //
714 // The main remaining dependency is:
715 //
716 // - Updating a JSObject makes use of its shape
717 //
718 // This means we require at least two phases for update:
719 //
720 // 1) a phase including shapes
721 // 2) a phase including all JS objects
722 //
723 // Also, there can be data races calling IsForwarded() on the new location of a
724 // cell whose first word is being updated in parallel on another thread. This
725 // easiest way to avoid this is to not store a GC pointer in the first word of a
726 // cell. Otherwise this can be avoided by updating different kinds of cell in
727 // different phases.
728 //
729 // Since we want to minimize the number of phases, arrange kinds into two
730 // arbitrary phases.
731
732 static constexpr AllocKinds UpdatePhaseOne{AllocKind::SCRIPT,
733 AllocKind::BASE_SHAPE,
734 AllocKind::SHAPE,
735 AllocKind::STRING,
736 AllocKind::JITCODE,
737 AllocKind::REGEXP_SHARED,
738 AllocKind::SCOPE,
739 AllocKind::GETTER_SETTER,
740 AllocKind::COMPACT_PROP_MAP,
741 AllocKind::NORMAL_PROP_MAP,
742 AllocKind::DICT_PROP_MAP};
743
744 static constexpr AllocKinds UpdatePhaseTwo{AllocKind::FUNCTION,
745 AllocKind::FUNCTION_EXTENDED,
746 AllocKind::OBJECT0,
747 AllocKind::OBJECT0_FOREGROUND,
748 AllocKind::OBJECT0_BACKGROUND,
749 AllocKind::OBJECT2,
750 AllocKind::OBJECT2_FOREGROUND,
751 AllocKind::OBJECT2_BACKGROUND,
752 AllocKind::ARRAYBUFFER4,
753 AllocKind::OBJECT4,
754 AllocKind::OBJECT4_FOREGROUND,
755 AllocKind::OBJECT4_BACKGROUND,
756 AllocKind::ARRAYBUFFER8,
757 AllocKind::OBJECT8,
758 AllocKind::OBJECT8_FOREGROUND,
759 AllocKind::OBJECT8_BACKGROUND,
760 AllocKind::ARRAYBUFFER12,
761 AllocKind::OBJECT12,
762 AllocKind::OBJECT12_FOREGROUND,
763 AllocKind::OBJECT12_BACKGROUND,
764 AllocKind::ARRAYBUFFER16,
765 AllocKind::OBJECT16,
766 AllocKind::OBJECT16_FOREGROUND,
767 AllocKind::OBJECT16_BACKGROUND};
768
769 void GCRuntime::updateAllCellPointers(MovingTracer* trc, Zone* zone) {
770 updateCellPointers(zone, UpdatePhaseOne);
771 updateCellPointers(zone, UpdatePhaseTwo);
772 }
773
774 /*
775 * Update pointers to relocated cells in a single zone by doing a traversal of
776 * that zone's arenas and calling per-zone sweep hooks.
777 *
778 * The latter is necessary to update weak references which are not marked as
779 * part of the traversal.
780 */
781 void GCRuntime::updateZonePointersToRelocatedCells(Zone* zone) {
782 MOZ_ASSERT(!rt->isBeingDestroyed());
783 MOZ_ASSERT(zone->isGCCompacting());
784
785 AutoTouchingGrayThings tgt;
786
787 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::COMPACT_UPDATE);
788 MovingTracer trc(rt);
789
790 zone->fixupAfterMovingGC();
791 zone->fixupScriptMapsAfterMovingGC(&trc);
792
793 // Fixup compartment global pointers as these get accessed during marking.
794 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
795 comp->fixupAfterMovingGC(&trc);
796 }
797
798 zone->externalStringCache().purge();
799 zone->functionToStringCache().purge();
800 zone->shapeZone().purgeShapeCaches(rt->gcContext());
801 rt->caches().stringToAtomCache.purge();
802
803 // Iterate through all cells that can contain relocatable pointers to update
804 // them. Since updating each cell is independent we try to parallelize this
805 // as much as possible.
806 updateAllCellPointers(&trc, zone);
807
808 // Sweep everything to fix up weak pointers.
809 sweepZoneAfterCompacting(&trc, zone);
810
811 // Call callbacks to get the rest of the system to fixup other untraced
812 // pointers.
813 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
814 callWeakPointerCompartmentCallbacks(&trc, comp);
815 }
816 }
817
818 /*
819 * Update runtime-wide pointers to relocated cells.
820 */
821 void GCRuntime::updateRuntimePointersToRelocatedCells(AutoGCSession& session) {
822 MOZ_ASSERT(!rt->isBeingDestroyed());
823
824 gcstats::AutoPhase ap1(stats(), gcstats::PhaseKind::COMPACT_UPDATE);
825 MovingTracer trc(rt);
826
827 Zone::fixupAllCrossCompartmentWrappersAfterMovingGC(&trc);
828
829 rt->geckoProfiler().fixupStringsMapAfterMovingGC();
830
831 // Mark roots to update them.
832
833 traceRuntimeForMajorGC(&trc, session);
834
835 jit::UpdateJitActivationsForCompactingGC(rt);
836
837 {
838 gcstats::AutoPhase ap2(stats(), gcstats::PhaseKind::MARK_ROOTS);
839 DebugAPI::traceAllForMovingGC(&trc);
840 DebugAPI::traceCrossCompartmentEdges(&trc);
841
842 // Mark all gray roots.
843 traceEmbeddingGrayRoots(&trc);
844 Compartment::traceIncomingCrossCompartmentEdgesForZoneGC(
845 &trc, Compartment::GrayEdges);
846 }
847
848 // Sweep everything to fix up weak pointers.
849 jit::JitRuntime::TraceWeakJitcodeGlobalTable(rt, &trc);
850 for (JS::detail::WeakCacheBase* cache : rt->weakCaches()) {
851 cache->traceWeak(&trc, JS::detail::WeakCacheBase::DontLockStoreBuffer);
852 }
853
854 if (rt->hasJitRuntime() && rt->jitRuntime()->hasInterpreterEntryMap()) {
855 rt->jitRuntime()->getInterpreterEntryMap()->updateScriptsAfterMovingGC();
856 }
857
858 // Type inference may put more blocks here to free.
859 {
860 AutoLockHelperThreadState lock;
861 lifoBlocksToFree.ref().freeAll();
862 }
863
864 // Call callbacks to get the rest of the system to fixup other untraced
865 // pointers.
866 callWeakPointerZonesCallbacks(&trc);
867 }
868
869 void GCRuntime::clearRelocatedArenas(Arena* arenaList, JS::GCReason reason) {
870 AutoLockGC lock(this);
871 clearRelocatedArenasWithoutUnlocking(arenaList, reason, lock);
872 }
873
874 void GCRuntime::clearRelocatedArenasWithoutUnlocking(Arena* arenaList,
875 JS::GCReason reason,
876 const AutoLockGC& lock) {
877 // Clear the relocated arenas, now containing only forwarding pointers
878 while (arenaList) {
879 Arena* arena = arenaList;
880 arenaList = arenaList->next;
881
882 // Clear the mark bits
883 arena->unmarkAll();
884
885 // Mark arena as empty
886 arena->setAsFullyUnused();
887
888 #ifdef DEBUG
889 // The cell contents have been partially marked no access in RelocateCell,
890 // so we need to mark the region as undefined again so we can poison it.
891 SetMemCheckKind(reinterpret_cast<void*>(arena->thingsStart()),
892 arena->getThingsSpan(), MemCheckKind::MakeUndefined);
893 #endif
894
895 AlwaysPoison(reinterpret_cast<void*>(arena->thingsStart()),
896 JS_MOVED_TENURED_PATTERN, arena->getThingsSpan(),
897 MemCheckKind::MakeNoAccess);
898
899 // Don't count emptied arenas as being freed by the current GC:
900 // - if we purposely moved everything to new arenas, as that will already
901 // have allocated a similar number of arenas. (This only happens for
902 // collections triggered by GC zeal.)
903 // - if they were allocated since the start of the GC.
904 bool allArenasRelocated = ShouldRelocateAllArenas(reason);
905 bool updateRetainedSize = !allArenasRelocated && !arena->isNewlyCreated();
906 Zone* zone = arena->zone();
907 if (IsBufferAllocKind(arena->getAllocKind())) {
908 size_t usableBytes = ArenaSize - arena->getFirstThingOffset();
909 zone->mallocHeapSize.removeBytes(usableBytes, updateRetainedSize);
910 } else {
911 zone->gcHeapSize.removeBytes(ArenaSize, updateRetainedSize, heapSize);
912 }
913
914 // There is no atom marking bitmap index to free.
915 MOZ_ASSERT(!zone->isAtomsZone());
916
917 // Release the arena but don't return it to the chunk yet.
918 arena->release();
919 }
920 }
921
922 #ifdef DEBUG
923
924 // In debug mode we don't always release relocated arenas straight away.
925 // Sometimes protect them instead and hold onto them until the next GC sweep
926 // phase to catch any pointers to them that didn't get forwarded.
927
928 static inline bool CanProtectArenas() {
929 // On some systems the page size is larger than the size of an arena so we
930 // can't change the mapping permissions per arena.
931 return SystemPageSize() <= ArenaSize;
932 }
933
934 static inline bool ShouldProtectRelocatedArenas(JS::GCReason reason) {
935 // For zeal mode collections we don't release the relocated arenas
936 // immediately. Instead we protect them and keep them around until the next
937 // collection so we can catch any stray accesses to them.
938 return reason == JS::GCReason::DEBUG_GC && CanProtectArenas();
939 }
940
941 void GCRuntime::protectOrReleaseRelocatedArenas(Arena* arenaList,
942 JS::GCReason reason) {
943 if (ShouldProtectRelocatedArenas(reason)) {
944 protectAndHoldArenas(arenaList);
945 return;
946 }
947
948 releaseRelocatedArenas(arenaList);
949 }
950
951 void GCRuntime::protectAndHoldArenas(Arena* arenaList) {
952 for (Arena* arena = arenaList; arena;) {
953 MOZ_ASSERT(!arena->allocated());
954 Arena* next = arena->next;
955 if (!next) {
956 // Prepend to hold list before we protect the memory.
957 AutoLockGC lock(this);
958 arena->next = relocatedArenasToRelease;
959 relocatedArenasToRelease = arenaList;
960 }
961 ProtectPages(arena, ArenaSize);
962 arena = next;
963 }
964 }
965
966 void GCRuntime::unprotectHeldRelocatedArenas(const AutoLockGC& lock) {
967 for (Arena* arena = relocatedArenasToRelease; arena; arena = arena->next) {
968 UnprotectPages(arena, ArenaSize);
969 MOZ_ASSERT(!arena->allocated());
970 }
971 }
972
973 void GCRuntime::releaseHeldRelocatedArenas() {
974 AutoLockGC lock(this);
975 unprotectHeldRelocatedArenas(lock);
976 Arena* arenas = relocatedArenasToRelease;
977 relocatedArenasToRelease = nullptr;
978 releaseRelocatedArenasWithoutUnlocking(arenas, lock);
979 }
980
981 void GCRuntime::releaseHeldRelocatedArenasWithoutUnlocking(
982 const AutoLockGC& lock) {
983 unprotectHeldRelocatedArenas(lock);
984 releaseRelocatedArenasWithoutUnlocking(relocatedArenasToRelease, lock);
985 relocatedArenasToRelease = nullptr;
986 }
987
988 #endif
989
990 void GCRuntime::releaseRelocatedArenas(Arena* arenaList) {
991 AutoLockGC lock(this);
992 releaseRelocatedArenasWithoutUnlocking(arenaList, lock);
993 }
994
995 void GCRuntime::releaseRelocatedArenasWithoutUnlocking(Arena* arenaList,
996 const AutoLockGC& lock) {
997 // Release relocated arenas previously cleared with clearRelocatedArenas().
998 while (arenaList) {
999 Arena* arena = arenaList;
1000 arenaList = arenaList->next;
1001
1002 // We already updated the memory accounting so just call
1003 // Chunk::releaseArena.
1004 arena->chunk()->releaseArena(this, arena, lock);
1005 }
1006 }