Debian Codegraph @

js/src/gc/Verifier.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 #include "mozilla/Maybe.h"
8 #include "mozilla/Sprintf.h"
9
10 #include <algorithm>
11 #include <utility>
12
13 #ifdef MOZ_VALGRIND
14 # include <valgrind/memcheck.h>
15 #endif
16
17 #include "gc/GCInternals.h"
18 #include "gc/GCLock.h"
19 #include "gc/PublicIterators.h"
20 #include "gc/WeakMap.h"
21 #include "gc/Zone.h"
22 #include "js/friend/DumpFunctions.h" // js::DumpObject
23 #include "js/HashTable.h"
24 #include "vm/JSContext.h"
25
26 #include "gc/ArenaList-inl.h"
27 #include "gc/GC-inl.h"
28 #include "gc/Heap-inl.h"
29 #include "gc/Marking-inl.h"
30 #include "gc/PrivateIterators-inl.h"
31
32 using namespace js;
33 using namespace js::gc;
34
35 #ifdef JS_GC_ZEAL
36
37 /*
38 * Write barrier verification
39 *
40 * The next few functions are for write barrier verification.
41 *
42 * The VerifyBarriers function is a shorthand. It checks if a verification phase
43 * is currently running. If not, it starts one. Otherwise, it ends the current
44 * phase and starts a new one.
45 *
46 * The user can adjust the frequency of verifications, which causes
47 * VerifyBarriers to be a no-op all but one out of N calls. However, if the
48 * |always| parameter is true, it starts a new phase no matter what.
49 *
50 * Pre-Barrier Verifier:
51 * When StartVerifyBarriers is called, a snapshot is taken of all objects in
52 * the GC heap and saved in an explicit graph data structure. Later,
53 * EndVerifyBarriers traverses the heap again. Any pointer values that were in
54 * the snapshot and are no longer found must be marked; otherwise an assertion
55 * triggers. Note that we must not GC in between starting and finishing a
56 * verification phase.
57 */
58
59 struct EdgeValue {
60 JS::GCCellPtr thing;
61 const char* label;
62 };
63
64 struct VerifyNode {
65 JS::GCCellPtr thing;
66 uint32_t count = 0;
67 EdgeValue edges[1];
68 };
69
70 using NodeMap =
71 HashMap<Cell*, VerifyNode*, DefaultHasher<Cell*>, SystemAllocPolicy>;
72
73 /*
74 * The verifier data structures are simple. The entire graph is stored in a
75 * single block of memory. At the beginning is a VerifyNode for the root
76 * node. It is followed by a sequence of EdgeValues--the exact number is given
77 * in the node. After the edges come more nodes and their edges.
78 *
79 * The edgeptr and term fields are used to allocate out of the block of memory
80 * for the graph. If we run out of memory (i.e., if edgeptr goes beyond term),
81 * we just abandon the verification.
82 *
83 * The nodemap field is a hashtable that maps from the address of the GC thing
84 * to the VerifyNode that represents it.
85 */
86 class js::VerifyPreTracer final : public JS::CallbackTracer {
87 JS::AutoDisableGenerationalGC noggc;
88
89 void onChild(JS::GCCellPtr thing, const char* name) override;
90
91 public:
92 /* The gcNumber when the verification began. */
93 uint64_t number;
94
95 /* This counts up to gcZealFrequency to decide whether to verify. */
96 int count;
97
98 /* This graph represents the initial GC "snapshot". */
99 VerifyNode* curnode;
100 VerifyNode* root;
101 char* edgeptr;
102 char* term;
103 NodeMap nodemap;
104
105 explicit VerifyPreTracer(JSRuntime* rt)
106 : JS::CallbackTracer(rt, JS::TracerKind::Callback,
107 JS::WeakEdgeTraceAction::Skip),
108 noggc(rt->mainContextFromOwnThread()),
109 number(rt->gc.gcNumber()),
110 count(0),
111 curnode(nullptr),
112 root(nullptr),
113 edgeptr(nullptr),
114 term(nullptr) {
115 // We don't care about weak edges here. Since they are not marked they
116 // cannot cause the problem that the pre-write barrier protects against.
117 }
118
119 ~VerifyPreTracer() { js_free(root); }
120 };
121
122 inline bool IgnoreForPreBarrierVerifier(JSRuntime* runtime,
123 JS::GCCellPtr thing) {
124 // Skip things in other runtimes.
125 if (thing.asCell()->asTenured().runtimeFromAnyThread() != runtime) {
126 return true;
127 }
128
129 // Ignore buffers as these don't escape and are not barriered.
130 if (thing.kind() == JS::TraceKind::SmallBuffer) {
131 return true;
132 }
133
134 return false;
135 }
136
137 /*
138 * This function builds up the heap snapshot by adding edges to the current
139 * node.
140 */
141 void VerifyPreTracer::onChild(JS::GCCellPtr thing, const char* name) {
142 MOZ_ASSERT(!IsInsideNursery(thing.asCell()));
143
144 if (IgnoreForPreBarrierVerifier(runtime(), thing)) {
145 return;
146 }
147
148 edgeptr += sizeof(EdgeValue);
149 if (edgeptr >= term) {
150 edgeptr = term;
151 return;
152 }
153
154 VerifyNode* node = curnode;
155 uint32_t i = node->count;
156
157 node->edges[i].thing = thing;
158 node->edges[i].label = name;
159 node->count++;
160 }
161
162 static VerifyNode* MakeNode(VerifyPreTracer* trc, JS::GCCellPtr thing) {
163 NodeMap::AddPtr p = trc->nodemap.lookupForAdd(thing.asCell());
164 if (!p) {
165 VerifyNode* node = (VerifyNode*)trc->edgeptr;
166 trc->edgeptr += sizeof(VerifyNode) - sizeof(EdgeValue);
167 if (trc->edgeptr >= trc->term) {
168 trc->edgeptr = trc->term;
169 return nullptr;
170 }
171
172 node->thing = thing;
173 node->count = 0;
174 if (!trc->nodemap.add(p, thing.asCell(), node)) {
175 trc->edgeptr = trc->term;
176 return nullptr;
177 }
178
179 return node;
180 }
181 return nullptr;
182 }
183
184 static VerifyNode* NextNode(VerifyNode* node) {
185 if (node->count == 0) {
186 return (VerifyNode*)((char*)node + sizeof(VerifyNode) - sizeof(EdgeValue));
187 }
188
189 return (VerifyNode*)((char*)node + sizeof(VerifyNode) +
190 sizeof(EdgeValue) * (node->count - 1));
191 }
192
193 template <typename ZonesIterT>
194 static void ClearMarkBits(GCRuntime* gc) {
195 // This does not clear the mark bits for permanent atoms, whose arenas are
196 // removed from the arena lists by GCRuntime::freezePermanentAtoms.
197
198 for (ZonesIterT zone(gc); !zone.done(); zone.next()) {
199 for (auto kind : AllAllocKinds()) {
200 for (ArenaIter arena(zone, kind); !arena.done(); arena.next()) {
201 arena->unmarkAll();
202 }
203 }
204 }
205 }
206
207 void gc::GCRuntime::startVerifyPreBarriers() {
208 if (verifyPreData || isIncrementalGCInProgress()) {
209 return;
210 }
211
212 JSContext* cx = rt->mainContextFromOwnThread();
213 MOZ_ASSERT(!cx->suppressGC);
214
215 number++;
216
217 VerifyPreTracer* trc = js_new<VerifyPreTracer>(rt);
218 if (!trc) {
219 return;
220 }
221
222 AutoPrepareForTracing prep(cx);
223
224 # ifdef DEBUG
225 for (AllZonesIter zone(this); !zone.done(); zone.next()) {
226 zone->bufferAllocator.checkGCStateNotInUse();
227 }
228 # endif
229
230 ClearMarkBits<AllZonesIter>(this);
231
232 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::TRACE_HEAP);
233
234 const size_t size = 64 * 1024 * 1024;
235 trc->root = (VerifyNode*)js_malloc(size);
236 if (!trc->root) {
237 goto oom;
238 }
239 trc->edgeptr = (char*)trc->root;
240 trc->term = trc->edgeptr + size;
241
242 /* Create the root node. */
243 trc->curnode = MakeNode(trc, JS::GCCellPtr());
244
245 MOZ_ASSERT(incrementalState == State::NotActive);
246 incrementalState = State::MarkRoots;
247
248 /* Make all the roots be edges emanating from the root node. */
249 traceRuntime(trc, prep);
250
251 VerifyNode* node;
252 node = trc->curnode;
253 if (trc->edgeptr == trc->term) {
254 goto oom;
255 }
256
257 /* For each edge, make a node for it if one doesn't already exist. */
258 while ((char*)node < trc->edgeptr) {
259 for (uint32_t i = 0; i < node->count; i++) {
260 EdgeValue& e = node->edges[i];
261 VerifyNode* child = MakeNode(trc, e.thing);
262 if (child) {
263 trc->curnode = child;
264 JS::TraceChildren(trc, e.thing);
265 }
266 if (trc->edgeptr == trc->term) {
267 goto oom;
268 }
269 }
270
271 node = NextNode(node);
272 }
273
274 verifyPreData = trc;
275 incrementalState = State::Mark;
276 haveAllImplicitEdges_ = true;
277 marker().start();
278
279 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
280 zone->changeGCState(Zone::NoGC, Zone::VerifyPreBarriers);
281 zone->setNeedsIncrementalBarrier(true);
282 zone->arenas.clearFreeLists();
283 }
284
285 return;
286
287 oom:
288 incrementalState = State::NotActive;
289 js_delete(trc);
290 verifyPreData = nullptr;
291 }
292
293 static bool IsMarkedOrAllocated(TenuredCell* cell) {
294 return cell->isMarkedAny();
295 }
296
297 struct CheckEdgeTracer final : public JS::CallbackTracer {
298 VerifyNode* node;
299 explicit CheckEdgeTracer(JSRuntime* rt)
300 : JS::CallbackTracer(rt), node(nullptr) {}
301 void onChild(JS::GCCellPtr thing, const char* name) override;
302 };
303
304 static const uint32_t MAX_VERIFIER_EDGES = 1000;
305
306 /*
307 * This function is called by EndVerifyBarriers for every heap edge. If the edge
308 * already existed in the original snapshot, we "cancel it out" by overwriting
309 * it with nullptr. EndVerifyBarriers later asserts that the remaining
310 * non-nullptr edges (i.e., the ones from the original snapshot that must have
311 * been modified) must point to marked objects.
312 */
313 void CheckEdgeTracer::onChild(JS::GCCellPtr thing, const char* name) {
314 if (IgnoreForPreBarrierVerifier(runtime(), thing)) {
315 return;
316 }
317
318 /* Avoid n^2 behavior. */
319 if (node->count > MAX_VERIFIER_EDGES) {
320 return;
321 }
322
323 for (uint32_t i = 0; i < node->count; i++) {
324 if (node->edges[i].thing == thing) {
325 node->edges[i].thing = JS::GCCellPtr();
326 return;
327 }
328 }
329 }
330
331 static bool IsMarkedOrAllocated(const EdgeValue& edge) {
332 if (!edge.thing || IsMarkedOrAllocated(&edge.thing.asCell()->asTenured())) {
333 return true;
334 }
335
336 // Permanent atoms and well-known symbols aren't marked during graph
337 // traversal.
338 if (edge.thing.is<JSString>() &&
339 edge.thing.as<JSString>().isPermanentAtom()) {
340 return true;
341 }
342 if (edge.thing.is<JS::Symbol>() &&
343 edge.thing.as<JS::Symbol>().isWellKnownSymbol()) {
344 return true;
345 }
346
347 return false;
348 }
349
350 void gc::GCRuntime::endVerifyPreBarriers() {
351 VerifyPreTracer* trc = verifyPreData;
352
353 if (!trc) {
354 return;
355 }
356
357 MOZ_ASSERT(!JS::IsGenerationalGCEnabled(rt));
358
359 // Now that barrier marking has finished, prepare the heap to allow this
360 // method to trace cells and discover their outgoing edges.
361 AutoPrepareForTracing prep(rt->mainContextFromOwnThread());
362
363 bool compartmentCreated = false;
364
365 /* We need to disable barriers before tracing, which may invoke barriers. */
366 for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
367 if (zone->isVerifyingPreBarriers()) {
368 zone->changeGCState(Zone::VerifyPreBarriers, Zone::NoGC);
369 } else {
370 compartmentCreated = true;
371 }
372
373 MOZ_ASSERT(!zone->wasGCStarted());
374 MOZ_ASSERT(!zone->needsIncrementalBarrier());
375 }
376
377 verifyPreData = nullptr;
378 MOZ_ASSERT(incrementalState == State::Mark);
379 incrementalState = State::NotActive;
380
381 if (!compartmentCreated) {
382 CheckEdgeTracer cetrc(rt);
383
384 /* Start after the roots. */
385 VerifyNode* node = NextNode(trc->root);
386 while ((char*)node < trc->edgeptr) {
387 cetrc.node = node;
388 JS::TraceChildren(&cetrc, node->thing);
389
390 if (node->count <= MAX_VERIFIER_EDGES) {
391 for (uint32_t i = 0; i < node->count; i++) {
392 EdgeValue& edge = node->edges[i];
393 if (!IsMarkedOrAllocated(edge)) {
394 char msgbuf[1024];
395 SprintfLiteral(
396 msgbuf,
397 "[barrier verifier] Unmarked edge: %s %p '%s' edge to %s %p",
398 JS::GCTraceKindToAscii(node->thing.kind()),
399 node->thing.asCell(), edge.label,
400 JS::GCTraceKindToAscii(edge.thing.kind()), edge.thing.asCell());
401 MOZ_ReportAssertionFailure(msgbuf, __FILE__, __LINE__);
402 MOZ_CRASH();
403 }
404 }
405 }
406
407 node = NextNode(node);
408 }
409 }
410
411 marker().reset();
412 resetDelayedMarking();
413
414 for (AllZonesIter zone(this); !zone.done(); zone.next()) {
415 zone->bufferAllocator.clearMarkStateAfterBarrierVerification();
416 }
417
418 js_delete(trc);
419 }
420
421 /*** Barrier Verifier Scheduling ***/
422
423 void gc::VerifyBarriers(JSRuntime* rt, VerifierType type) {
424 if (type == PreBarrierVerifier) {
425 rt->gc.verifyPreBarriers();
426 }
427
428 if (type == PostBarrierVerifier) {
429 rt->gc.verifyPostBarriers();
430 }
431 }
432
433 void gc::GCRuntime::verifyPreBarriers() {
434 if (verifyPreData) {
435 endVerifyPreBarriers();
436 } else {
437 startVerifyPreBarriers();
438 }
439 }
440
441 void gc::GCRuntime::verifyPostBarriers() {
442 if (hasZealMode(ZealMode::VerifierPost)) {
443 clearZealMode(ZealMode::VerifierPost);
444 } else {
445 setZeal(uint8_t(ZealMode::VerifierPost), JS::ShellDefaultGCZealFrequency);
446 }
447 }
448
449 void gc::GCRuntime::maybeVerifyPreBarriers(bool always) {
450 if (!hasZealMode(ZealMode::VerifierPre)) {
451 return;
452 }
453
454 if (rt->mainContextFromOwnThread()->suppressGC) {
455 return;
456 }
457
458 if (verifyPreData) {
459 if (++verifyPreData->count < zealFrequency && !always) {
460 return;
461 }
462
463 endVerifyPreBarriers();
464 }
465
466 startVerifyPreBarriers();
467 }
468
469 void js::gc::MaybeVerifyBarriers(JSContext* cx, bool always) {
470 GCRuntime* gc = &cx->runtime()->gc;
471 gc->maybeVerifyPreBarriers(always);
472 }
473
474 void js::gc::GCRuntime::finishVerifier() {
475 if (verifyPreData) {
476 js_delete(verifyPreData.ref());
477 verifyPreData = nullptr;
478 }
479 }
480
481 struct GCChunkHasher {
482 using Lookup = gc::ArenaChunk*;
483
484 /*
485 * Strip zeros for better distribution after multiplying by the golden
486 * ratio.
487 */
488 static HashNumber hash(gc::ArenaChunk* chunk) {
489 MOZ_ASSERT(!(uintptr_t(chunk) & gc::ChunkMask));
490 return HashNumber(uintptr_t(chunk) >> gc::ChunkShift);
491 }
492
493 static bool match(gc::ArenaChunk* k, gc::ArenaChunk* l) {
494 MOZ_ASSERT(!(uintptr_t(k) & gc::ChunkMask));
495 MOZ_ASSERT(!(uintptr_t(l) & gc::ChunkMask));
496 return k == l;
497 }
498 };
499
500 class js::gc::MarkingValidator {
501 public:
502 explicit MarkingValidator(GCRuntime* gc);
503 void nonIncrementalMark(AutoGCSession& session);
504 void validate();
505
506 private:
507 GCRuntime* gc;
508 bool initialized;
509
510 using BitmapMap = HashMap<ArenaChunk*, UniquePtr<ChunkMarkBitmap>,
511 GCChunkHasher, SystemAllocPolicy>;
512 BitmapMap map;
513 };
514
515 js::gc::MarkingValidator::MarkingValidator(GCRuntime* gc)
516 : gc(gc), initialized(false) {}
517
518 void js::gc::MarkingValidator::nonIncrementalMark(AutoGCSession& session) {
519 /*
520 * Perform a non-incremental mark for all collecting zones and record
521 * the results for later comparison.
522 */
523
524 GCMarker* gcmarker = &gc->marker();
525
526 MOZ_ASSERT(!gcmarker->isWeakMarking());
527
528 /* We require that the nursery is empty at the start of collection. */
529 MOZ_ASSERT(gc->nursery().isEmpty());
530
531 /* Wait for off-thread parsing which can allocate. */
532 WaitForAllHelperThreads();
533
534 gc->waitBackgroundAllocEnd();
535 gc->waitBackgroundSweepEnd();
536
537 /* Save existing mark bits. */
538 {
539 AutoLockGC lock(gc);
540 for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done();
541 chunk.next()) {
542 // Bug 1842582: Allocate mark bit buffer in two stages to avoid alignment
543 // restriction which we currently can't support.
544 void* buffer = js_malloc(sizeof(ChunkMarkBitmap));
545 if (!buffer) {
546 return;
547 }
548 UniquePtr<ChunkMarkBitmap> entry(new (buffer) ChunkMarkBitmap);
549 entry->copyFrom(chunk->markBits);
550 if (!map.putNew(chunk, std::move(entry))) {
551 return;
552 }
553 }
554 }
555
556 /*
557 * Temporarily clear the weakmaps' mark flags for the compartments we are
558 * collecting.
559 */
560
561 WeakMapColors markedWeakMaps;
562
563 /*
564 * For saving, smush all of the keys into one big table and split them back
565 * up into per-zone tables when restoring.
566 */
567 gc::EphemeronEdgeTable savedEphemeronEdges;
568
569 for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
570 if (!WeakMapBase::saveZoneMarkedWeakMaps(zone, markedWeakMaps)) {
571 return;
572 }
573
574 AutoEnterOOMUnsafeRegion oomUnsafe;
575 for (auto r = zone->gcEphemeronEdges().all(); !r.empty(); r.popFront()) {
576 MOZ_ASSERT(r.front().key()->asTenured().zone() == zone);
577 if (!savedEphemeronEdges.putNew(r.front().key(),
578 std::move(r.front().value()))) {
579 oomUnsafe.crash("saving weak keys table for validator");
580 }
581 }
582
583 zone->gcEphemeronEdges().clearAndCompact();
584 }
585
586 # ifdef DEBUG
587 // The test mark queue can cause spurious differences if the non-incremental
588 // marking for validation happens before the full queue has been processed,
589 // since the later part of the queue may mark things during sweeping. Disable
590 // validation if there is anything left in the queue at this point.
591 if (gc->testMarkQueueRemaining() > 0) {
592 return;
593 }
594 # endif
595
596 /*
597 * After this point, the function should run to completion, so we shouldn't
598 * do anything fallible.
599 */
600 initialized = true;
601
602 /* Re-do all the marking, but non-incrementally. */
603 js::gc::State state = gc->incrementalState;
604 gc->incrementalState = State::MarkRoots;
605
606 {
607 gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::PREPARE);
608
609 {
610 gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::UNMARK);
611
612 for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
613 WeakMapBase::unmarkZone(zone);
614 }
615
616 MOZ_ASSERT(gcmarker->isDrained());
617
618 ClearMarkBits<GCZonesIter>(gc);
619 }
620 }
621
622 {
623 gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::MARK);
624
625 gc->traceRuntimeForMajorGC(gcmarker->tracer(), session);
626
627 gc->incrementalState = State::Mark;
628 gc->drainMarkStack();
629 }
630
631 gc->incrementalState = State::Sweep;
632 {
633 gcstats::AutoPhase ap1(gc->stats(), gcstats::PhaseKind::SWEEP);
634 gcstats::AutoPhase ap2(gc->stats(), gcstats::PhaseKind::MARK);
635
636 gc->markAllWeakReferences();
637
638 /* Update zone state for gray marking. */
639 for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
640 zone->changeGCState(zone->initialMarkingState(), Zone::MarkBlackAndGray);
641 }
642
643 /*
644 * markAllGrayReferences may mark both gray and black, so it manages the
645 * mark color internally.
646 */
647 gc->markAllGrayReferences(gcstats::PhaseKind::MARK_GRAY);
648
649 AutoSetMarkColor setColorGray(*gcmarker, MarkColor::Gray);
650 gc->markAllWeakReferences();
651
652 /* Restore zone state. */
653 for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
654 zone->changeGCState(Zone::MarkBlackAndGray, zone->initialMarkingState());
655 }
656 MOZ_ASSERT(gc->marker().isDrained());
657 }
658
659 /* Take a copy of the non-incremental mark state and restore the original. */
660 {
661 AutoLockGC lock(gc);
662 for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done();
663 chunk.next()) {
664 ChunkMarkBitmap* bitmap = &chunk->markBits;
665 auto ptr = map.lookup(chunk);
666 MOZ_RELEASE_ASSERT(ptr, "Chunk not found in map");
667 ChunkMarkBitmap* entry = ptr->value().get();
668 ChunkMarkBitmap temp;
669 temp.copyFrom(*entry);
670 entry->copyFrom(*bitmap);
671 bitmap->copyFrom(temp);
672 }
673 }
674
675 for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
676 WeakMapBase::unmarkZone(zone);
677 MOZ_ASSERT(zone->gcEphemeronEdges().empty(), "unmarkZone clears the map");
678 }
679
680 WeakMapBase::restoreMarkedWeakMaps(markedWeakMaps);
681
682 for (auto r = savedEphemeronEdges.all(); !r.empty(); r.popFront()) {
683 AutoEnterOOMUnsafeRegion oomUnsafe;
684 Zone* zone = r.front().key()->asTenured().zone();
685 if (!zone->gcEphemeronEdges().putNew(r.front().key(),
686 std::move(r.front().value()))) {
687 oomUnsafe.crash("restoring weak keys table for validator");
688 }
689 }
690
691 # ifdef DEBUG
692 MOZ_ASSERT(gc->testMarkQueueRemaining() == 0);
693 MOZ_ASSERT(gc->queueMarkColor.isNothing());
694 # endif
695
696 gc->incrementalState = state;
697 }
698
699 void js::gc::MarkingValidator::validate() {
700 /*
701 * Validates the incremental marking for a single compartment by comparing
702 * the mark bits to those previously recorded for a non-incremental mark.
703 */
704
705 if (!initialized) {
706 return;
707 }
708
709 MOZ_ASSERT(!gc->marker().isWeakMarking());
710
711 gc->waitBackgroundSweepEnd();
712
713 bool ok = true;
714 AutoLockGC lock(gc->rt);
715 for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done(); chunk.next()) {
716 BitmapMap::Ptr ptr = map.lookup(chunk);
717 if (!ptr) {
718 continue; /* Allocated after we did the non-incremental mark. */
719 }
720
721 ChunkMarkBitmap* bitmap = ptr->value().get();
722 ChunkMarkBitmap* incBitmap = &chunk->markBits;
723
724 for (size_t i = 0; i < ArenasPerChunk; i++) {
725 size_t pageIndex = ArenaChunk::arenaToPageIndex(i);
726 if (chunk->decommittedPages[pageIndex]) {
727 continue;
728 }
729 Arena* arena = &chunk->arenas[i];
730 if (!arena->allocated()) {
731 continue;
732 }
733 if (!arena->zone()->isGCSweeping()) {
734 continue;
735 }
736
737 AllocKind kind = arena->getAllocKind();
738 uintptr_t thing = arena->thingsStart();
739 uintptr_t end = arena->thingsEnd();
740 while (thing < end) {
741 auto* cell = reinterpret_cast<TenuredCell*>(thing);
742
743 /*
744 * If a non-incremental GC wouldn't have collected a cell, then an
745 * incremental GC should not collect it either. However incremental
746 * marking is conservative and is allowed to mark things that
747 * non-incremental marking would not have marked.
748 *
749 * Further, incremental marking should not result in a cell that is
750 * "less marked" than non-incremental marking. For example where
751 * non-incremental marking would have marked a cell black incremental
752 * marking is not allowed to mark it gray, since the cycle collector
753 * could then consider paths through it to be part of garbage
754 * cycles. It's OK for a cell that would have been marked gray by
755 * non-incremental marking to be marked black by incremental marking.
756 *
757 * It's OK for a cell that would not be marked by non-incremental
758 * marking to end up gray. Since the cell is unreachable according to
759 * the non-incremental marking then the cycle collector will not find
760 * it. This can happen when a barrier marks a weak map key black and the
761 * map is gray, resulting in the value being marked gray.
762 *
763 * In summary:
764 *
765 * Non-incremental Incremental: Outcome:
766 * result: result:
767 *
768 * White White OK
769 * Gray OK, conservative
770 * Black OK, conservative
771 * Gray White Fail
772 * Gray OK
773 * Black OK, conservative
774 * Black White Fail
775 * Gray Fail
776 * Black OK
777 */
778
779 CellColor incColor = TenuredCell::getColor(incBitmap, cell);
780 CellColor nonIncColor = TenuredCell::getColor(bitmap, cell);
781 if (incColor < nonIncColor) {
782 ok = false;
783 fprintf(stderr,
784 "%p: cell was marked %s, but would be marked %s by "
785 "non-incremental marking\n",
786 cell, CellColorName(incColor), CellColorName(nonIncColor));
787 # ifdef DEBUG
788 cell->dump();
789 fprintf(stderr, "\n");
790 # endif
791 }
792
793 thing += Arena::thingSize(kind);
794 }
795 }
796 }
797
798 MOZ_RELEASE_ASSERT(ok, "Incremental marking verification failed");
799 }
800
801 void GCRuntime::computeNonIncrementalMarkingForValidation(
802 AutoGCSession& session) {
803 MOZ_ASSERT(!markingValidator);
804 if (isIncremental && hasZealMode(ZealMode::IncrementalMarkingValidator)) {
805 markingValidator = js_new<MarkingValidator>(this);
806 }
807 if (markingValidator) {
808 markingValidator->nonIncrementalMark(session);
809 }
810 }
811
812 void GCRuntime::validateIncrementalMarking() {
813 if (markingValidator) {
814 markingValidator->validate();
815 }
816 }
817
818 void GCRuntime::finishMarkingValidation() {
819 js_delete(markingValidator.ref());
820 markingValidator = nullptr;
821 }
822
823 #endif /* JS_GC_ZEAL */
824
825 #if defined(JS_GC_ZEAL) || defined(DEBUG)
826
827 class HeapCheckTracerBase : public JS::CallbackTracer {
828 public:
829 explicit HeapCheckTracerBase(JSRuntime* rt, JS::TraceOptions options);
830 bool traceHeap(AutoHeapSession& session);
831 virtual bool checkCell(Cell* cell, const char* name) = 0;
832
833 protected:
834 void dumpCellInfo(Cell* cell);
835 void dumpCellPath(const char* name);
836
837 Cell* parentCell() {
838 return parentIndex == -1 ? nullptr : stack[parentIndex].thing.asCell();
839 }
840
841 size_t failures;
842
843 private:
844 void onChild(JS::GCCellPtr thing, const char* name) override;
845
846 struct WorkItem {
847 WorkItem(JS::GCCellPtr thing, const char* name, int parentIndex)
848 : thing(thing),
849 name(name),
850 parentIndex(parentIndex),
851 processed(false) {}
852
853 JS::GCCellPtr thing;
854 const char* name;
855 int parentIndex;
856 bool processed;
857 };
858
859 JSRuntime* rt;
860 bool oom;
861 HashSet<Cell*, DefaultHasher<Cell*>, SystemAllocPolicy> visited;
862 Vector<WorkItem, 0, SystemAllocPolicy> stack;
863 int parentIndex;
864 };
865
866 HeapCheckTracerBase::HeapCheckTracerBase(JSRuntime* rt,
867 JS::TraceOptions options)
868 : CallbackTracer(rt, JS::TracerKind::HeapCheck, options),
869 failures(0),
870 rt(rt),
871 oom(false),
872 parentIndex(-1) {}
873
874 void HeapCheckTracerBase::onChild(JS::GCCellPtr thing, const char* name) {
875 Cell* cell = thing.asCell();
876 if (visited.lookup(cell)) {
877 return;
878 }
879
880 if (!visited.put(cell)) {
881 oom = true;
882 return;
883 }
884
885 if (!checkCell(cell, name)) {
886 // Don't trace through known bad cell.
887 return;
888 }
889
890 // Don't trace into GC things owned by another runtime.
891 if (cell->runtimeFromAnyThread() != rt) {
892 return;
893 }
894
895 WorkItem item(thing, name, parentIndex);
896 if (!stack.append(item)) {
897 oom = true;
898 }
899 }
900
901 bool HeapCheckTracerBase::traceHeap(AutoHeapSession& session) {
902 // The analysis thinks that traceRuntime might GC by calling a GC callback.
903 JS::AutoSuppressGCAnalysis nogc;
904 if (!rt->isBeingDestroyed()) {
905 rt->gc.traceRuntime(this, session);
906 }
907
908 while (!stack.empty() && !oom) {
909 WorkItem item = stack.back();
910 if (item.processed) {
911 stack.popBack();
912 } else {
913 MOZ_ASSERT(stack.length() <= INT_MAX);
914 parentIndex = int(stack.length()) - 1;
915 stack.back().processed = true;
916 TraceChildren(this, item.thing);
917 }
918 }
919
920 return !oom;
921 }
922
923 void HeapCheckTracerBase::dumpCellInfo(Cell* cell) {
924 auto kind = cell->getTraceKind();
925 JSObject* obj =
926 kind == JS::TraceKind::Object ? static_cast<JSObject*>(cell) : nullptr;
927
928 fprintf(stderr, "%s %s", CellColorName(cell->color()),
929 GCTraceKindToAscii(kind));
930 if (obj) {
931 fprintf(stderr, " %s", obj->getClass()->name);
932 }
933 fprintf(stderr, " %p", cell);
934 if (obj) {
935 fprintf(stderr, " (compartment %p)", obj->compartment());
936 }
937 }
938
939 void HeapCheckTracerBase::dumpCellPath(const char* name) {
940 for (int index = parentIndex; index != -1; index = stack[index].parentIndex) {
941 const WorkItem& parent = stack[index];
942 Cell* cell = parent.thing.asCell();
943 fprintf(stderr, " from ");
944 dumpCellInfo(cell);
945 fprintf(stderr, " %s edge\n", name);
946 name = parent.name;
947 }
948 fprintf(stderr, " from root %s\n", name);
949 }
950
951 class CheckHeapTracer final : public HeapCheckTracerBase {
952 public:
953 enum GCType { Moving, NonMoving, VerifyPostBarriers };
954
955 explicit CheckHeapTracer(JSRuntime* rt, GCType type);
956 void check(AutoHeapSession& session);
957
958 private:
959 bool checkCell(Cell* cell, const char* name) override;
960 bool cellIsValid(Cell* cell);
961 GCType gcType;
962 };
963
964 CheckHeapTracer::CheckHeapTracer(JSRuntime* rt, GCType type)
965 : HeapCheckTracerBase(rt, JS::WeakMapTraceAction::TraceKeysAndValues),
966 gcType(type) {}
967
968 inline static bool IsValidGCThingPointer(Cell* cell) {
969 return (uintptr_t(cell) & CellAlignMask) == 0;
970 }
971
972 bool CheckHeapTracer::checkCell(Cell* cell, const char* name) {
973 if (cellIsValid(cell)) {
974 return true;
975 }
976
977 failures++;
978 fprintf(stderr, "Bad pointer %p\n", cell);
979 dumpCellPath(name);
980 return false;
981 }
982
983 bool CheckHeapTracer::cellIsValid(Cell* cell) {
984 if (!IsValidGCThingPointer(cell)) {
985 return false;
986 }
987
988 if (gcType == GCType::Moving) {
989 return IsGCThingValidAfterMovingGC(cell);
990 }
991
992 if (gcType == GCType::NonMoving) {
993 return !cell->isForwarded();
994 }
995
996 MOZ_ASSERT(gcType == GCType::VerifyPostBarriers);
997
998 // No reachable Cell* should be in the collected part of the nursery.
999 if (runtime()->gc.nursery().inCollectedRegion(cell)) {
1000 return false;
1001 }
1002
1003 // String data should also not be in the collected part of nursery.
1004 if (cell->is<JSString>() && cell->as<JSString>()->isLinear()) {
1005 if (cell->as<JSString>()->asLinear().hasCharsInCollectedNurseryRegion()) {
1006 return false;
1007 }
1008 }
1009
1010 return true;
1011 }
1012
1013 void CheckHeapTracer::check(AutoHeapSession& session) {
1014 if (!traceHeap(session)) {
1015 return;
1016 }
1017
1018 if (failures) {
1019 fprintf(stderr, "Heap check: %zu failure(s)\n", failures);
1020 }
1021 MOZ_RELEASE_ASSERT(failures == 0);
1022 }
1023
1024 void js::gc::CheckHeapAfterGC(JSRuntime* rt) {
1025 MOZ_ASSERT(!rt->gc.isBackgroundDecommitting());
1026
1027 AutoTraceSession session(rt);
1028 CheckHeapTracer::GCType gcType;
1029
1030 if (rt->gc.nursery().isEmpty()) {
1031 gcType = CheckHeapTracer::GCType::Moving;
1032 } else {
1033 gcType = CheckHeapTracer::GCType::NonMoving;
1034 }
1035
1036 CheckHeapTracer tracer(rt, gcType);
1037 tracer.check(session);
1038 }
1039
1040 class CheckGrayMarkingTracer final : public HeapCheckTracerBase {
1041 public:
1042 explicit CheckGrayMarkingTracer(JSRuntime* rt);
1043 bool check(AutoHeapSession& session);
1044
1045 private:
1046 bool checkCell(Cell* cell, const char* name) override;
1047 bool isBlackToGrayEdge(Cell* parent, Cell* child);
1048 };
1049
1050 CheckGrayMarkingTracer::CheckGrayMarkingTracer(JSRuntime* rt)
1051 : HeapCheckTracerBase(rt, JS::TraceOptions(JS::WeakMapTraceAction::Skip,
1052 JS::WeakEdgeTraceAction::Skip)) {
1053 // Weak gray->black edges are allowed.
1054 }
1055
1056 bool CheckGrayMarkingTracer::checkCell(Cell* cell, const char* name) {
1057 Cell* parent = parentCell();
1058 if (!parent) {
1059 return true;
1060 }
1061
1062 if (!isBlackToGrayEdge(parent, cell)) {
1063 return true;
1064 }
1065
1066 failures++;
1067
1068 fprintf(stderr, "Found black to gray edge to ");
1069 dumpCellInfo(cell);
1070 fprintf(stderr, "\n");
1071 dumpCellPath(name);
1072
1073 # ifdef DEBUG
1074 if (parent->is<JSObject>()) {
1075 fprintf(stderr, "\nSource: ");
1076 DumpObject(parent->as<JSObject>(), stderr);
1077 }
1078 if (cell->is<JSObject>()) {
1079 fprintf(stderr, "\nTarget: ");
1080 DumpObject(cell->as<JSObject>(), stderr);
1081 }
1082 # endif
1083
1084 return false;
1085 }
1086
1087 bool CheckGrayMarkingTracer::isBlackToGrayEdge(Cell* parent, Cell* child) {
1088 return parent->isMarkedBlack() && child->isMarkedGray();
1089 }
1090
1091 bool CheckGrayMarkingTracer::check(AutoHeapSession& session) {
1092 if (!traceHeap(session)) {
1093 return true; // Ignore failure.
1094 }
1095
1096 return failures == 0;
1097 }
1098
1099 JS_PUBLIC_API bool js::CheckGrayMarkingState(JSRuntime* rt) {
1100 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
1101 MOZ_ASSERT(!rt->gc.isIncrementalGCInProgress());
1102 if (!rt->gc.areGrayBitsValid()) {
1103 return true;
1104 }
1105
1106 gcstats::AutoPhase ap(rt->gc.stats(), gcstats::PhaseKind::TRACE_HEAP);
1107 AutoTraceSession session(rt);
1108 CheckGrayMarkingTracer tracer(rt);
1109
1110 return tracer.check(session);
1111 }
1112
1113 static JSObject* MaybeGetDelegate(Cell* cell) {
1114 if (!cell->is<JSObject>()) {
1115 return nullptr;
1116 }
1117
1118 JSObject* object = cell->as<JSObject>();
1119 return js::UncheckedUnwrapWithoutExpose(object);
1120 }
1121
1122 bool js::gc::CheckWeakMapEntryMarking(const WeakMapBase* map, Cell* key,
1123 Cell* value) {
1124 bool ok = true;
1125
1126 Zone* zone = map->zone();
1127 MOZ_ASSERT(CurrentThreadCanAccessZone(zone));
1128 MOZ_ASSERT(zone->isGCMarking());
1129
1130 JSObject* object = map->memberOf;
1131 MOZ_ASSERT_IF(object, object->zone() == zone);
1132
1133 // Debugger weak maps can have keys in different zones.
1134 Zone* keyZone = key->zoneFromAnyThread();
1135 MOZ_ASSERT_IF(!map->allowKeysInOtherZones(),
1136 keyZone == zone || keyZone->isAtomsZone());
1137
1138 Zone* valueZone = value->zoneFromAnyThread();
1139 MOZ_ASSERT(valueZone == zone || valueZone->isAtomsZone());
1140
1141 if (object && object->color() != map->mapColor()) {
1142 fprintf(stderr, "WeakMap object is marked differently to the map\n");
1143 fprintf(stderr, "(map %p is %s, object %p is %s)\n", map,
1144 CellColorName(map->mapColor()), object,
1145 CellColorName(object->color()));
1146 ok = false;
1147 }
1148
1149 // Values belonging to other runtimes or in uncollected zones are treated as
1150 // black.
1151 JSRuntime* mapRuntime = zone->runtimeFromAnyThread();
1152 auto effectiveColor = [=](Cell* cell, Zone* cellZone) -> CellColor {
1153 if (cell->runtimeFromAnyThread() != mapRuntime) {
1154 return CellColor::Black;
1155 }
1156 if (cellZone->isGCMarkingOrSweeping()) {
1157 return cell->color();
1158 }
1159 return CellColor::Black;
1160 };
1161
1162 CellColor valueColor = effectiveColor(value, valueZone);
1163 CellColor keyColor = effectiveColor(key, keyZone);
1164
1165 if (valueColor < std::min(map->mapColor(), keyColor)) {
1166 fprintf(stderr, "WeakMap value is less marked than map and key\n");
1167 fprintf(stderr, "(map %p is %s, key %p is %s, value %p is %s)\n", map,
1168 CellColorName(map->mapColor()), key, CellColorName(keyColor), value,
1169 CellColorName(valueColor));
1170 # ifdef DEBUG
1171 fprintf(stderr, "Key:\n");
1172 key->dump();
1173 if (auto* delegate = MaybeGetDelegate(key); delegate) {
1174 fprintf(stderr, "Delegate:\n");
1175 delegate->dump();
1176 }
1177 fprintf(stderr, "Value:\n");
1178 value->dump();
1179 # endif
1180
1181 ok = false;
1182 }
1183
1184 JSObject* delegate = MaybeGetDelegate(key);
1185 if (!delegate) {
1186 return ok;
1187 }
1188
1189 CellColor delegateColor = effectiveColor(delegate, delegate->zone());
1190 if (keyColor < std::min(map->mapColor(), delegateColor)) {
1191 fprintf(stderr, "WeakMap key is less marked than map or delegate\n");
1192 fprintf(stderr, "(map %p is %s, delegate %p is %s, key %p is %s)\n", map,
1193 CellColorName(map->mapColor()), delegate,
1194 CellColorName(delegateColor), key, CellColorName(keyColor));
1195 ok = false;
1196 }
1197
1198 return ok;
1199 }
1200
1201 #endif // defined(JS_GC_ZEAL) || defined(DEBUG)
1202
1203 #ifdef JS_GC_ZEAL
1204 void GCRuntime::verifyPostBarriers(AutoHeapSession& session) {
1205 // Walk the entire heap to check for pointers into the nursery that should
1206 // have been tracked by the store buffer.
1207 CheckHeapTracer tracer(rt, CheckHeapTracer::GCType::VerifyPostBarriers);
1208 tracer.check(session);
1209 }
1210
1211 void GCRuntime::checkHeapBeforeMinorGC(AutoHeapSession& session) {
1212 // Similar to verifyPostBarriers but run before a minor GC. Checks for tenured
1213 // dependent strings pointing to nursery chars but not in the store buffer. If
1214 // a tenured string cell points to a nursery string cell, then it will be in
1215 // the store buffer and is fine. So this looks for tenured strings that point
1216 // to tenured strings but contain nursery data.
1217
1218 for (ZonesIter zone(rt, SkipAtoms); !zone.done(); zone.next()) {
1219 if (zone->isGCFinished()) {
1220 continue; // Don't access zones that are being swept off thread.
1221 }
1222
1223 for (ArenaIter aiter(zone, gc::AllocKind::STRING); !aiter.done();
1224 aiter.next()) {
1225 for (ArenaCellIterUnderGC cell(aiter.get()); !cell.done(); cell.next()) {
1226 if (cell->as<JSString>()->isDependent()) {
1227 JSDependentString* str = &cell->as<JSString>()->asDependent();
1228 if (str->isTenured() && str->base()->isTenured()) {
1229 MOZ_RELEASE_ASSERT(!str->hasCharsInCollectedNurseryRegion());
1230 }
1231 }
1232 }
1233 }
1234 }
1235 }
1236 #endif
1237
1238 // Return whether an arbitrary pointer is within a cell with the given
1239 // traceKind. Only for assertions and js::debug::* APIs.
1240 bool GCRuntime::isPointerWithinTenuredCell(void* ptr, JS::TraceKind traceKind) {
1241 AutoLockGC lock(this);
1242 for (auto chunk = allNonEmptyChunks(lock); !chunk.done(); chunk.next()) {
1243 MOZ_ASSERT(!chunk->isNurseryChunk());
1244 if (ptr >= &chunk->arenas[0] && ptr < &chunk->arenas[ArenasPerChunk]) {
1245 auto* arena = reinterpret_cast<Arena*>(uintptr_t(ptr) & ~ArenaMask);
1246 if (!arena->allocated()) {
1247 return false;
1248 }
1249
1250 return traceKind == JS::TraceKind::Null ||
1251 MapAllocToTraceKind(arena->getAllocKind()) == traceKind;
1252 }
1253 }
1254
1255 return false;
1256 }
1257
1258 bool GCRuntime::isPointerWithinBufferAlloc(void* ptr) {
1259 if (isPointerWithinTenuredCell(ptr, JS::TraceKind::SmallBuffer)) {
1260 return true;
1261 }
1262
1263 for (AllZonesIter zone(this); !zone.done(); zone.next()) {
1264 if (zone->bufferAllocator.isPointerWithinMediumOrLargeBuffer(ptr)) {
1265 return true;
1266 }
1267 }
1268
1269 return false;
1270 }