Debian Codegraph @

js/src/gc/Marking.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 "gc/Marking-inl.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/IntegerRange.h"
11 #include "mozilla/MathAlgorithms.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/PodOperations.h"
14 #include "mozilla/ScopeExit.h"
15
16 #include <algorithm>
17 #include <type_traits>
18
19 #include "jsmath.h"
20
21 #include "gc/BufferAllocator.h"
22 #include "gc/GCInternals.h"
23 #include "gc/ParallelMarking.h"
24 #include "gc/TraceKind.h"
25 #include "jit/JitCode.h"
26 #include "js/GCTypeMacros.h" // JS_FOR_EACH_PUBLIC_{,TAGGED_}GC_POINTER_TYPE
27 #include "js/SliceBudget.h"
28 #include "util/Poison.h"
29 #include "vm/GeneratorObject.h"
30
31 #include "gc/BufferAllocator-inl.h"
32 #include "gc/GC-inl.h"
33 #include "gc/PrivateIterators-inl.h"
34 #include "gc/TraceMethods-inl.h"
35 #include "gc/WeakMap-inl.h"
36 #include "vm/GeckoProfiler-inl.h"
37
38 using namespace js;
39 using namespace js::gc;
40
41 using JS::MapTypeToTraceKind;
42 using JS::SliceBudget;
43
44 using mozilla::DebugOnly;
45 using mozilla::IntegerRange;
46
47 // [SMDOC] GC Tracing
48 //
49 // Tracing Overview
50 // ================
51 //
52 // Tracing, in this context, refers to an abstract visitation of some or all of
53 // the GC-controlled heap. The effect of tracing an edge of the graph depends
54 // on the subclass of the JSTracer on whose behalf we are tracing.
55 //
56 // Marking
57 // -------
58 //
59 // The primary JSTracer is the GCMarker. The marking tracer causes the target
60 // of each traversed edge to be marked black and the target edge's children to
61 // be marked either gray (in the gc algorithm sense) or immediately black.
62 //
63 // Callback
64 // --------
65 //
66 // The secondary JSTracer is the CallbackTracer. This simply invokes a callback
67 // on each edge in a child.
68 //
69 // The following is a rough outline of the general struture of the tracing
70 // internals.
71 //
72 /* clang-format off */
73 //
74 // +-------------------+ ......................
75 // | | : :
76 // | v v +---+---+
77 // | TraceRoot TraceEdge TraceRange GCMarker:: | |
78 // | | | | processMarkStackTop | Mark |
79 // | +-----------------------+ | | Stack |
80 // | | | | |
81 // | v | +---+---+
82 // | TraceEdgeInternal | ^
83 // | | +<-------------+ :
84 // | | | | :
85 // | v v | :
86 // | CallbackTracer:: markAndTraverseEdge | :
87 // | onSomeEdge | | :
88 // | | | | :
89 // | | | | :
90 // | +-------------+---------------+ | :
91 // | | | :
92 // | v | :
93 // | markAndTraverse | :
94 // | | | :
95 // | | | :
96 // | traverse | :
97 // | | | :
98 // | +--------------------------------------+ | :
99 // | | | | | :
100 // | v v v | :
101 // | markAndTraceChildren markAndPush eagerlyMarkChildren | :
102 // | | : | | :
103 // | v : +-----------+ :
104 // | T::traceChildren : :
105 // | | : :
106 // +-------------+ ......................................
107 //
108 // Legend:
109 // ------- Direct calls
110 // ....... Data flow
111 //
112 /* clang-format on */
113
114 static const size_t ValueRangeWords =
115 sizeof(MarkStack::SlotsOrElementsRange) / sizeof(uintptr_t);
116
117 /*** Tracing Invariants *****************************************************/
118
119 template <typename T>
120 static inline bool IsOwnedByOtherRuntime(JSRuntime* rt, T thing) {
121 bool other = thing->runtimeFromAnyThread() != rt;
122 MOZ_ASSERT_IF(other, thing->isPermanentAndMayBeShared());
123 return other;
124 }
125
126 #ifdef DEBUG
127
128 static inline bool IsInFreeList(TenuredCell* cell) {
129 Arena* arena = cell->arena();
130 uintptr_t addr = reinterpret_cast<uintptr_t>(cell);
131 MOZ_ASSERT(Arena::isAligned(addr, arena->getThingSize()));
132 return arena->inFreeList(addr);
133 }
134
135 template <typename T>
136 void js::CheckTracedThing(JSTracer* trc, T* thing) {
137 MOZ_ASSERT(trc);
138 MOZ_ASSERT(thing);
139
140 if (IsForwarded(thing)) {
141 JS::TracerKind kind = trc->kind();
142 MOZ_ASSERT(kind == JS::TracerKind::Tenuring ||
143 kind == JS::TracerKind::MinorSweeping ||
144 kind == JS::TracerKind::Moving ||
145 kind == JS::TracerKind::HeapCheck);
146 thing = Forwarded(thing);
147 }
148
149 /* This function uses data that's not available in the nursery. */
150 if (IsInsideNursery(thing)) {
151 return;
152 }
153
154 /*
155 * Permanent shared things that are not associated with this runtime will be
156 * ignored during marking.
157 */
158 Zone* zone = thing->zoneFromAnyThread();
159 if (IsOwnedByOtherRuntime(trc->runtime(), thing)) {
160 MOZ_ASSERT(!zone->wasGCStarted());
161 MOZ_ASSERT(thing->isMarkedBlack());
162 return;
163 }
164
165 JSRuntime* rt = trc->runtime();
166 MOZ_ASSERT(zone->runtimeFromAnyThread() == rt);
167
168 bool isGcMarkingTracer = trc->isMarkingTracer();
169 bool isUnmarkGrayTracer = IsTracerKind(trc, JS::TracerKind::UnmarkGray);
170 bool isClearEdgesTracer = IsTracerKind(trc, JS::TracerKind::ClearEdges);
171
172 if (TlsContext.get()) {
173 // If we're on the main thread we must have access to the runtime and zone.
174 MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
175 MOZ_ASSERT(CurrentThreadCanAccessZone(zone));
176 } else {
177 MOZ_ASSERT(isGcMarkingTracer || isUnmarkGrayTracer || isClearEdgesTracer ||
178 IsTracerKind(trc, JS::TracerKind::Moving) ||
179 IsTracerKind(trc, JS::TracerKind::Sweeping));
180 MOZ_ASSERT_IF(!isClearEdgesTracer, CurrentThreadIsPerformingGC());
181 }
182
183 MOZ_ASSERT(thing->isAligned());
184 MOZ_ASSERT(MapTypeToTraceKind<std::remove_pointer_t<T>>::kind ==
185 thing->getTraceKind());
186
187 /*
188 * Check that we only mark allocated cells.
189 *
190 * This check is restricted to marking for two reasons: Firstly, if background
191 * sweeping is running and concurrently modifying the free list then it is not
192 * safe. Secondly, it was thought to be slow so this is a compromise so as to
193 * not affect test times too much.
194 */
195 MOZ_ASSERT_IF(zone->isGCMarking(), !IsInFreeList(&thing->asTenured()));
196 }
197
198 template <typename T>
199 void js::CheckTracedThing(JSTracer* trc, const T& thing) {
200 ApplyGCThingTyped(thing, [trc](auto t) { CheckTracedThing(trc, t); });
201 }
202
203 template <typename T>
204 static void CheckMarkedThing(GCMarker* gcMarker, T* thing) {
205 Zone* zone = thing->zoneFromAnyThread();
206
207 MOZ_ASSERT(zone->shouldMarkInZone(gcMarker->markColor()));
208
209 MOZ_ASSERT_IF(gcMarker->shouldCheckCompartments(),
210 zone->isCollectingFromAnyThread() || zone->isAtomsZone());
211
212 MOZ_ASSERT_IF(gcMarker->markColor() == MarkColor::Gray,
213 !zone->isGCMarkingBlackOnly() || zone->isAtomsZone());
214
215 MOZ_ASSERT(!(zone->isGCSweeping() || zone->isGCFinished() ||
216 zone->isGCCompacting()));
217
218 // Check that we don't stray from the current compartment and zone without
219 // using TraceCrossCompartmentEdge.
220 Compartment* comp = thing->maybeCompartment();
221 MOZ_ASSERT_IF(gcMarker->tracingCompartment && comp,
222 gcMarker->tracingCompartment == comp);
223 MOZ_ASSERT_IF(gcMarker->tracingZone,
224 gcMarker->tracingZone == zone || zone->isAtomsZone());
225 }
226
227 namespace js {
228
229 # define IMPL_CHECK_TRACED_THING(_, type, _1, _2) \
230 template void CheckTracedThing<type>(JSTracer*, type*);
231 JS_FOR_EACH_TRACEKIND(IMPL_CHECK_TRACED_THING);
232 # undef IMPL_CHECK_TRACED_THING
233
234 template void CheckTracedThing<Value>(JSTracer*, const Value&);
235 template void CheckTracedThing<wasm::AnyRef>(JSTracer*, const wasm::AnyRef&);
236
237 } // namespace js
238
239 #endif
240
241 static inline bool ShouldMarkCrossCompartment(GCMarker* marker, JSObject* src,
242 Cell* dstCell, const char* name) {
243 #ifdef DEBUG
244 if (src->isMarkedGray() && !dstCell->isTenured()) {
245 // Bug 1743098: This shouldn't be possible but it does seem to happen. Log
246 // some useful information in debug builds.
247 SEprinter printer;
248 printer.printf(
249 "ShouldMarkCrossCompartment: cross compartment edge '%s' from gray "
250 "object to nursery thing\n",
251 name);
252 printer.put("src: ");
253 src->dump(printer);
254 printer.put("dst: ");
255 dstCell->dump(printer);
256 MOZ_CRASH("Found cross compartment edge from gray object to nursery thing");
257 }
258 #endif
259
260 CellColor targetColor = AsCellColor(marker->markColor());
261 CellColor currentColor = dstCell->color();
262 if (currentColor >= targetColor) {
263 // Cell is already sufficiently marked. Nothing to do.
264 return false;
265 }
266
267 TenuredCell& dst = dstCell->asTenured();
268 JS::Zone* dstZone = dst.zone();
269 if (!src->zone()->isGCMarking() && !dstZone->isGCMarking()) {
270 return false;
271 }
272
273 if (targetColor == CellColor::Black) {
274 // Check our sweep groups are correct: we should never have to
275 // mark something in a zone that we have started sweeping.
276 MOZ_ASSERT(currentColor < CellColor::Black);
277 MOZ_ASSERT(!dstZone->isGCSweeping());
278
279 /*
280 * Having black->gray edges violates our promise to the cycle collector so
281 * we ensure that gray things we encounter when marking black end up getting
282 * marked black.
283 *
284 * This can happen for two reasons:
285 *
286 * 1) If we're collecting a compartment and it has an edge to an uncollected
287 * compartment it's possible that the source and destination of the
288 * cross-compartment edge should be gray, but the source was marked black by
289 * the write barrier.
290 *
291 * 2) If we yield during gray marking and the write barrier marks a gray
292 * thing black.
293 *
294 * We handle the first case before returning whereas the second case happens
295 * as part of normal marking.
296 */
297 if (currentColor == CellColor::Gray && !dstZone->isGCMarking()) {
298 UnmarkGrayGCThingUnchecked(marker,
299 JS::GCCellPtr(&dst, dst.getTraceKind()));
300 return false;
301 }
302
303 return dstZone->isGCMarking();
304 }
305
306 // Check our sweep groups are correct as above.
307 MOZ_ASSERT(currentColor == CellColor::White);
308 MOZ_ASSERT(!dstZone->isGCSweeping());
309
310 if (dstZone->isGCMarkingBlackOnly()) {
311 /*
312 * The destination compartment is being not being marked gray now,
313 * but it will be later, so record the cell so it can be marked gray
314 * at the appropriate time.
315 */
316 DelayCrossCompartmentGrayMarking(marker, src);
317 return false;
318 }
319
320 return dstZone->isGCMarkingBlackAndGray();
321 }
322
323 static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
324 Cell* dstCell, const char* name) {
325 if (!trc->isMarkingTracer()) {
326 return true;
327 }
328
329 return ShouldMarkCrossCompartment(GCMarker::fromTracer(trc), src, dstCell,
330 name);
331 }
332
333 static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
334 const Value& val, const char* name) {
335 return val.isGCThing() &&
336 ShouldTraceCrossCompartment(trc, src, val.toGCThing(), name);
337 }
338
339 #ifdef DEBUG
340
341 template <typename T>
342 void js::gc::AssertShouldMarkInZone(GCMarker* marker, T* thing) {
343 if (thing->isMarkedBlack()) {
344 return;
345 }
346
347 // Allow marking marking atoms if we're not collected the atoms zone, except
348 // for symbols which may entrain other GC things if they're used as weakmap
349 // keys.
350 bool allowAtoms = !std::is_same_v<T, JS::Symbol>;
351
352 Zone* zone = thing->zone();
353 MOZ_ASSERT(zone->shouldMarkInZone(marker->markColor()) ||
354 (allowAtoms && zone->isAtomsZone()));
355 }
356
357 void js::gc::AssertRootMarkingPhase(JSTracer* trc) {
358 MOZ_ASSERT_IF(trc->isMarkingTracer(),
359 trc->runtime()->gc.state() == State::NotActive ||
360 trc->runtime()->gc.state() == State::MarkRoots);
361 }
362
363 #endif // DEBUG
364
365 /*** Tracing Interface ******************************************************/
366
367 template <typename T>
368 static void TraceExternalEdgeHelper(JSTracer* trc, T* thingp,
369 const char* name) {
370 MOZ_ASSERT(InternalBarrierMethods<T>::isMarkable(*thingp));
371 TraceEdgeInternal(trc, ConvertToBase(thingp), name);
372 }
373
374 JS_PUBLIC_API void js::UnsafeTraceManuallyBarrieredEdge(JSTracer* trc,
375 JSObject** thingp,
376 const char* name) {
377 TraceEdgeInternal(trc, ConvertToBase(thingp), name);
378 }
379
380 template <typename T>
381 static void TraceRootHelper(JSTracer* trc, T* thingp, const char* name) {
382 MOZ_ASSERT(thingp);
383 js::TraceNullableRoot(trc, thingp, name);
384 }
385
386 namespace js {
387 class AbstractGeneratorObject;
388 class SavedFrame;
389 } // namespace js
390
391 #define DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION(type) \
392 JS_PUBLIC_API void js::gc::TraceExternalEdge(JSTracer* trc, type* thingp, \
393 const char* name) { \
394 TraceExternalEdgeHelper(trc, thingp, name); \
395 }
396
397 // Define TraceExternalEdge for each public GC pointer type.
398 JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION)
399 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION)
400
401 #undef DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION
402
403 #define DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(type) \
404 JS_PUBLIC_API void JS::TraceRoot(JSTracer* trc, type* thingp, \
405 const char* name) { \
406 TraceRootHelper(trc, thingp, name); \
407 }
408
409 // Define TraceRoot for each public GC pointer type.
410 JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DEFINE_UNSAFE_TRACE_ROOT_FUNCTION)
411 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DEFINE_UNSAFE_TRACE_ROOT_FUNCTION)
412
413 // Also, for the moment, define TraceRoot for internal GC pointer types.
414 DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(AbstractGeneratorObject*)
415 DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(SavedFrame*)
416 DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(wasm::AnyRef)
417
418 #undef DEFINE_UNSAFE_TRACE_ROOT_FUNCTION
419
420 namespace js::gc {
421
422 #define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type) \
423 template void TraceRangeInternal<type>(JSTracer*, size_t len, type*, \
424 const char*);
425
426 #define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND(_1, type, _2, _3) \
427 INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type*)
428
429 JS_FOR_EACH_TRACEKIND(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND)
430 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS)
431 INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(TaggedProto)
432
433 #undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND
434 #undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS
435
436 } // namespace js::gc
437
438 // In debug builds, makes a note of the current compartment before calling a
439 // trace hook or traceChildren() method on a GC thing.
440 class MOZ_RAII AutoSetTracingSource {
441 #ifndef DEBUG
442 public:
443 template <typename T>
444 AutoSetTracingSource(JSTracer* trc, T* thing) {}
445 ~AutoSetTracingSource() {}
446 #else
447 GCMarker* marker = nullptr;
448
449 public:
450 template <typename T>
451 AutoSetTracingSource(JSTracer* trc, T* thing) {
452 if (trc->isMarkingTracer() && thing) {
453 marker = GCMarker::fromTracer(trc);
454 MOZ_ASSERT(!marker->tracingZone);
455 marker->tracingZone = thing->asTenured().zone();
456 MOZ_ASSERT(!marker->tracingCompartment);
457 marker->tracingCompartment = thing->maybeCompartment();
458 }
459 }
460
461 ~AutoSetTracingSource() {
462 if (marker) {
463 marker->tracingZone = nullptr;
464 marker->tracingCompartment = nullptr;
465 }
466 }
467 #endif
468 };
469
470 // In debug builds, clear the trace hook compartment. This happens after the
471 // trace hook has called back into one of our trace APIs and we've checked the
472 // traced thing.
473 class MOZ_RAII AutoClearTracingSource {
474 #ifndef DEBUG
475 public:
476 explicit AutoClearTracingSource(GCMarker* marker) {}
477 explicit AutoClearTracingSource(JSTracer* trc) {}
478 ~AutoClearTracingSource() {}
479 #else
480 GCMarker* marker = nullptr;
481 JS::Zone* prevZone = nullptr;
482 Compartment* prevCompartment = nullptr;
483
484 public:
485 explicit AutoClearTracingSource(JSTracer* trc) {
486 if (trc->isMarkingTracer()) {
487 marker = GCMarker::fromTracer(trc);
488 prevZone = marker->tracingZone;
489 marker->tracingZone = nullptr;
490 prevCompartment = marker->tracingCompartment;
491 marker->tracingCompartment = nullptr;
492 }
493 }
494 ~AutoClearTracingSource() {
495 if (marker) {
496 marker->tracingZone = prevZone;
497 marker->tracingCompartment = prevCompartment;
498 }
499 }
500 #endif
501 };
502
503 template <typename T>
504 void js::TraceManuallyBarrieredCrossCompartmentEdge(JSTracer* trc,
505 JSObject* src, T* dst,
506 const char* name) {
507 // Clear expected compartment for cross-compartment edge.
508 AutoClearTracingSource acts(trc);
509
510 if (ShouldTraceCrossCompartment(trc, src, *dst, name)) {
511 TraceEdgeInternal(trc, dst, name);
512 }
513 }
514 template void js::TraceManuallyBarrieredCrossCompartmentEdge<Value>(
515 JSTracer*, JSObject*, Value*, const char*);
516 template void js::TraceManuallyBarrieredCrossCompartmentEdge<JSObject*>(
517 JSTracer*, JSObject*, JSObject**, const char*);
518 template void js::TraceManuallyBarrieredCrossCompartmentEdge<BaseScript*>(
519 JSTracer*, JSObject*, BaseScript**, const char*);
520
521 template <typename T>
522 void js::TraceSameZoneCrossCompartmentEdge(JSTracer* trc,
523 const BarrieredBase<T>* dst,
524 const char* name) {
525 #ifdef DEBUG
526 if (trc->isMarkingTracer()) {
527 T thing = *dst->unbarrieredAddress();
528 MOZ_ASSERT(thing->maybeCompartment(),
529 "Use TraceEdge for GC things without a compartment");
530
531 GCMarker* gcMarker = GCMarker::fromTracer(trc);
532 MOZ_ASSERT_IF(gcMarker->tracingZone,
533 thing->zone() == gcMarker->tracingZone);
534 }
535
536 // Skip compartment checks for this edge.
537 if (trc->kind() == JS::TracerKind::CompartmentCheck) {
538 return;
539 }
540 #endif
541
542 // Clear expected compartment for cross-compartment edge.
543 AutoClearTracingSource acts(trc);
544 TraceEdgeInternal(trc, ConvertToBase(dst->unbarrieredAddress()), name);
545 }
546 template void js::TraceSameZoneCrossCompartmentEdge(
547 JSTracer*, const BarrieredBase<Shape*>*, const char*);
548
549 template <typename T>
550 void js::TraceWeakMapKeyEdgeInternal(JSTracer* trc, Zone* weakMapZone,
551 T** thingp, const char* name) {
552 // We can't use ShouldTraceCrossCompartment here because that assumes the
553 // source of the edge is a CCW object which could be used to delay gray
554 // marking. Instead, assert that the weak map zone is in the same marking
555 // state as the target thing's zone and therefore we can go ahead and mark it.
556 #ifdef DEBUG
557 auto thing = *thingp;
558 if (trc->isMarkingTracer()) {
559 MOZ_ASSERT(weakMapZone->isGCMarking());
560 MOZ_ASSERT(weakMapZone->gcState() == thing->zone()->gcState());
561 }
562 #endif
563
564 // Clear expected compartment for cross-compartment edge.
565 AutoClearTracingSource acts(trc);
566
567 TraceEdgeInternal(trc, thingp, name);
568 }
569
570 template <typename T>
571 void js::TraceWeakMapKeyEdgeInternal(JSTracer* trc, Zone* weakMapZone,
572 T* thingp, const char* name) {
573 // We can't use ShouldTraceCrossCompartment here because that assumes the
574 // source of the edge is a CCW object which could be used to delay gray
575 // marking. Instead, assert that the weak map zone is in the same marking
576 // state as the target thing's zone and therefore we can go ahead and mark it.
577 #ifdef DEBUG
578 if (trc->isMarkingTracer()) {
579 MOZ_ASSERT(weakMapZone->isGCMarking());
580 MOZ_ASSERT(weakMapZone->gcState() ==
581 gc::ToMarkable(*thingp)->zone()->gcState());
582 }
583 #endif
584
585 // Clear expected compartment for cross-compartment edge.
586 AutoClearTracingSource acts(trc);
587
588 TraceEdgeInternal(trc, thingp, name);
589 }
590
591 template void js::TraceWeakMapKeyEdgeInternal<JSObject>(JSTracer*, Zone*,
592 JSObject**,
593 const char*);
594 template void js::TraceWeakMapKeyEdgeInternal<BaseScript>(JSTracer*, Zone*,
595 BaseScript**,
596 const char*);
597 template void js::TraceWeakMapKeyEdgeInternal<JS::Value>(JSTracer*, Zone*,
598 JS::Value*,
599 const char*);
600
601 static Cell* TraceGenericPointerRootAndType(JSTracer* trc, Cell* thing,
602 JS::TraceKind kind,
603 const char* name) {
604 return MapGCThingTyped(thing, kind, [trc, name](auto t) -> Cell* {
605 TraceRoot(trc, &t, name);
606 return t;
607 });
608 }
609
610 void js::TraceGenericPointerRoot(JSTracer* trc, Cell** thingp,
611 const char* name) {
612 MOZ_ASSERT(thingp);
613 Cell* thing = *thingp;
614 if (!thing) {
615 return;
616 }
617
618 Cell* traced =
619 TraceGenericPointerRootAndType(trc, thing, thing->getTraceKind(), name);
620 if (traced != thing) {
621 *thingp = traced;
622 }
623 }
624
625 void js::TraceManuallyBarrieredGenericPointerEdge(JSTracer* trc, Cell** thingp,
626 const char* name) {
627 MOZ_ASSERT(thingp);
628 Cell* thing = *thingp;
629 if (!*thingp) {
630 return;
631 }
632
633 auto* traced = MapGCThingTyped(thing, thing->getTraceKind(),
634 [trc, name](auto t) -> Cell* {
635 TraceManuallyBarrieredEdge(trc, &t, name);
636 return t;
637 });
638 if (traced != thing) {
639 *thingp = traced;
640 }
641 }
642
643 void js::TraceGCCellPtrRoot(JSTracer* trc, JS::GCCellPtr* thingp,
644 const char* name) {
645 Cell* thing = thingp->asCell();
646 if (!thing) {
647 return;
648 }
649
650 Cell* traced =
651 TraceGenericPointerRootAndType(trc, thing, thingp->kind(), name);
652
653 if (!traced) {
654 *thingp = JS::GCCellPtr();
655 } else if (traced != thingp->asCell()) {
656 *thingp = JS::GCCellPtr(traced, thingp->kind());
657 }
658 }
659
660 void js::TraceManuallyBarrieredGCCellPtr(JSTracer* trc, JS::GCCellPtr* thingp,
661 const char* name) {
662 Cell* thing = thingp->asCell();
663 if (!thing) {
664 return;
665 }
666
667 Cell* traced = MapGCThingTyped(thing, thing->getTraceKind(),
668 [trc, name](auto t) -> Cell* {
669 TraceManuallyBarrieredEdge(trc, &t, name);
670 return t;
671 });
672
673 if (!traced) {
674 // If we are clearing edges, also erase the type. This happens when using
675 // ClearEdgesTracer.
676 *thingp = JS::GCCellPtr();
677 } else if (traced != thingp->asCell()) {
678 *thingp = JS::GCCellPtr(traced, thingp->kind());
679 }
680 }
681
682 template <typename T>
683 inline bool TraceTaggedPtrEdge(JSTracer* trc, T* thingp, const char* name) {
684 // Return true by default. For some types the lambda below won't be called.
685 bool ret = true;
686 auto thing = MapGCThingTyped(*thingp, [&](auto thing) {
687 if (!TraceEdgeInternal(trc, &thing, name)) {
688 ret = false;
689 return TaggedPtr<T>::empty();
690 }
691
692 return TaggedPtr<T>::wrap(thing);
693 });
694
695 // Only update *thingp if the value changed, to avoid TSan false positives for
696 // template objects when using DumpHeapTracer or UbiNode tracers while Ion
697 // compiling off-thread.
698 if (thing.isSome() && thing.value() != *thingp) {
699 *thingp = thing.value();
700 }
701
702 return ret;
703 }
704
705 bool js::gc::TraceEdgeInternal(JSTracer* trc, Value* thingp, const char* name) {
706 return TraceTaggedPtrEdge(trc, thingp, name);
707 }
708 bool js::gc::TraceEdgeInternal(JSTracer* trc, jsid* thingp, const char* name) {
709 return TraceTaggedPtrEdge(trc, thingp, name);
710 }
711 bool js::gc::TraceEdgeInternal(JSTracer* trc, TaggedProto* thingp,
712 const char* name) {
713 return TraceTaggedPtrEdge(trc, thingp, name);
714 }
715 bool js::gc::TraceEdgeInternal(JSTracer* trc, wasm::AnyRef* thingp,
716 const char* name) {
717 return TraceTaggedPtrEdge(trc, thingp, name);
718 }
719
720 template <typename T>
721 void js::gc::TraceRangeInternal(JSTracer* trc, size_t len, T* vec,
722 const char* name) {
723 JS::AutoTracingIndex index(trc);
724 for (auto i : IntegerRange(len)) {
725 if (InternalBarrierMethods<T>::isMarkable(vec[i])) {
726 TraceEdgeInternal(trc, &vec[i], name);
727 }
728 ++index;
729 }
730 }
731
732 /*** GC Marking Interface ***************************************************/
733
734 namespace js {
735
736 void GCMarker::markEphemeronEdges(EphemeronEdgeVector& edges,
737 gc::MarkColor srcColor) {
738 // This is called as part of GC weak marking or by barriers outside of GC.
739 MOZ_ASSERT_IF(CurrentThreadIsPerformingGC(),
740 state == MarkingState::WeakMarking);
741
742 DebugOnly<size_t> initialLength = edges.length();
743
744 for (auto& edge : edges) {
745 MarkColor targetColor = std::min(srcColor, MarkColor(edge.color));
746 MOZ_ASSERT(markColor() >= targetColor);
747 if (targetColor == markColor()) {
748 ApplyGCThingTyped(edge.target, edge.target->getTraceKind(),
749 [this](auto t) {
750 markAndTraverse<MarkingOptions::MarkImplicitEdges>(t);
751 });
752 }
753 }
754
755 // The above marking always goes through pushThing, which will not cause
756 // 'edges' to be appended to while iterating.
757 MOZ_ASSERT(edges.length() == initialLength);
758
759 // This is not just an optimization. When nuking a CCW, we conservatively
760 // mark through the related edges and then lose the CCW->target connection
761 // that induces a sweep group edge. As a result, it is possible for the
762 // delegate zone to get marked later, look up an edge in this table, and
763 // then try to mark something in a Zone that is no longer marking.
764 if (srcColor == MarkColor::Black && markColor() == MarkColor::Black) {
765 edges.eraseIf([](auto& edge) { return edge.color == MarkColor::Black; });
766 }
767 }
768
769 template <typename T>
770 struct TypeCanHaveImplicitEdges : std::false_type {};
771 template <>
772 struct TypeCanHaveImplicitEdges<JSObject> : std::true_type {};
773 template <>
774 struct TypeCanHaveImplicitEdges<BaseScript> : std::true_type {};
775 template <>
776 struct TypeCanHaveImplicitEdges<JS::Symbol> : std::true_type {};
777
778 template <typename T>
779 void GCMarker::markImplicitEdges(T* markedThing) {
780 if constexpr (!TypeCanHaveImplicitEdges<T>::value) {
781 return;
782 }
783
784 if (!isWeakMarking()) {
785 return;
786 }
787
788 Zone* zone = markedThing->asTenured().zone();
789 MOZ_ASSERT(zone->isGCMarking());
790 MOZ_ASSERT(!zone->isGCSweeping());
791
792 auto& ephemeronTable = zone->gcEphemeronEdges();
793 auto p = ephemeronTable.lookup(markedThing);
794 if (!p) {
795 return;
796 }
797
798 EphemeronEdgeVector& edges = p->value();
799
800 // markedThing might be a key in a debugger weakmap, which can end up marking
801 // values that are in a different compartment.
802 AutoClearTracingSource acts(tracer());
803
804 MarkColor thingColor = markColor();
805 MOZ_ASSERT(CellColor(thingColor) ==
806 gc::detail::GetEffectiveColor(this, markedThing));
807
808 markEphemeronEdges(edges, thingColor);
809
810 if (edges.empty()) {
811 ephemeronTable.remove(p);
812 }
813 }
814
815 template void GCMarker::markImplicitEdges(JSObject*);
816 template void GCMarker::markImplicitEdges(BaseScript*);
817 #ifdef NIGHTLY_BUILD
818 template void GCMarker::markImplicitEdges(JS::Symbol*);
819 #endif
820
821 } // namespace js
822
823 template <typename T>
824 static inline bool ShouldMark(GCMarker* gcmarker, T* thing) {
825 // We may encounter nursery things during normal marking since we don't
826 // collect the nursery at the start of every GC slice.
827 if (!thing->isTenured()) {
828 return false;
829 }
830
831 // Don't mark things outside a zone if we are in a per-zone GC. Don't mark
832 // permanent shared things owned by other runtimes (we will never observe
833 // their zone being collected).
834 Zone* zone = thing->asTenured().zoneFromAnyThread();
835 return zone->shouldMarkInZone(gcmarker->markColor());
836 }
837
838 template <uint32_t opts>
839 MarkingTracerT<opts>::MarkingTracerT(JSRuntime* runtime, GCMarker* marker)
840 : GenericTracerImpl<MarkingTracerT<opts>>(
841 runtime, JS::TracerKind::Marking,
842 JS::TraceOptions(JS::WeakMapTraceAction::Expand,
843 JS::WeakEdgeTraceAction::Skip)) {
844 // Marking tracers are owned by (and part of) a GCMarker.
845 MOZ_ASSERT(this == marker->tracer());
846 MOZ_ASSERT(getMarker() == marker);
847 }
848
849 template <uint32_t opts>
850 MOZ_ALWAYS_INLINE GCMarker* MarkingTracerT<opts>::getMarker() {
851 return GCMarker::fromTracer(this);
852 }
853
854 template <uint32_t opts>
855 template <typename T>
856 void MarkingTracerT<opts>::onEdge(T** thingp, const char* name) {
857 T* thing = *thingp;
858
859 // Do per-type marking precondition checks.
860 GCMarker* marker = getMarker();
861 if (!ShouldMark(marker, thing)) {
862 MOZ_ASSERT(gc::detail::GetEffectiveColor(marker, thing) ==
863 js::gc::CellColor::Black);
864 return;
865 }
866
867 MOZ_ASSERT(!IsOwnedByOtherRuntime(this->runtime(), thing));
868
869 #ifdef DEBUG
870 CheckMarkedThing(marker, thing);
871 #endif
872
873 AutoClearTracingSource acts(this);
874 marker->markAndTraverse<opts>(thing);
875 }
876
877 #define INSTANTIATE_ONEDGE_METHOD(name, type, _1, _2) \
878 template void MarkingTracerT<MarkingOptions::None>::onEdge<type>( \
879 type * *thingp, const char* name); \
880 template void \
881 MarkingTracerT<MarkingOptions::MarkImplicitEdges>::onEdge<type>( \
882 type * *thingp, const char* name); \
883 template void \
884 MarkingTracerT<MarkingOptions::MarkRootCompartments>::onEdge<type>( \
885 type * *thingp, const char* name);
886 JS_FOR_EACH_TRACEKIND(INSTANTIATE_ONEDGE_METHOD)
887 #undef INSTANTIATE_ONEDGE_METHOD
888
889 static void TraceEdgeForBarrier(GCMarker* gcmarker, TenuredCell* thing,
890 JS::TraceKind kind) {
891 // Dispatch to markAndTraverse without checking ShouldMark.
892 ApplyGCThingTyped(thing, kind, [gcmarker](auto thing) {
893 MOZ_ASSERT(ShouldMark(gcmarker, thing));
894 CheckTracedThing(gcmarker->tracer(), thing);
895 AutoClearTracingSource acts(gcmarker->tracer());
896 #ifdef DEBUG
897 AutoSetThreadIsMarking threadIsMarking;
898 #endif // DEBUG
899 gcmarker->markAndTraverse<NormalMarkingOptions>(thing);
900 });
901 }
902
903 JS_PUBLIC_API void js::gc::PerformIncrementalReadBarrier(JS::GCCellPtr thing) {
904 // Optimized marking for read barriers. This is called from
905 // ExposeGCThingToActiveJS which has already checked the prerequisites for
906 // performing a read barrier. This means we can skip a bunch of checks and
907 // call into the tracer directly.
908
909 MOZ_ASSERT(thing);
910 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
911
912 TenuredCell* cell = &thing.asCell()->asTenured();
913 MOZ_ASSERT(!cell->isMarkedBlack());
914
915 Zone* zone = cell->zone();
916 MOZ_ASSERT(zone->needsIncrementalBarrier());
917
918 // Skip dispatching on known tracer type.
919 GCMarker* gcmarker = GCMarker::fromTracer(zone->barrierTracer());
920 TraceEdgeForBarrier(gcmarker, cell, thing.kind());
921 }
922
923 void js::gc::PerformIncrementalReadBarrier(TenuredCell* cell) {
924 // Internal version of previous function.
925
926 MOZ_ASSERT(cell);
927 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
928
929 if (cell->isMarkedBlack()) {
930 return;
931 }
932
933 Zone* zone = cell->zone();
934 MOZ_ASSERT(zone->needsIncrementalBarrier());
935
936 // Skip dispatching on known tracer type.
937 GCMarker* gcmarker = GCMarker::fromTracer(zone->barrierTracer());
938 TraceEdgeForBarrier(gcmarker, cell, cell->getTraceKind());
939 }
940
941 void js::gc::PerformIncrementalPreWriteBarrier(TenuredCell* cell) {
942 // The same as PerformIncrementalReadBarrier except for an extra check on the
943 // runtime for cells in atoms zone.
944
945 Zone* zone = cell->zoneFromAnyThread();
946
947 MOZ_ASSERT(cell);
948 if (cell->isMarkedBlack()) {
949 return;
950 }
951
952 // Barriers can be triggered off the main thread by background finalization of
953 // HeapPtrs to the atoms zone. We don't want to trigger the barrier in this
954 // case.
955 bool checkThread = zone->isAtomsZone();
956 JSRuntime* runtime = cell->runtimeFromAnyThread();
957 if (checkThread && !CurrentThreadCanAccessRuntime(runtime)) {
958 MOZ_ASSERT(CurrentThreadIsGCFinalizing());
959 return;
960 }
961
962 MOZ_ASSERT(zone->needsIncrementalBarrier());
963 MOZ_ASSERT(CurrentThreadIsMainThread());
964 MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting());
965
966 // Skip dispatching on known tracer type.
967 GCMarker* gcmarker = GCMarker::fromTracer(zone->barrierTracer());
968 TraceEdgeForBarrier(gcmarker, cell, cell->getTraceKind());
969 }
970
971 void js::gc::PerformIncrementalBarrierDuringFlattening(JSString* str) {
972 TenuredCell* cell = &str->asTenured();
973
974 // Skip eager marking of ropes during flattening. Their children will also be
975 // barriered by flattening process so we don't need to traverse them.
976 if (str->isRope()) {
977 cell->markBlack();
978 return;
979 }
980
981 PerformIncrementalPreWriteBarrier(cell);
982 }
983
984 template <uint32_t opts, typename T>
985 void js::GCMarker::markAndTraverse(T* thing) {
986 if (mark<opts>(thing)) {
987 // We only mark permanent things during initialization.
988 MOZ_ASSERT_IF(thing->isPermanentAndMayBeShared(),
989 !runtime()->permanentAtomsPopulated());
990
991 // We don't need to pass MarkRootCompartments options on to children.
992 constexpr uint32_t traverseOpts =
993 opts & ~MarkingOptions::MarkRootCompartments;
994
995 traverse<traverseOpts>(thing);
996
997 if constexpr (bool(opts & MarkingOptions::MarkRootCompartments)) {
998 // Mark the compartment as live.
999 SetCompartmentHasMarkedCells(thing);
1000 }
1001 }
1002 }
1003
1004 // The |traverse| method overloads select the traversal strategy for each kind.
1005 //
1006 // There are three possible strategies:
1007 //
1008 // 1. traceChildren
1009 //
1010 // The simplest traversal calls out to the fully generic traceChildren
1011 // function to visit the child edges. In the absence of other traversal
1012 // mechanisms, this function will rapidly grow the stack past its bounds and
1013 // crash the process. Thus, this generic tracing should only be used in cases
1014 // where subsequent tracing will not recurse.
1015 //
1016 // 2. scanChildren
1017 //
1018 // Strings, Shapes, and Scopes are extremely common, but have simple patterns
1019 // of recursion. We traverse trees of these edges immediately, with
1020 // aggressive, manual inlining, implemented by eagerlyTraceChildren.
1021 //
1022 // 3. pushThing
1023 //
1024 // Objects are extremely common and can contain arbitrarily nested graphs, so
1025 // are not trivially inlined. In this case we use the mark stack to control
1026 // recursion. JitCode shares none of these properties, but is included for
1027 // historical reasons. JSScript normally cannot recurse, but may be used as a
1028 // weakmap key and thereby recurse into weakmapped values.
1029
1030 template <uint32_t opts>
1031 void GCMarker::traverse(BaseShape* thing) {
1032 traceChildren<opts>(thing);
1033 }
1034 template <uint32_t opts>
1035 void GCMarker::traverse(GetterSetter* thing) {
1036 traceChildren<opts>(thing);
1037 }
1038 template <uint32_t opts>
1039 void GCMarker::traverse(JS::Symbol* thing) {
1040 #ifdef NIGHTLY_BUILD
1041 if constexpr (bool(opts & MarkingOptions::MarkImplicitEdges)) {
1042 pushThing<opts>(thing);
1043 return;
1044 }
1045 #endif
1046 traceChildren<opts>(thing);
1047 }
1048 template <uint32_t opts>
1049 void GCMarker::traverse(JS::BigInt* thing) {
1050 traceChildren<opts>(thing);
1051 }
1052 template <uint32_t opts>
1053 void GCMarker::traverse(RegExpShared* thing) {
1054 traceChildren<opts>(thing);
1055 }
1056 template <uint32_t opts>
1057 void GCMarker::traverse(JSString* thing) {
1058 scanChildren<opts>(thing);
1059 }
1060 template <uint32_t opts>
1061 void GCMarker::traverse(Shape* thing) {
1062 scanChildren<opts>(thing);
1063 }
1064 template <uint32_t opts>
1065 void GCMarker::traverse(PropMap* thing) {
1066 scanChildren<opts>(thing);
1067 }
1068 template <uint32_t opts>
1069 void GCMarker::traverse(js::Scope* thing) {
1070 scanChildren<opts>(thing);
1071 }
1072 template <uint32_t opts>
1073 void GCMarker::traverse(JSObject* thing) {
1074 pushThing<opts>(thing);
1075 }
1076 template <uint32_t opts>
1077 void GCMarker::traverse(jit::JitCode* thing) {
1078 pushThing<opts>(thing);
1079 }
1080 template <uint32_t opts>
1081 void GCMarker::traverse(BaseScript* thing) {
1082 pushThing<opts>(thing);
1083 }
1084 template <uint32_t opts>
1085 void GCMarker::traverse(SmallBuffer* thing) {
1086 // Buffer contents are traced by their owning GC thing.
1087 }
1088
1089 template <uint32_t opts, typename T>
1090 void js::GCMarker::traceChildren(T* thing) {
1091 MOZ_ASSERT(!thing->isPermanentAndMayBeShared());
1092 MOZ_ASSERT(thing->isMarkedAny());
1093 AutoSetTracingSource asts(tracer(), thing);
1094 thing->traceChildren(tracer());
1095 }
1096
1097 template <uint32_t opts, typename T>
1098 void js::GCMarker::scanChildren(T* thing) {
1099 MOZ_ASSERT(!thing->isPermanentAndMayBeShared());
1100 MOZ_ASSERT(thing->isMarkedAny());
1101 eagerlyMarkChildren<opts>(thing);
1102 }
1103
1104 template <uint32_t opts, typename T>
1105 void js::GCMarker::pushThing(T* thing) {
1106 MOZ_ASSERT(!thing->isPermanentAndMayBeShared());
1107 MOZ_ASSERT(thing->isMarkedAny());
1108 pushTaggedPtr(thing);
1109 }
1110
1111 template void js::GCMarker::markAndTraverse<MarkingOptions::None, JSObject>(
1112 JSObject* thing);
1113 template void js::GCMarker::markAndTraverse<MarkingOptions::MarkImplicitEdges,
1114 JSObject>(JSObject* thing);
1115 template void js::GCMarker::markAndTraverse<
1116 MarkingOptions::MarkRootCompartments, JSObject>(JSObject* thing);
1117
1118 #ifdef DEBUG
1119 void GCMarker::setCheckAtomMarking(bool check) {
1120 MOZ_ASSERT(check != checkAtomMarking);
1121 checkAtomMarking = check;
1122 }
1123 #endif
1124
1125 template <typename S, typename T>
1126 inline void GCMarker::checkTraversedEdge(S source, T* target) {
1127 #ifdef DEBUG
1128 // Atoms and Symbols do not have or mark their internal pointers,
1129 // respectively.
1130 MOZ_ASSERT(!source->isPermanentAndMayBeShared());
1131
1132 // Shared things are already black so we will not mark them.
1133 if (target->isPermanentAndMayBeShared()) {
1134 Zone* zone = target->zoneFromAnyThread();
1135 MOZ_ASSERT(!zone->wasGCStarted());
1136 MOZ_ASSERT(!zone->needsIncrementalBarrier());
1137 MOZ_ASSERT(target->isMarkedBlack());
1138 MOZ_ASSERT(!target->maybeCompartment());
1139 return;
1140 }
1141
1142 Zone* sourceZone = source->zone();
1143 Zone* targetZone = target->zone();
1144
1145 // Atoms and Symbols do not have access to a compartment pointer, or we'd need
1146 // to adjust the subsequent check to catch that case.
1147 MOZ_ASSERT_IF(targetZone->isAtomsZone(), !target->maybeCompartment());
1148
1149 // The Zones must match, unless the target is an atom.
1150 MOZ_ASSERT(targetZone == sourceZone || targetZone->isAtomsZone());
1151
1152 // If we are marking an atom, that atom must be marked in the source zone's
1153 // atom bitmap.
1154 if (checkAtomMarking && !sourceZone->isAtomsZone() &&
1155 targetZone->isAtomsZone()) {
1156 MOZ_ASSERT(target->runtimeFromAnyThread()->gc.atomMarking.atomIsMarked(
1157 sourceZone, reinterpret_cast<TenuredCell*>(target)));
1158 }
1159
1160 // If we have access to a compartment pointer for both things, they must
1161 // match.
1162 MOZ_ASSERT_IF(source->maybeCompartment() && target->maybeCompartment(),
1163 source->maybeCompartment() == target->maybeCompartment());
1164 #endif
1165 }
1166
1167 template <uint32_t opts, typename S, typename T>
1168 void js::GCMarker::markAndTraverseEdge(S* source, T* target) {
1169 checkTraversedEdge(source, target);
1170 markAndTraverse<opts>(target);
1171 }
1172
1173 template <uint32_t opts, typename S, typename T>
1174 void js::GCMarker::markAndTraverseEdge(S* source, const T& target) {
1175 ApplyGCThingTyped(target, [this, source](auto t) {
1176 this->markAndTraverseEdge<opts>(source, t);
1177 });
1178 }
1179
1180 template <uint32_t opts>
1181 MOZ_NEVER_INLINE bool js::GCMarker::markAndTraversePrivateGCThing(
1182 JSObject* source, TenuredCell* target) {
1183 JS::TraceKind kind = target->getTraceKind();
1184 ApplyGCThingTyped(target, kind, [this, source](auto t) {
1185 this->markAndTraverseEdge<opts>(source, t);
1186 });
1187
1188 // Ensure stack headroom in case we pushed.
1189 if (MOZ_UNLIKELY(!stack.ensureSpace(ValueRangeWords))) {
1190 delayMarkingChildrenOnOOM(source);
1191 return false;
1192 }
1193
1194 return true;
1195 }
1196
1197 template <uint32_t opts>
1198 bool js::GCMarker::markAndTraverseSymbol(JSObject* source, JS::Symbol* target) {
1199 this->markAndTraverseEdge<opts>(source, target);
1200
1201 // Ensure stack headroom in case we pushed.
1202 if (MOZ_UNLIKELY(!stack.ensureSpace(ValueRangeWords))) {
1203 delayMarkingChildrenOnOOM(source);
1204 return false;
1205 }
1206
1207 return true;
1208 }
1209
1210 template <uint32_t opts, typename T>
1211 bool js::GCMarker::mark(T* thing) {
1212 if (!thing->isTenured()) {
1213 return false;
1214 }
1215
1216 // Don't mark symbols if we're not collecting the atoms zone.
1217 if constexpr (std::is_same_v<T, JS::Symbol>) {
1218 if (IsOwnedByOtherRuntime(runtime(), thing) ||
1219 !thing->zone()->isGCMarkingOrVerifyingPreBarriers()) {
1220 return false;
1221 }
1222 }
1223
1224 AssertShouldMarkInZone(this, thing);
1225
1226 MarkColor color =
1227 TraceKindCanBeGray<T>::value ? markColor() : MarkColor::Black;
1228
1229 if constexpr (bool(opts & MarkingOptions::ParallelMarking)) {
1230 return thing->asTenured().markIfUnmarkedThreadSafe(color);
1231 }
1232
1233 return thing->asTenured().markIfUnmarked(color);
1234 }
1235
1236 /*** Mark-stack Marking *****************************************************/
1237
1238 // Call the trace hook set on the object, if present.
1239 static inline void CallTraceHook(JSTracer* trc, JSObject* obj) {
1240 const JSClass* clasp = obj->getClass();
1241 MOZ_ASSERT(clasp);
1242
1243 if (clasp->hasTrace()) {
1244 AutoSetTracingSource asts(trc, obj);
1245 clasp->doTrace(trc, obj);
1246 }
1247 }
1248
1249 static gcstats::PhaseKind GrayMarkingPhaseForCurrentPhase(
1250 const gcstats::Statistics& stats) {
1251 using namespace gcstats;
1252 switch (stats.currentPhaseKind()) {
1253 case PhaseKind::MARK:
1254 return PhaseKind::MARK_GRAY;
1255 case PhaseKind::MARK_WEAK:
1256 return PhaseKind::MARK_GRAY_WEAK;
1257 default:
1258 MOZ_CRASH("Unexpected current phase");
1259 }
1260 }
1261
1262 size_t GCMarker::moveWork(GCMarker* dst, GCMarker* src, bool allowDistribute) {
1263 MOZ_ASSERT(dst->stack.isEmpty());
1264 MOZ_ASSERT(src->canDonateWork());
1265
1266 return MarkStack::moveWork(src, dst->stack, src->stack, allowDistribute);
1267 }
1268
1269 bool GCMarker::initStack() {
1270 MOZ_ASSERT(!isActive());
1271 MOZ_ASSERT(markColor_ == gc::MarkColor::Black);
1272 return stack.init();
1273 }
1274
1275 void GCMarker::resetStackCapacity() {
1276 MOZ_ASSERT(!isActive());
1277 MOZ_ASSERT(markColor_ == gc::MarkColor::Black);
1278 (void)stack.resetStackCapacity();
1279 }
1280
1281 void GCMarker::freeStack() {
1282 MOZ_ASSERT(!isActive());
1283 MOZ_ASSERT(markColor_ == gc::MarkColor::Black);
1284 stack.clearAndFreeStack();
1285 }
1286
1287 bool GCMarker::markUntilBudgetExhausted(SliceBudget& budget,
1288 ShouldReportMarkTime reportTime) {
1289 #ifdef DEBUG
1290 MOZ_ASSERT(!strictCompartmentChecking);
1291 strictCompartmentChecking = true;
1292 auto acc = mozilla::MakeScopeExit([&] { strictCompartmentChecking = false; });
1293 #endif
1294
1295 if (budget.isOverBudget()) {
1296 return false;
1297 }
1298
1299 if (isWeakMarking()) {
1300 return doMarking<MarkingOptions::MarkImplicitEdges>(budget, reportTime);
1301 }
1302
1303 return doMarking<MarkingOptions::None>(budget, reportTime);
1304 }
1305
1306 template <uint32_t opts>
1307 bool GCMarker::doMarking(SliceBudget& budget, ShouldReportMarkTime reportTime) {
1308 GCRuntime& gc = runtime()->gc;
1309
1310 // This method leaves the mark color as it found it.
1311
1312 if (hasBlackEntries() && !markOneColor<opts, MarkColor::Black>(budget)) {
1313 return false;
1314 }
1315
1316 if (hasGrayEntries()) {
1317 mozilla::Maybe<gcstats::AutoPhase> ap;
1318 if (reportTime) {
1319 auto& stats = runtime()->gc.stats();
1320 ap.emplace(stats, GrayMarkingPhaseForCurrentPhase(stats));
1321 }
1322
1323 if (!markOneColor<opts, MarkColor::Gray>(budget)) {
1324 return false;
1325 }
1326 }
1327
1328 // Mark children of things that caused too deep recursion during the above
1329 // tracing. All normal marking happens before any delayed marking.
1330 if (gc.hasDelayedMarking()) {
1331 gc.markAllDelayedChildren(reportTime);
1332 }
1333
1334 MOZ_ASSERT(!gc.hasDelayedMarking());
1335 MOZ_ASSERT(isDrained());
1336
1337 return true;
1338 }
1339
1340 template <uint32_t opts, MarkColor color>
1341 bool GCMarker::markOneColor(SliceBudget& budget) {
1342 AutoSetMarkColor setColor(*this, color);
1343 AutoUpdateMarkStackRanges updateRanges(*this);
1344
1345 while (processMarkStackTop<opts>(budget)) {
1346 if (stack.isEmpty()) {
1347 return true;
1348 }
1349 }
1350
1351 return false;
1352 }
1353
1354 bool GCMarker::markCurrentColorInParallel(SliceBudget& budget) {
1355 MOZ_ASSERT(stack.elementsRangesAreValid);
1356
1357 ParallelMarker::AtomicCount& waitingTaskCount =
1358 parallelMarker_->waitingTaskCountRef();
1359
1360 while (processMarkStackTop<MarkingOptions::ParallelMarking>(budget)) {
1361 if (stack.isEmpty()) {
1362 return true;
1363 }
1364
1365 // TODO: It might be better to only check this occasionally, possibly
1366 // combined with the slice budget check. Experiments with giving this its
1367 // own counter resulted in worse performance.
1368 if (waitingTaskCount && shouldDonateWork()) {
1369 parallelMarker_->donateWorkFrom(this);
1370 }
1371 }
1372
1373 return false;
1374 }
1375
1376 #ifdef DEBUG
1377 bool GCMarker::markOneObjectForTest(JSObject* obj) {
1378 MOZ_ASSERT(obj->zone()->isGCMarking());
1379 MOZ_ASSERT(!obj->isMarked(markColor()));
1380
1381 size_t oldPosition = stack.position();
1382 markAndTraverse<NormalMarkingOptions>(obj);
1383 if (stack.position() == oldPosition) {
1384 return false;
1385 }
1386
1387 AutoUpdateMarkStackRanges updateRanges(*this);
1388
1389 SliceBudget unlimited = SliceBudget::unlimited();
1390 processMarkStackTop<NormalMarkingOptions>(unlimited);
1391
1392 return true;
1393 }
1394 #endif
1395
1396 static inline void CheckForCompartmentMismatch(JSObject* obj, JSObject* obj2) {
1397 #ifdef DEBUG
1398 if (MOZ_UNLIKELY(obj->compartment() != obj2->compartment())) {
1399 fprintf(
1400 stderr,
1401 "Compartment mismatch in pointer from %s object slot to %s object\n",
1402 obj->getClass()->name, obj2->getClass()->name);
1403 MOZ_CRASH("Compartment mismatch");
1404 }
1405 #endif
1406 }
1407
1408 static inline size_t NumUsedFixedSlots(NativeObject* obj) {
1409 return std::min(obj->numFixedSlots(), obj->slotSpan());
1410 }
1411
1412 static inline size_t NumUsedDynamicSlots(NativeObject* obj) {
1413 size_t nfixed = obj->numFixedSlots();
1414 size_t nslots = obj->slotSpan();
1415 if (nslots < nfixed) {
1416 return 0;
1417 }
1418
1419 return nslots - nfixed;
1420 }
1421
1422 void GCMarker::updateRangesAtStartOfSlice() {
1423 MOZ_ASSERT(!stack.elementsRangesAreValid);
1424
1425 for (MarkStackIter iter(stack); !iter.done(); iter.next()) {
1426 if (iter.isSlotsOrElementsRange()) {
1427 MarkStack::SlotsOrElementsRange range = iter.slotsOrElementsRange();
1428 JSObject* obj = range.ptr().asRangeObject();
1429 if (!obj->is<NativeObject>()) {
1430 // The object owning the range was swapped with a non-native object by
1431 // the mutator. The barriers at the end of JSObject::swap ensure that
1432 // everything gets marked so there's nothing to do here.
1433 range.setEmpty();
1434 iter.setSlotsOrElementsRange(range);
1435 } else if (range.kind() == SlotsOrElementsKind::Elements) {
1436 NativeObject* obj = &range.ptr().asRangeObject()->as<NativeObject>();
1437 size_t index = range.start();
1438 size_t numShifted = obj->getElementsHeader()->numShiftedElements();
1439 index -= std::min(numShifted, index);
1440 range.setStart(index);
1441 iter.setSlotsOrElementsRange(range);
1442 }
1443 }
1444 }
1445
1446 #ifdef DEBUG
1447 stack.elementsRangesAreValid = true;
1448 #endif
1449 }
1450
1451 void GCMarker::updateRangesAtEndOfSlice() {
1452 MOZ_ASSERT(stack.elementsRangesAreValid);
1453
1454 for (MarkStackIter iter(stack); !iter.done(); iter.next()) {
1455 if (iter.isSlotsOrElementsRange()) {
1456 MarkStack::SlotsOrElementsRange range = iter.slotsOrElementsRange();
1457 if (range.kind() == SlotsOrElementsKind::Elements) {
1458 NativeObject* obj = &range.ptr().asRangeObject()->as<NativeObject>();
1459 size_t numShifted = obj->getElementsHeader()->numShiftedElements();
1460 range.setStart(range.start() + numShifted);
1461 iter.setSlotsOrElementsRange(range);
1462 }
1463 }
1464 }
1465
1466 #ifdef DEBUG
1467 stack.elementsRangesAreValid = false;
1468 #endif
1469 }
1470
1471 template <uint32_t opts>
1472 inline bool GCMarker::processMarkStackTop(SliceBudget& budget) {
1473 /*
1474 * This function uses explicit goto and scans objects directly. This allows us
1475 * to eliminate tail recursion and significantly improve the marking
1476 * performance, see bug 641025.
1477 *
1478 * Note that the mutator can change the size and layout of objects between
1479 * marking slices, so we must check slots and element ranges read from the
1480 * stack.
1481 */
1482
1483 MOZ_ASSERT(!stack.isEmpty());
1484 MOZ_ASSERT(stack.elementsRangesAreValid);
1485 MOZ_ASSERT_IF(markColor() == MarkColor::Gray, !hasBlackEntries());
1486
1487 JSObject* obj; // The object being scanned.
1488 SlotsOrElementsKind kind; // The kind of slot range being scanned, if any.
1489 HeapSlot* base; // Slot range base pointer.
1490 size_t index; // Index of the next slot to mark.
1491 size_t end; // End of slot range to mark.
1492
1493 if (stack.peekTag() == MarkStack::SlotsOrElementsRangeTag) {
1494 auto range = stack.popSlotsOrElementsRange();
1495 obj = range.ptr().asRangeObject();
1496 NativeObject* nobj = &obj->as<NativeObject>();
1497 kind = range.kind();
1498 index = range.start();
1499
1500 switch (kind) {
1501 case SlotsOrElementsKind::FixedSlots: {
1502 base = nobj->fixedSlots();
1503 end = NumUsedFixedSlots(nobj);
1504 break;
1505 }
1506
1507 case SlotsOrElementsKind::DynamicSlots: {
1508 base = nobj->slots_;
1509 end = NumUsedDynamicSlots(nobj);
1510 break;
1511 }
1512
1513 case SlotsOrElementsKind::Elements: {
1514 base = nobj->getDenseElements();
1515 end = nobj->getDenseInitializedLength();
1516 break;
1517 }
1518
1519 case SlotsOrElementsKind::Unused: {
1520 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unused SlotsOrElementsKind");
1521 }
1522 }
1523
1524 goto scan_value_range;
1525 }
1526
1527 budget.step();
1528 if (budget.isOverBudget()) {
1529 return false;
1530 }
1531
1532 {
1533 MarkStack::TaggedPtr ptr = stack.popPtr();
1534 switch (ptr.tag()) {
1535 case MarkStack::ObjectTag: {
1536 obj = ptr.as<JSObject>();
1537 AssertShouldMarkInZone(this, obj);
1538 goto scan_obj;
1539 }
1540
1541 case MarkStack::SymbolTag: {
1542 #ifdef NIGHTLY_BUILD
1543 auto* symbol = ptr.as<JS::Symbol>();
1544 if constexpr (bool(opts & MarkingOptions::MarkImplicitEdges)) {
1545 markImplicitEdges(symbol);
1546 }
1547 AutoSetTracingSource asts(tracer(), symbol);
1548 symbol->traceChildren(tracer());
1549 return true;
1550 #else
1551 MOZ_CRASH("symbols-as-weakmap-keys is enabled only on Nightly");
1552 #endif
1553 }
1554
1555 case MarkStack::JitCodeTag: {
1556 auto* code = ptr.as<jit::JitCode>();
1557 AutoSetTracingSource asts(tracer(), code);
1558 code->traceChildren(tracer());
1559 return true;
1560 }
1561
1562 case MarkStack::ScriptTag: {
1563 auto* script = ptr.as<BaseScript>();
1564 if constexpr (bool(opts & MarkingOptions::MarkImplicitEdges)) {
1565 markImplicitEdges(script);
1566 }
1567 AutoSetTracingSource asts(tracer(), script);
1568 script->traceChildren(tracer());
1569 return true;
1570 }
1571
1572 default:
1573 MOZ_CRASH("Invalid tag in mark stack");
1574 }
1575 }
1576
1577 return true;
1578
1579 scan_value_range:
1580 while (index < end) {
1581 MOZ_ASSERT(stack.capacity() >= stack.position() + ValueRangeWords);
1582
1583 budget.step();
1584 if (budget.isOverBudget()) {
1585 pushValueRange(obj, kind, index, end);
1586 return false;
1587 }
1588
1589 const Value& v = base[index];
1590 index++;
1591
1592 if (!v.isGCThing()) {
1593 continue;
1594 }
1595
1596 if (v.isString()) {
1597 markAndTraverseEdge<opts>(obj, v.toString());
1598 } else if (v.isObject()) {
1599 JSObject* obj2 = &v.toObject();
1600 #ifdef DEBUG
1601 if (!obj2) {
1602 fprintf(stderr,
1603 "processMarkStackTop found ObjectValue(nullptr) "
1604 "at %zu Values from end of range in object:\n",
1605 size_t(end - (index - 1)));
1606 obj->dump();
1607 }
1608 #endif
1609 CheckForCompartmentMismatch(obj, obj2);
1610 if (mark<opts>(obj2)) {
1611 // Save the rest of this value range for later and start scanning obj2's
1612 // children.
1613 pushValueRange(obj, kind, index, end);
1614 obj = obj2;
1615 goto scan_obj;
1616 }
1617 } else if (v.isSymbol()) {
1618 if (!markAndTraverseSymbol<opts>(obj, v.toSymbol())) {
1619 return true;
1620 }
1621 } else if (v.isBigInt()) {
1622 markAndTraverseEdge<opts>(obj, v.toBigInt());
1623 } else {
1624 MOZ_ASSERT(v.isPrivateGCThing());
1625 if (!markAndTraversePrivateGCThing<opts>(obj,
1626 &v.toGCThing()->asTenured())) {
1627 return true;
1628 }
1629 }
1630 }
1631
1632 return true;
1633
1634 scan_obj: {
1635 AssertShouldMarkInZone(this, obj);
1636
1637 if constexpr (bool(opts & MarkingOptions::MarkImplicitEdges)) {
1638 markImplicitEdges(obj);
1639 }
1640 markAndTraverseEdge<opts>(obj, obj->shape());
1641
1642 CallTraceHook(tracer(), obj);
1643
1644 if (!obj->is<NativeObject>()) {
1645 return true;
1646 }
1647
1648 NativeObject* nobj = &obj->as<NativeObject>();
1649
1650 // Ensure stack headroom for three ranges (fixed slots, dynamic slots and
1651 // elements).
1652 if (MOZ_UNLIKELY(!stack.ensureSpace(ValueRangeWords * 3))) {
1653 delayMarkingChildrenOnOOM(obj);
1654 return true;
1655 }
1656
1657 unsigned nslots = nobj->slotSpan();
1658
1659 if (nobj->hasDynamicSlots()) {
1660 ObjectSlots* slots = nobj->getSlotsHeader();
1661 MarkTenuredBuffer(nobj->zone(), slots);
1662 }
1663
1664 if (nobj->hasDynamicElements()) {
1665 void* elements = nobj->getUnshiftedElementsHeader();
1666 MarkTenuredBuffer(nobj->zone(), elements);
1667 }
1668
1669 if (!nobj->hasEmptyElements()) {
1670 base = nobj->getDenseElements();
1671 kind = SlotsOrElementsKind::Elements;
1672 index = 0;
1673 end = nobj->getDenseInitializedLength();
1674
1675 if (!nslots) {
1676 // No slots at all. Scan elements immediately.
1677 goto scan_value_range;
1678 }
1679
1680 pushValueRange(nobj, kind, index, end);
1681 }
1682
1683 unsigned nfixed = nobj->numFixedSlots();
1684 base = nobj->fixedSlots();
1685 kind = SlotsOrElementsKind::FixedSlots;
1686 index = 0;
1687
1688 if (nslots > nfixed) {
1689 // Push dynamic slots for later scan.
1690 pushValueRange(nobj, SlotsOrElementsKind::DynamicSlots, 0, nslots - nfixed);
1691 end = nfixed;
1692 } else {
1693 end = nslots;
1694 }
1695
1696 // Scan any fixed slots.
1697 goto scan_value_range;
1698 }
1699 }
1700
1701 /*** Mark Stack *************************************************************/
1702
1703 static_assert(sizeof(MarkStack::TaggedPtr) == sizeof(uintptr_t),
1704 "A TaggedPtr should be the same size as a pointer");
1705 static_assert((sizeof(MarkStack::SlotsOrElementsRange) % sizeof(uintptr_t)) ==
1706 0,
1707 "SlotsOrElementsRange size should be a multiple of "
1708 "the pointer size");
1709
1710 template <typename T>
1711 struct MapTypeToMarkStackTag {};
1712 template <>
1713 struct MapTypeToMarkStackTag<JSObject*> {
1714 static const auto value = MarkStack::ObjectTag;
1715 };
1716 template <>
1717 struct MapTypeToMarkStackTag<JS::Symbol*> {
1718 static const auto value = MarkStack::SymbolTag;
1719 };
1720 template <>
1721 struct MapTypeToMarkStackTag<jit::JitCode*> {
1722 static const auto value = MarkStack::JitCodeTag;
1723 };
1724 template <>
1725 struct MapTypeToMarkStackTag<BaseScript*> {
1726 static const auto value = MarkStack::ScriptTag;
1727 };
1728
1729 static inline bool TagIsRangeTag(MarkStack::Tag tag) {
1730 return tag == MarkStack::SlotsOrElementsRangeTag;
1731 }
1732
1733 inline MarkStack::TaggedPtr::TaggedPtr(Tag tag, Cell* ptr)
1734 : bits(tag | uintptr_t(ptr)) {
1735 assertValid();
1736 }
1737
1738 /* static */
1739 inline MarkStack::TaggedPtr MarkStack::TaggedPtr::fromBits(uintptr_t bits) {
1740 return TaggedPtr(bits);
1741 }
1742
1743 inline MarkStack::TaggedPtr::TaggedPtr(uintptr_t bits) : bits(bits) {
1744 assertValid();
1745 }
1746
1747 inline uintptr_t MarkStack::TaggedPtr::asBits() const { return bits; }
1748
1749 inline MarkStack::Tag MarkStack::TaggedPtr::tag() const {
1750 auto tag = Tag(bits & TagMask);
1751 MOZ_ASSERT(tag <= LastTag);
1752 return tag;
1753 }
1754
1755 inline Cell* MarkStack::TaggedPtr::ptr() const {
1756 return reinterpret_cast<Cell*>(bits & ~TagMask);
1757 }
1758
1759 inline void MarkStack::TaggedPtr::assertValid() const {
1760 (void)tag();
1761 MOZ_ASSERT(IsCellPointerValid(ptr()));
1762 }
1763
1764 template <typename T>
1765 inline T* MarkStack::TaggedPtr::as() const {
1766 MOZ_ASSERT(tag() == MapTypeToMarkStackTag<T*>::value);
1767 MOZ_ASSERT(ptr()->isTenured());
1768 MOZ_ASSERT(ptr()->is<T>());
1769 return static_cast<T*>(ptr());
1770 }
1771
1772 inline JSObject* MarkStack::TaggedPtr::asRangeObject() const {
1773 MOZ_ASSERT(TagIsRangeTag(tag()));
1774 MOZ_ASSERT(ptr()->isTenured());
1775 return ptr()->as<JSObject>();
1776 }
1777
1778 inline JSRope* MarkStack::TaggedPtr::asTempRope() const {
1779 MOZ_ASSERT(tag() == TempRopeTag);
1780 return &ptr()->as<JSString>()->asRope();
1781 }
1782
1783 inline MarkStack::SlotsOrElementsRange::SlotsOrElementsRange(
1784 SlotsOrElementsKind kindArg, JSObject* obj, size_t startArg)
1785 : startAndKind_((startArg << StartShift) | size_t(kindArg)),
1786 ptr_(SlotsOrElementsRangeTag, obj) {
1787 assertValid();
1788 MOZ_ASSERT(kind() == kindArg);
1789 MOZ_ASSERT(start() == startArg);
1790 }
1791
1792 /* static */
1793 inline MarkStack::SlotsOrElementsRange
1794 MarkStack::SlotsOrElementsRange::fromBits(uintptr_t startAndKind,
1795 uintptr_t ptr) {
1796 return SlotsOrElementsRange(startAndKind, ptr);
1797 }
1798
1799 inline MarkStack::SlotsOrElementsRange::SlotsOrElementsRange(
1800 uintptr_t startAndKind, uintptr_t ptr)
1801 : startAndKind_(startAndKind), ptr_(TaggedPtr::fromBits(ptr)) {
1802 assertValid();
1803 }
1804
1805 inline void MarkStack::SlotsOrElementsRange::assertValid() const {
1806 ptr_.assertValid();
1807 MOZ_ASSERT(TagIsRangeTag(ptr_.tag()));
1808 }
1809
1810 inline SlotsOrElementsKind MarkStack::SlotsOrElementsRange::kind() const {
1811 return SlotsOrElementsKind(startAndKind_ & KindMask);
1812 }
1813
1814 inline size_t MarkStack::SlotsOrElementsRange::start() const {
1815 return startAndKind_ >> StartShift;
1816 }
1817
1818 inline void MarkStack::SlotsOrElementsRange::setStart(size_t newStart) {
1819 startAndKind_ = (newStart << StartShift) | uintptr_t(kind());
1820 MOZ_ASSERT(start() == newStart);
1821 }
1822
1823 inline void MarkStack::SlotsOrElementsRange::setEmpty() {
1824 // Replace this SlotsOrElementsRange with something that's valid for marking
1825 // but doesn't involve accessing this range, which is now invalid. This
1826 // replaces the two-word range with two single-word entries for the owning
1827 // object.
1828 TaggedPtr entry(ObjectTag, ptr().asRangeObject());
1829 ptr_ = entry;
1830 startAndKind_ = entry.asBits();
1831 }
1832
1833 inline MarkStack::TaggedPtr MarkStack::SlotsOrElementsRange::ptr() const {
1834 return ptr_;
1835 }
1836
1837 inline uintptr_t MarkStack::SlotsOrElementsRange::asBits0() const {
1838 return startAndKind_;
1839 }
1840
1841 inline uintptr_t MarkStack::SlotsOrElementsRange::asBits1() const {
1842 return ptr_.asBits();
1843 }
1844
1845 MarkStack::MarkStack() { MOZ_ASSERT(isEmpty()); }
1846
1847 MarkStack::~MarkStack() {
1848 MOZ_ASSERT(isEmpty());
1849 clearAndFreeStack();
1850 }
1851
1852 void MarkStack::swap(MarkStack& other) {
1853 std::swap(stack_, other.stack_);
1854 std::swap(capacity_, other.capacity_);
1855 std::swap(topIndex_, other.topIndex_);
1856 #ifdef JS_GC_ZEAL
1857 std::swap(maxCapacity_, other.maxCapacity_);
1858 #endif
1859 #ifdef DEBUG
1860 std::swap(elementsRangesAreValid, other.elementsRangesAreValid);
1861 #endif
1862 }
1863
1864 bool MarkStack::init() { return resetStackCapacity(); }
1865
1866 bool MarkStack::resetStackCapacity() {
1867 MOZ_ASSERT(isEmpty());
1868
1869 size_t capacity = MARK_STACK_BASE_CAPACITY;
1870
1871 #ifdef JS_GC_ZEAL
1872 capacity = std::min(capacity, maxCapacity_.ref());
1873 #endif
1874
1875 return resize(capacity);
1876 }
1877
1878 #ifdef JS_GC_ZEAL
1879 void MarkStack::setMaxCapacity(size_t maxCapacity) {
1880 MOZ_ASSERT(maxCapacity != 0);
1881 MOZ_ASSERT(isEmpty());
1882
1883 maxCapacity_ = maxCapacity;
1884 if (capacity() > maxCapacity_) {
1885 // If the realloc fails, just keep using the existing stack; it's
1886 // not ideal but better than failing.
1887 (void)resize(maxCapacity_);
1888 }
1889 }
1890 #endif
1891
1892 MOZ_ALWAYS_INLINE bool MarkStack::indexIsEntryBase(size_t index) const {
1893 // The mark stack holds both TaggedPtr and SlotsOrElementsRange entries, which
1894 // are one or two words long respectively. Determine whether |index| points to
1895 // the base of an entry (i.e. the lowest word in memory).
1896 //
1897 // The possible cases are that |index| points to:
1898 // 1. a single word TaggedPtr entry => true
1899 // 2. the startAndKind_ word of SlotsOrElementsRange => true
1900 // (startAndKind_ is a uintptr_t tagged with SlotsOrElementsKind)
1901 // 3. the ptr_ word of SlotsOrElementsRange (itself a TaggedPtr) => false
1902 //
1903 // To check for case 3, interpret the word as a TaggedPtr: if it is tagged as
1904 // a SlotsOrElementsRange tagged pointer then we are inside such a range and
1905 // |index| does not point to the base of an entry. This requires that no
1906 // startAndKind_ word can be interpreted as such, which is arranged by making
1907 // SlotsOrElementsRangeTag zero and all SlotsOrElementsKind tags non-zero.
1908
1909 MOZ_ASSERT(index < capacity_);
1910 return (stack_[index] & TagMask) != SlotsOrElementsRangeTag;
1911 }
1912
1913 /* static */
1914 size_t MarkStack::moveWork(GCMarker* marker, MarkStack& dst, MarkStack& src,
1915 bool allowDistribute) {
1916 // Move some work from |src| to |dst|. Assumes |dst| is empty.
1917 //
1918 // When this method runs during parallel marking, we are on the thread that
1919 // owns |src|, and the thread that owns |dst| is blocked waiting on the
1920 // ParallelMarkTask::resumed condition variable.
1921
1922 MOZ_ASSERT(dst.isEmpty());
1923 MOZ_ASSERT(src.elementsRangesAreValid == dst.elementsRangesAreValid);
1924
1925 // Limit the size of moves to stop threads with work spending too much time
1926 // donating.
1927 static const size_t MaxWordsToMove = 4096;
1928
1929 size_t totalWords = src.position();
1930 size_t wordsToMove = std::min(totalWords / 2, MaxWordsToMove);
1931
1932 // Mark stack entries do not represent uniform amounts of marking work (they
1933 // are either single GC things or arbitrarily large arrays) and when the mark
1934 // stack is small the situation often arises where one thread repeatedly takes
1935 // what is in effect a small amount of marking work while leaving the other
1936 // thread with a whole lot more. To split the work up more effectively we
1937 // randomly distribute stack entries for small stack.
1938 //
1939 // This works by randomly choosing one of every pair of entries in |src| and
1940 // moving it to |dst| (rather than moving half of the stack as a contiguous
1941 // region).
1942 //
1943 // This has the effect of reducing the number of donations between threads. It
1944 // does not decrease average marking time but it does decrease variance of
1945 // marking time.
1946 static constexpr size_t MaxWordsToDistribute = 30;
1947 if (allowDistribute && totalWords <= MaxWordsToDistribute) {
1948 if (!dst.ensureSpace(totalWords)) {
1949 return 0;
1950 }
1951
1952 src.topIndex_ = 0;
1953
1954 // We will use bits from a single 64-bit random number.
1955 static_assert(HowMany(MaxWordsToDistribute, 2) <= 64);
1956 uint64_t randomBits = marker->random.ref().next();
1957 DebugOnly<size_t> randomBitCount = 64;
1958
1959 size_t i = 0; // Entry index.
1960 size_t pos = 0; // Source stack position.
1961 uintptr_t* data = src.stack_;
1962 while (pos < totalWords) {
1963 MOZ_ASSERT(src.indexIsEntryBase(pos));
1964
1965 // Randomly chose which stack to copy the entry to, with each half of each
1966 // pair of entries moving to different stacks.
1967 MOZ_ASSERT(randomBitCount != 0);
1968 bool whichStack = (randomBits & 1) ^ (i & 1);
1969 randomBits <<= i & 1;
1970 randomBitCount -= i & 1;
1971
1972 MarkStack& stack = whichStack ? dst : src;
1973
1974 bool isRange =
1975 pos < totalWords - 1 && TagIsRangeTag(Tag(data[pos + 1] & TagMask));
1976 if (isRange) {
1977 stack.infalliblePush(
1978 SlotsOrElementsRange::fromBits(data[pos], data[pos + 1]));
1979 pos += ValueRangeWords;
1980 } else {
1981 stack.infalliblePush(TaggedPtr::fromBits(data[pos]));
1982 pos++;
1983 }
1984
1985 i++;
1986 }
1987
1988 return totalWords;
1989 }
1990
1991 size_t targetPos = src.position() - wordsToMove;
1992
1993 // Adjust the target position in case it points to the middle of a two word
1994 // entry.
1995 if (!src.indexIsEntryBase(targetPos)) {
1996 targetPos--;
1997 wordsToMove++;
1998 }
1999 MOZ_ASSERT(src.indexIsEntryBase(targetPos));
2000 MOZ_ASSERT(targetPos < src.position());
2001 MOZ_ASSERT(targetPos > 0);
2002 MOZ_ASSERT(wordsToMove == src.position() - targetPos);
2003
2004 if (!dst.ensureSpace(wordsToMove)) {
2005 return 0;
2006 }
2007
2008 // TODO: This doesn't have good cache behaviour when moving work between
2009 // threads. It might be better if the original thread ended up with the top
2010 // part of the stack, in src words if this method stole from the bottom of
2011 // the stack rather than the top.
2012
2013 mozilla::PodCopy(dst.end(), src.stack_ + targetPos, wordsToMove);
2014 dst.topIndex_ += wordsToMove;
2015 dst.peekPtr().assertValid();
2016
2017 src.topIndex_ = targetPos;
2018 #ifdef DEBUG
2019 src.poisonUnused();
2020 #endif
2021 src.peekPtr().assertValid();
2022 return wordsToMove;
2023 }
2024
2025 void MarkStack::clearAndResetCapacity() {
2026 // Fall back to the smaller initial capacity so we don't hold on to excess
2027 // memory between GCs.
2028 topIndex_ = 0;
2029 (void)resetStackCapacity();
2030 }
2031
2032 void MarkStack::clearAndFreeStack() {
2033 // Free all stack memory so we don't hold on to excess memory between GCs.
2034 js_free(stack_);
2035 stack_ = nullptr;
2036 capacity_ = 0;
2037 topIndex_ = 0;
2038 }
2039
2040 template <typename T>
2041 inline bool MarkStack::push(T* ptr) {
2042 return push(TaggedPtr(MapTypeToMarkStackTag<T*>::value, ptr));
2043 }
2044
2045 inline bool MarkStack::pushTempRope(JSRope* rope) {
2046 return push(TaggedPtr(TempRopeTag, rope));
2047 }
2048
2049 inline bool MarkStack::push(const TaggedPtr& ptr) {
2050 if (!ensureSpace(1)) {
2051 return false;
2052 }
2053
2054 infalliblePush(ptr);
2055 return true;
2056 }
2057
2058 inline void MarkStack::infalliblePush(const TaggedPtr& ptr) {
2059 MOZ_ASSERT(position() + 1 <= capacity());
2060 *end() = ptr.asBits();
2061 topIndex_++;
2062 }
2063
2064 inline void MarkStack::infalliblePush(JSObject* obj, SlotsOrElementsKind kind,
2065 size_t start) {
2066 SlotsOrElementsRange range(kind, obj, start);
2067 infalliblePush(range);
2068 }
2069
2070 inline void MarkStack::infalliblePush(const SlotsOrElementsRange& range) {
2071 MOZ_ASSERT(position() + ValueRangeWords <= capacity());
2072
2073 range.assertValid();
2074 end()[0] = range.asBits0();
2075 end()[1] = range.asBits1();
2076 topIndex_ += ValueRangeWords;
2077 MOZ_ASSERT(TagIsRangeTag(peekTag()));
2078 }
2079
2080 inline MarkStack::TaggedPtr MarkStack::peekPtr() const {
2081 MOZ_ASSERT(!isEmpty());
2082 return TaggedPtr::fromBits(at(topIndex_ - 1));
2083 }
2084
2085 inline MarkStack::Tag MarkStack::peekTag() const {
2086 MOZ_ASSERT(!isEmpty());
2087 return peekPtr().tag();
2088 }
2089
2090 inline MarkStack::TaggedPtr MarkStack::popPtr() {
2091 MOZ_ASSERT(!isEmpty());
2092 MOZ_ASSERT(!TagIsRangeTag(peekTag()));
2093 peekPtr().assertValid();
2094 topIndex_--;
2095 return TaggedPtr::fromBits(*end());
2096 }
2097
2098 inline MarkStack::SlotsOrElementsRange MarkStack::popSlotsOrElementsRange() {
2099 MOZ_ASSERT(!isEmpty());
2100 MOZ_ASSERT(TagIsRangeTag(peekTag()));
2101 MOZ_ASSERT(position() >= ValueRangeWords);
2102
2103 topIndex_ -= ValueRangeWords;
2104 return SlotsOrElementsRange::fromBits(end()[0], end()[1]);
2105 }
2106
2107 inline bool MarkStack::ensureSpace(size_t count) {
2108 if (MOZ_LIKELY((topIndex_ + count) <= capacity())) {
2109 return true;
2110 }
2111
2112 return enlarge(count);
2113 }
2114
2115 MOZ_NEVER_INLINE bool MarkStack::enlarge(size_t count) {
2116 size_t required = capacity() + count;
2117 size_t newCapacity = mozilla::RoundUpPow2(required);
2118
2119 #ifdef JS_GC_ZEAL
2120 newCapacity = std::min(newCapacity, maxCapacity_.ref());
2121 if (newCapacity < required) {
2122 return false;
2123 }
2124 #endif
2125
2126 return resize(newCapacity);
2127 }
2128
2129 bool MarkStack::resize(size_t newCapacity) {
2130 MOZ_ASSERT(newCapacity != 0);
2131 MOZ_ASSERT(newCapacity >= position());
2132
2133 auto poisonOnExit = mozilla::MakeScopeExit([this]() { poisonUnused(); });
2134
2135 if (newCapacity == capacity_) {
2136 return true;
2137 }
2138
2139 uintptr_t* newStack =
2140 js_pod_realloc<uintptr_t>(stack_, capacity_, newCapacity);
2141 if (!newStack) {
2142 return false;
2143 }
2144
2145 stack_ = newStack;
2146 capacity_ = newCapacity;
2147 return true;
2148 }
2149
2150 inline void MarkStack::poisonUnused() {
2151 static_assert((JS_FRESH_MARK_STACK_PATTERN & TagMask) > LastTag,
2152 "The mark stack poison pattern must not look like a valid "
2153 "tagged pointer");
2154
2155 MOZ_ASSERT(topIndex_ <= capacity_);
2156 AlwaysPoison(stack_ + topIndex_, JS_FRESH_MARK_STACK_PATTERN,
2157 capacity_ - topIndex_, MemCheckKind::MakeUndefined);
2158 }
2159
2160 size_t MarkStack::sizeOfExcludingThis(
2161 mozilla::MallocSizeOf mallocSizeOf) const {
2162 return capacity_ * sizeof(uintptr_t);
2163 }
2164
2165 MarkStackIter::MarkStackIter(MarkStack& stack)
2166 : stack_(stack), pos_(stack.position()) {}
2167
2168 inline size_t MarkStackIter::position() const { return pos_; }
2169
2170 inline bool MarkStackIter::done() const { return position() == 0; }
2171
2172 inline void MarkStackIter::next() {
2173 if (isSlotsOrElementsRange()) {
2174 MOZ_ASSERT(position() >= ValueRangeWords);
2175 pos_ -= ValueRangeWords;
2176 return;
2177 }
2178
2179 MOZ_ASSERT(!done());
2180 pos_--;
2181 }
2182
2183 inline bool MarkStackIter::isSlotsOrElementsRange() const {
2184 return TagIsRangeTag(peekTag());
2185 }
2186
2187 inline MarkStack::Tag MarkStackIter::peekTag() const { return peekPtr().tag(); }
2188
2189 inline MarkStack::TaggedPtr MarkStackIter::peekPtr() const {
2190 MOZ_ASSERT(!done());
2191 return MarkStack::TaggedPtr::fromBits(stack_.at(pos_ - 1));
2192 }
2193
2194 inline MarkStack::SlotsOrElementsRange MarkStackIter::slotsOrElementsRange()
2195 const {
2196 MOZ_ASSERT(TagIsRangeTag(peekTag()));
2197 MOZ_ASSERT(position() >= ValueRangeWords);
2198
2199 uintptr_t* ptr = stack_.ptr(pos_ - ValueRangeWords);
2200 return MarkStack::SlotsOrElementsRange::fromBits(ptr[0], ptr[1]);
2201 }
2202
2203 inline void MarkStackIter::setSlotsOrElementsRange(
2204 const MarkStack::SlotsOrElementsRange& range) {
2205 MOZ_ASSERT(isSlotsOrElementsRange());
2206
2207 uintptr_t* ptr = stack_.ptr(pos_ - ValueRangeWords);
2208 ptr[0] = range.asBits0();
2209 ptr[1] = range.asBits1();
2210 }
2211
2212 /*** GCMarker ***************************************************************/
2213
2214 /*
2215 * WeakMapTraceAction::Expand: the GC is recomputing the liveness of WeakMap
2216 * entries by expanding each live WeakMap into its constituent key->value edges,
2217 * a table of which will be consulted in a later phase whenever marking a
2218 * potential key.
2219 */
2220 GCMarker::GCMarker(JSRuntime* rt)
2221 : tracer_(mozilla::VariantType<MarkingTracer>(), rt, this),
2222 runtime_(rt),
2223 haveSwappedStacks(false),
2224 markColor_(MarkColor::Black),
2225 state(NotActive),
2226 incrementalWeakMapMarkingEnabled(
2227 TuningDefaults::IncrementalWeakMapMarkingEnabled),
2228 random(js::GenerateRandomSeed(), js::GenerateRandomSeed())
2229 #ifdef DEBUG
2230 ,
2231 checkAtomMarking(true),
2232 strictCompartmentChecking(false)
2233 #endif
2234 {
2235 }
2236
2237 bool GCMarker::init() { return stack.init(); }
2238
2239 void GCMarker::start() {
2240 MOZ_ASSERT(state == NotActive);
2241 MOZ_ASSERT(stack.isEmpty());
2242 state = RegularMarking;
2243 setMarkColor(MarkColor::Black);
2244 }
2245
2246 static void ClearEphemeronEdges(JSRuntime* rt) {
2247 for (GCZonesIter zone(rt); !zone.done(); zone.next()) {
2248 zone->gcEphemeronEdges().clearAndCompact();
2249 zone->gcNurseryEphemeronEdges().clearAndCompact();
2250 }
2251 }
2252
2253 void GCMarker::stop() {
2254 MOZ_ASSERT(isDrained());
2255 MOZ_ASSERT(markColor() == MarkColor::Black);
2256 MOZ_ASSERT(!haveSwappedStacks);
2257
2258 if (state == NotActive) {
2259 return;
2260 }
2261 state = NotActive;
2262
2263 otherStack.clearAndFreeStack();
2264 ClearEphemeronEdges(runtime());
2265 unmarkGrayStack.clearAndFree();
2266 }
2267
2268 void GCMarker::reset() {
2269 state = NotActive;
2270
2271 stack.clearAndResetCapacity();
2272 otherStack.clearAndFreeStack();
2273 ClearEphemeronEdges(runtime());
2274 MOZ_ASSERT(isDrained());
2275
2276 setMarkColor(MarkColor::Black);
2277 MOZ_ASSERT(!haveSwappedStacks);
2278
2279 unmarkGrayStack.clearAndFree();
2280 }
2281
2282 void GCMarker::setMarkColor(gc::MarkColor newColor) {
2283 if (markColor_ == newColor) {
2284 return;
2285 }
2286
2287 // We don't support gray marking while there is black marking work to do.
2288 MOZ_ASSERT(!hasBlackEntries());
2289
2290 markColor_ = newColor;
2291
2292 // Switch stacks. We only need to do this if there are any stack entries (as
2293 // empty stacks are interchangeable) or to swtich back to the original stack.
2294 if (!isDrained() || haveSwappedStacks) {
2295 stack.swap(otherStack);
2296 haveSwappedStacks = !haveSwappedStacks;
2297 }
2298 }
2299
2300 bool GCMarker::hasEntries(MarkColor color) const {
2301 const MarkStack& stackForColor = color == markColor() ? stack : otherStack;
2302 return stackForColor.hasEntries();
2303 }
2304
2305 template <typename T>
2306 inline void GCMarker::pushTaggedPtr(T* ptr) {
2307 checkZone(ptr);
2308 if (!stack.push(ptr)) {
2309 delayMarkingChildrenOnOOM(ptr);
2310 }
2311 }
2312
2313 inline void GCMarker::pushValueRange(JSObject* obj, SlotsOrElementsKind kind,
2314 size_t start, size_t end) {
2315 checkZone(obj);
2316 MOZ_ASSERT(obj->is<NativeObject>());
2317 MOZ_ASSERT(start <= end);
2318
2319 if (start != end) {
2320 stack.infalliblePush(obj, kind, start);
2321 }
2322 }
2323
2324 void GCMarker::setRootMarkingMode(bool newState) {
2325 if (newState) {
2326 setMarkingStateAndTracer<RootMarkingTracer>(RegularMarking, RootMarking);
2327 } else {
2328 setMarkingStateAndTracer<MarkingTracer>(RootMarking, RegularMarking);
2329 }
2330 }
2331
2332 void GCMarker::enterParallelMarkingMode(ParallelMarker* pm) {
2333 MOZ_ASSERT(pm);
2334 MOZ_ASSERT(!parallelMarker_);
2335 setMarkingStateAndTracer<ParallelMarkingTracer>(RegularMarking,
2336 ParallelMarking);
2337 parallelMarker_ = pm;
2338 }
2339
2340 void GCMarker::leaveParallelMarkingMode() {
2341 MOZ_ASSERT(parallelMarker_);
2342 setMarkingStateAndTracer<MarkingTracer>(ParallelMarking, RegularMarking);
2343 parallelMarker_ = nullptr;
2344 }
2345
2346 // It may not be worth the overhead of donating very few mark stack entries. For
2347 // some (non-parallelizable) workloads this could lead to constantly
2348 // interrupting marking work and makes parallel marking slower than single
2349 // threaded.
2350 //
2351 // Conversely, we do want to try splitting up work occasionally or we may fail
2352 // to parallelize workloads that result in few mark stack entries.
2353 //
2354 // Therefore we try hard to split work up at the start of a slice (calling
2355 // canDonateWork) but when a slice is running we only donate if there is enough
2356 // work to make it worthwhile (calling shouldDonateWork).
2357 bool GCMarker::canDonateWork() const {
2358 return stack.position() > ValueRangeWords;
2359 }
2360 bool GCMarker::shouldDonateWork() const {
2361 constexpr size_t MinWordCount = 12;
2362 static_assert(MinWordCount >= ValueRangeWords,
2363 "We must always leave at least one stack entry.");
2364
2365 return stack.position() > MinWordCount;
2366 }
2367
2368 template <typename Tracer>
2369 void GCMarker::setMarkingStateAndTracer(MarkingState prev, MarkingState next) {
2370 MOZ_ASSERT(state == prev);
2371 state = next;
2372 tracer_.emplace<Tracer>(runtime(), this);
2373 }
2374
2375 bool GCMarker::enterWeakMarkingMode() {
2376 MOZ_ASSERT(tracer()->weakMapAction() == JS::WeakMapTraceAction::Expand);
2377 if (!runtime()->gc.haveAllImplicitEdges()) {
2378 return false;
2379 }
2380
2381 // During weak marking mode, we maintain a table mapping weak keys to
2382 // entries in known-live weakmaps. Initialize it with the keys of marked
2383 // weakmaps -- or more precisely, the keys of marked weakmaps that are
2384 // mapped to not yet live values. (Once bug 1167452 implements incremental
2385 // weakmap marking, this initialization step will become unnecessary, as
2386 // the table will already hold all such keys.)
2387
2388 // Set state before doing anything else, so any new key that is marked
2389 // during the following gcEphemeronEdges scan will itself be looked up in
2390 // gcEphemeronEdges and marked according to ephemeron rules.
2391 setMarkingStateAndTracer<WeakMarkingTracer>(RegularMarking, WeakMarking);
2392
2393 return true;
2394 }
2395
2396 IncrementalProgress JS::Zone::enterWeakMarkingMode(GCMarker* marker,
2397 SliceBudget& budget) {
2398 MOZ_ASSERT(marker->isWeakMarking());
2399
2400 if (!marker->incrementalWeakMapMarkingEnabled) {
2401 for (WeakMapBase* m : gcWeakMapList()) {
2402 if (IsMarked(m->mapColor())) {
2403 (void)m->markEntries(marker);
2404 }
2405 }
2406 return IncrementalProgress::Finished;
2407 }
2408
2409 // gcEphemeronEdges contains the keys from all weakmaps marked so far, or at
2410 // least the keys that might still need to be marked through. Scan through
2411 // gcEphemeronEdges and mark all values whose keys are marked. This marking
2412 // may recursively mark through other weakmap entries (immediately since we
2413 // are now in WeakMarking mode). The end result is a consistent state where
2414 // all values are marked if both their map and key are marked -- though note
2415 // that we may later leave weak marking mode, do some more marking, and then
2416 // enter back in.
2417 if (!isGCMarking()) {
2418 return IncrementalProgress::Finished;
2419 }
2420
2421 MOZ_ASSERT(gcNurseryEphemeronEdges().count() == 0);
2422
2423 for (auto r = gcEphemeronEdges().all(); !r.empty(); r.popFront()) {
2424 Cell* src = r.front().key();
2425 CellColor srcColor = gc::detail::GetEffectiveColor(marker, src);
2426 auto& edges = r.front().value();
2427
2428 if (IsMarked(srcColor) && edges.length() > 0) {
2429 uint32_t steps = edges.length();
2430 marker->markEphemeronEdges(edges, AsMarkColor(srcColor));
2431 budget.step(steps);
2432 if (budget.isOverBudget()) {
2433 return NotFinished;
2434 }
2435 }
2436 }
2437
2438 return IncrementalProgress::Finished;
2439 }
2440
2441 void GCMarker::leaveWeakMarkingMode() {
2442 if (state == RegularMarking) {
2443 return;
2444 }
2445
2446 setMarkingStateAndTracer<MarkingTracer>(WeakMarking, RegularMarking);
2447
2448 // The gcEphemeronEdges table is still populated and may be used during a
2449 // future weak marking mode within this GC.
2450 }
2451
2452 void GCMarker::abortLinearWeakMarking() {
2453 runtime()->gc.clearHaveAllImplicitEdges();
2454 if (state == WeakMarking) {
2455 leaveWeakMarkingMode();
2456 }
2457 }
2458
2459 MOZ_NEVER_INLINE void GCMarker::delayMarkingChildrenOnOOM(Cell* cell) {
2460 runtime()->gc.delayMarkingChildren(cell, markColor());
2461 }
2462
2463 bool GCRuntime::hasDelayedMarking() const {
2464 bool result = delayedMarkingList;
2465 MOZ_ASSERT(result == (markLaterArenas != 0));
2466 return result;
2467 }
2468
2469 void GCRuntime::delayMarkingChildren(Cell* cell, MarkColor color) {
2470 // Synchronize access to delayed marking state during parallel marking.
2471 LockGuard<Mutex> lock(delayedMarkingLock);
2472
2473 Arena* arena = cell->asTenured().arena();
2474 if (!arena->onDelayedMarkingList()) {
2475 arena->setNextDelayedMarkingArena(delayedMarkingList);
2476 delayedMarkingList = arena;
2477 #ifdef DEBUG
2478 markLaterArenas++;
2479 #endif
2480 }
2481
2482 if (!arena->hasDelayedMarking(color)) {
2483 arena->setHasDelayedMarking(color, true);
2484 delayedMarkingWorkAdded = true;
2485 }
2486 }
2487
2488 void GCRuntime::markDelayedChildren(Arena* arena, MarkColor color) {
2489 JSTracer* trc = marker().tracer();
2490 JS::TraceKind kind = MapAllocToTraceKind(arena->getAllocKind());
2491 MarkColor colorToCheck =
2492 TraceKindCanBeMarkedGray(kind) ? color : MarkColor::Black;
2493
2494 for (ArenaCellIterUnderGC cell(arena); !cell.done(); cell.next()) {
2495 if (cell->isMarked(colorToCheck)) {
2496 ApplyGCThingTyped(cell, kind, [trc, this](auto t) {
2497 t->traceChildren(trc);
2498 marker().markImplicitEdges(t);
2499 });
2500 }
2501 }
2502 }
2503
2504 /*
2505 * Process arenas from |delayedMarkingList| by marking the unmarked children of
2506 * marked cells of color |color|.
2507 *
2508 * This is called twice, first to mark gray children and then to mark black
2509 * children.
2510 */
2511 void GCRuntime::processDelayedMarkingList(MarkColor color) {
2512 // Marking delayed children may add more arenas to the list, including arenas
2513 // we are currently processing or have previously processed. Handle this by
2514 // clearing a flag on each arena before marking its children. This flag will
2515 // be set again if the arena is re-added. Iterate the list until no new arenas
2516 // were added.
2517
2518 AutoSetMarkColor setColor(marker(), color);
2519 AutoUpdateMarkStackRanges updateRanges(marker());
2520
2521 do {
2522 delayedMarkingWorkAdded = false;
2523 for (Arena* arena = delayedMarkingList; arena;
2524 arena = arena->getNextDelayedMarking()) {
2525 if (arena->hasDelayedMarking(color)) {
2526 arena->setHasDelayedMarking(color, false);
2527 markDelayedChildren(arena, color);
2528 }
2529 }
2530 while (marker().hasEntriesForCurrentColor()) {
2531 SliceBudget budget = SliceBudget::unlimited();
2532 MOZ_ALWAYS_TRUE(
2533 marker().processMarkStackTop<NormalMarkingOptions>(budget));
2534 }
2535 } while (delayedMarkingWorkAdded);
2536
2537 MOZ_ASSERT(marker().isDrained());
2538 }
2539
2540 void GCRuntime::markAllDelayedChildren(ShouldReportMarkTime reportTime) {
2541 MOZ_ASSERT(CurrentThreadIsMainThread() || CurrentThreadIsPerformingGC());
2542 MOZ_ASSERT(marker().isDrained());
2543 MOZ_ASSERT(hasDelayedMarking());
2544
2545 mozilla::Maybe<gcstats::AutoPhase> ap;
2546 if (reportTime) {
2547 ap.emplace(stats(), gcstats::PhaseKind::MARK_DELAYED);
2548 }
2549
2550 // We have a list of arenas containing marked cells with unmarked children
2551 // where we ran out of stack space during marking. Both black and gray cells
2552 // in these arenas may have unmarked children. Mark black children first.
2553
2554 const MarkColor colors[] = {MarkColor::Black, MarkColor::Gray};
2555 for (MarkColor color : colors) {
2556 processDelayedMarkingList(color);
2557 rebuildDelayedMarkingList();
2558 }
2559
2560 MOZ_ASSERT(!hasDelayedMarking());
2561 }
2562
2563 void GCRuntime::rebuildDelayedMarkingList() {
2564 // Rebuild the delayed marking list, removing arenas which do not need further
2565 // marking.
2566
2567 Arena* listTail = nullptr;
2568 forEachDelayedMarkingArena([&](Arena* arena) {
2569 if (!arena->hasAnyDelayedMarking()) {
2570 arena->clearDelayedMarkingState();
2571 #ifdef DEBUG
2572 MOZ_ASSERT(markLaterArenas);
2573 markLaterArenas--;
2574 #endif
2575 return;
2576 }
2577
2578 appendToDelayedMarkingList(&listTail, arena);
2579 });
2580 appendToDelayedMarkingList(&listTail, nullptr);
2581 }
2582
2583 void GCRuntime::resetDelayedMarking() {
2584 MOZ_ASSERT(CurrentThreadIsMainThread());
2585
2586 forEachDelayedMarkingArena([&](Arena* arena) {
2587 MOZ_ASSERT(arena->onDelayedMarkingList());
2588 arena->clearDelayedMarkingState();
2589 #ifdef DEBUG
2590 MOZ_ASSERT(markLaterArenas);
2591 markLaterArenas--;
2592 #endif
2593 });
2594 delayedMarkingList = nullptr;
2595 MOZ_ASSERT(!markLaterArenas);
2596 }
2597
2598 inline void GCRuntime::appendToDelayedMarkingList(Arena** listTail,
2599 Arena* arena) {
2600 if (*listTail) {
2601 (*listTail)->updateNextDelayedMarkingArena(arena);
2602 } else {
2603 delayedMarkingList = arena;
2604 }
2605 *listTail = arena;
2606 }
2607
2608 template <typename F>
2609 inline void GCRuntime::forEachDelayedMarkingArena(F&& f) {
2610 Arena* arena = delayedMarkingList;
2611 Arena* next;
2612 while (arena) {
2613 next = arena->getNextDelayedMarking();
2614 f(arena);
2615 arena = next;
2616 }
2617 }
2618
2619 #ifdef DEBUG
2620 void GCMarker::checkZone(void* p) {
2621 MOZ_ASSERT(state != NotActive);
2622 DebugOnly<Cell*> cell = static_cast<Cell*>(p);
2623 MOZ_ASSERT_IF(cell->isTenured(),
2624 cell->asTenured().zone()->isCollectingFromAnyThread());
2625 }
2626 #endif
2627
2628 size_t GCMarker::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
2629 return mallocSizeOf(this) + stack.sizeOfExcludingThis(mallocSizeOf) +
2630 otherStack.sizeOfExcludingThis(mallocSizeOf);
2631 }
2632
2633 /*** IsMarked / IsAboutToBeFinalized ****************************************/
2634
2635 template <typename T>
2636 static inline void CheckIsMarkedThing(T* thing) {
2637 #define IS_SAME_TYPE_OR(name, type, _, _1) std::is_same_v<type, T> ||
2638 static_assert(JS_FOR_EACH_TRACEKIND(IS_SAME_TYPE_OR) false,
2639 "Only the base cell layout types are allowed into "
2640 "marking/tracing internals");
2641 #undef IS_SAME_TYPE_OR
2642
2643 #ifdef DEBUG
2644 MOZ_ASSERT(thing);
2645
2646 // Allow any thread access to uncollected things.
2647 Zone* zone = thing->zoneFromAnyThread();
2648 if (thing->isPermanentAndMayBeShared()) {
2649 MOZ_ASSERT(!zone->wasGCStarted());
2650 MOZ_ASSERT(!zone->needsIncrementalBarrier());
2651 MOZ_ASSERT(thing->isMarkedBlack());
2652 return;
2653 }
2654
2655 // Allow the current thread access if it is sweeping or in sweep-marking, but
2656 // try to check the zone. Some threads have access to all zones when sweeping.
2657 JS::GCContext* gcx = TlsGCContext.get();
2658 MOZ_ASSERT(gcx->gcUse() != GCUse::Finalizing);
2659 if (gcx->gcUse() == GCUse::Sweeping || gcx->gcUse() == GCUse::Marking) {
2660 MOZ_ASSERT_IF(gcx->gcSweepZone(),
2661 gcx->gcSweepZone() == zone || zone->isAtomsZone());
2662 return;
2663 }
2664
2665 // Otherwise only allow access from the main thread or this zone's associated
2666 // thread.
2667 MOZ_ASSERT(CurrentThreadCanAccessRuntime(thing->runtimeFromAnyThread()) ||
2668 CurrentThreadCanAccessZone(thing->zoneFromAnyThread()));
2669 #endif
2670 }
2671
2672 template <typename T>
2673 bool js::gc::IsMarkedInternal(JSRuntime* rt, T* thing) {
2674 // Don't depend on the mark state of other cells during finalization.
2675 MOZ_ASSERT(!CurrentThreadIsGCFinalizing());
2676 MOZ_ASSERT(rt->heapState() != JS::HeapState::MinorCollecting);
2677 MOZ_ASSERT(thing);
2678 CheckIsMarkedThing(thing);
2679
2680 // This is not used during minor sweeping nor used to update moved GC things.
2681 MOZ_ASSERT(!IsForwarded(thing));
2682
2683 // Permanent things are never marked by non-owning runtimes.
2684 TenuredCell* cell = &thing->asTenured();
2685 Zone* zone = cell->zoneFromAnyThread();
2686 #ifdef DEBUG
2687 if (IsOwnedByOtherRuntime(rt, thing)) {
2688 MOZ_ASSERT(!zone->wasGCStarted());
2689 MOZ_ASSERT(thing->isMarkedBlack());
2690 }
2691 #endif
2692
2693 return !zone->isGCMarking() || TenuredThingIsMarkedAny(thing);
2694 }
2695
2696 template <typename T>
2697 bool js::gc::IsAboutToBeFinalizedInternal(T* thing) {
2698 // Don't depend on the mark state of other cells during finalization.
2699 MOZ_ASSERT(!CurrentThreadIsGCFinalizing());
2700 MOZ_ASSERT(thing);
2701 CheckIsMarkedThing(thing);
2702
2703 // This is not used during minor sweeping nor used to update moved GC things.
2704 MOZ_ASSERT(!IsForwarded(thing));
2705
2706 if (!thing->isTenured()) {
2707 return false;
2708 }
2709
2710 // Permanent things are never finalized by non-owning runtimes.
2711 TenuredCell* cell = &thing->asTenured();
2712 Zone* zone = cell->zoneFromAnyThread();
2713 #ifdef DEBUG
2714 JSRuntime* rt = TlsGCContext.get()->runtimeFromAnyThread();
2715 if (IsOwnedByOtherRuntime(rt, thing)) {
2716 MOZ_ASSERT(!zone->wasGCStarted());
2717 MOZ_ASSERT(thing->isMarkedBlack());
2718 }
2719 #endif
2720
2721 return zone->isGCSweeping() && !TenuredThingIsMarkedAny(thing);
2722 }
2723
2724 template <typename T>
2725 bool js::gc::IsAboutToBeFinalizedInternal(const T& thing) {
2726 bool dying = false;
2727 ApplyGCThingTyped(
2728 thing, [&dying](auto t) { dying = IsAboutToBeFinalizedInternal(t); });
2729 return dying;
2730 }
2731
2732 SweepingTracer::SweepingTracer(JSRuntime* rt)
2733 : GenericTracerImpl(rt, JS::TracerKind::Sweeping,
2734 JS::WeakMapTraceAction::TraceKeysAndValues) {}
2735
2736 template <typename T>
2737 inline void SweepingTracer::onEdge(T** thingp, const char* name) {
2738 T* thing = *thingp;
2739 CheckIsMarkedThing(thing);
2740
2741 if (!thing->isTenured()) {
2742 return;
2743 }
2744
2745 // Permanent things are never finalized by non-owning runtimes.
2746 TenuredCell* cell = &thing->asTenured();
2747 Zone* zone = cell->zoneFromAnyThread();
2748 #ifdef DEBUG
2749 if (IsOwnedByOtherRuntime(runtime(), thing)) {
2750 MOZ_ASSERT(!zone->wasGCStarted());
2751 MOZ_ASSERT(thing->isMarkedBlack());
2752 }
2753 #endif
2754
2755 // It would be nice if we could assert that the zone of the tenured cell is in
2756 // the Sweeping state, but that isn't always true for:
2757 // - atoms
2758 // - the jitcode map
2759 // - the mark queue
2760 if ((zone->isGCSweeping() || zone->isAtomsZone()) && !cell->isMarkedAny()) {
2761 *thingp = nullptr;
2762 }
2763 }
2764
2765 namespace js::gc {
2766
2767 template <typename T>
2768 JS_PUBLIC_API bool TraceWeakEdge(JSTracer* trc, JS::Heap<T>* thingp) {
2769 return TraceEdgeInternal(trc, gc::ConvertToBase(thingp->unsafeAddress()),
2770 "JS::Heap edge");
2771 }
2772
2773 template <typename T>
2774 JS_PUBLIC_API bool EdgeNeedsSweepUnbarrieredSlow(T* thingp) {
2775 return IsAboutToBeFinalizedInternal(*ConvertToBase(thingp));
2776 }
2777
2778 // Instantiate a copy of the Tracing templates for each public GC type.
2779 #define INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS(type) \
2780 template JS_PUBLIC_API bool TraceWeakEdge<type>(JSTracer * trc, \
2781 JS::Heap<type>*); \
2782 template JS_PUBLIC_API bool EdgeNeedsSweepUnbarrieredSlow<type>(type*);
2783 JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS)
2784 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(
2785 INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS)
2786
2787 #define INSTANTIATE_INTERNAL_IS_MARKED_FUNCTION(type) \
2788 template bool IsMarkedInternal(JSRuntime* rt, type thing);
2789
2790 #define INSTANTIATE_INTERNAL_IATBF_FUNCTION(type) \
2791 template bool IsAboutToBeFinalizedInternal(type thingp);
2792
2793 #define INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND(_1, type, _2, \
2794 _3) \
2795 INSTANTIATE_INTERNAL_IS_MARKED_FUNCTION(type*) \
2796 INSTANTIATE_INTERNAL_IATBF_FUNCTION(type*)
2797
2798 JS_FOR_EACH_TRACEKIND(INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND)
2799
2800 #define INSTANTIATE_IATBF_FUNCTION_FOR_TAGGED_POINTER(type) \
2801 INSTANTIATE_INTERNAL_IATBF_FUNCTION(const type&)
2802
2803 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(
2804 INSTANTIATE_IATBF_FUNCTION_FOR_TAGGED_POINTER)
2805
2806 #undef INSTANTIATE_INTERNAL_IS_MARKED_FUNCTION
2807 #undef INSTANTIATE_INTERNAL_IATBF_FUNCTION
2808 #undef INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND
2809 #undef INSTANTIATE_IATBF_FUNCTION_FOR_TAGGED_POINTER
2810
2811 } // namespace js::gc
2812
2813 /*** Cycle Collector Barrier Implementation *********************************/
2814
2815 /*
2816 * The GC and CC are run independently. Consequently, the following sequence of
2817 * events can occur:
2818 * 1. GC runs and marks an object gray.
2819 * 2. The mutator runs (specifically, some C++ code with access to gray
2820 * objects) and creates a pointer from a JS root or other black object to
2821 * the gray object. If we re-ran a GC at this point, the object would now be
2822 * black.
2823 * 3. Now we run the CC. It may think it can collect the gray object, even
2824 * though it's reachable from the JS heap.
2825 *
2826 * To prevent this badness, we unmark the gray bit of an object when it is
2827 * accessed by callers outside XPConnect. This would cause the object to go
2828 * black in step 2 above. This must be done on everything reachable from the
2829 * object being returned. The following code takes care of the recursive
2830 * re-coloring.
2831 *
2832 * There is an additional complication for certain kinds of edges that are not
2833 * contained explicitly in the source object itself, such as from a weakmap key
2834 * to its value. These "implicit edges" are represented in some other
2835 * container object, such as the weakmap itself. In these
2836 * cases, calling unmark gray on an object won't find all of its children.
2837 *
2838 * Handling these implicit edges has two parts:
2839 * - A special pass enumerating all of the containers that know about the
2840 * implicit edges to fix any black-gray edges that have been created. This
2841 * is implemented in nsXPConnect::FixWeakMappingGrayBits.
2842 * - To prevent any incorrectly gray objects from escaping to live JS outside
2843 * of the containers, we must add unmark-graying read barriers to these
2844 * containers.
2845 */
2846
2847 #ifdef DEBUG
2848 struct AssertNonGrayTracer final : public JS::CallbackTracer {
2849 // This is used by the UnmarkGray tracer only, and needs to report itself as
2850 // the non-gray tracer to not trigger assertions. Do not use it in another
2851 // context without making this more generic.
2852 explicit AssertNonGrayTracer(JSRuntime* rt)
2853 : JS::CallbackTracer(rt, JS::TracerKind::UnmarkGray) {}
2854 void onChild(JS::GCCellPtr thing, const char* name) override {
2855 MOZ_ASSERT(!thing.asCell()->isMarkedGray());
2856 }
2857 };
2858 #endif
2859
2860 class js::gc::UnmarkGrayTracer final : public JS::CallbackTracer {
2861 public:
2862 // We set weakMapAction to WeakMapTraceAction::Skip because the cycle
2863 // collector will fix up any color mismatches involving weakmaps when it runs.
2864 explicit UnmarkGrayTracer(GCMarker* marker)
2865 : JS::CallbackTracer(marker->runtime(), JS::TracerKind::UnmarkGray,
2866 JS::WeakMapTraceAction::Skip),
2867 unmarkedAny(false),
2868 oom(false),
2869 marker(marker),
2870 stack(marker->unmarkGrayStack) {}
2871
2872 void unmark(JS::GCCellPtr cell);
2873
2874 // Whether we unmarked anything.
2875 bool unmarkedAny;
2876
2877 // Whether we ran out of memory.
2878 bool oom;
2879
2880 private:
2881 // Marker to use if we need to unmark in zones that are currently being
2882 // marked.
2883 GCMarker* marker;
2884
2885 // Stack of cells to traverse.
2886 Vector<JS::GCCellPtr, 0, SystemAllocPolicy>& stack;
2887
2888 void onChild(JS::GCCellPtr thing, const char* name) override;
2889 };
2890
2891 void UnmarkGrayTracer::onChild(JS::GCCellPtr thing, const char* name) {
2892 Cell* cell = thing.asCell();
2893
2894 // Cells in the nursery cannot be gray, and nor can certain kinds of tenured
2895 // cells. These must necessarily point only to black edges.
2896 if (!cell->isTenured() || !TraceKindCanBeMarkedGray(thing.kind())) {
2897 #ifdef DEBUG
2898 MOZ_ASSERT(!cell->isMarkedGray());
2899 AssertNonGrayTracer nongray(runtime());
2900 JS::TraceChildren(&nongray, thing);
2901 #endif
2902 return;
2903 }
2904
2905 TenuredCell& tenured = cell->asTenured();
2906 Zone* zone = tenured.zone();
2907
2908 // If the cell is in a zone whose mark bits are being cleared, then it will
2909 // end up white.
2910 if (zone->isGCPreparing()) {
2911 return;
2912 }
2913
2914 // If the cell is in a zone that we're currently marking, then it's possible
2915 // that it is currently white but will end up gray. To handle this case,
2916 // trigger the barrier for any cells in zones that are currently being
2917 // marked. This will ensure they will eventually get marked black.
2918 if (zone->isGCMarking()) {
2919 if (!cell->isMarkedBlack()) {
2920 TraceEdgeForBarrier(marker, &tenured, thing.kind());
2921 unmarkedAny = true;
2922 }
2923 return;
2924 }
2925
2926 if (!tenured.isMarkedGray()) {
2927 return;
2928 }
2929
2930 // TODO: It may be a small improvement to only use the atomic version during
2931 // parallel marking.
2932 tenured.markBlackAtomic();
2933 unmarkedAny = true;
2934
2935 if (!stack.append(thing)) {
2936 oom = true;
2937 }
2938 }
2939
2940 void UnmarkGrayTracer::unmark(JS::GCCellPtr cell) {
2941 MOZ_ASSERT(stack.empty());
2942
2943 onChild(cell, "unmarking root");
2944
2945 while (!stack.empty() && !oom) {
2946 TraceChildren(this, stack.popCopy());
2947 }
2948
2949 if (oom) {
2950 // If we run out of memory, we take a drastic measure: require that we
2951 // GC again before the next CC.
2952 stack.clear();
2953 runtime()->gc.setGrayBitsInvalid();
2954 return;
2955 }
2956 }
2957
2958 bool js::gc::UnmarkGrayGCThingUnchecked(GCMarker* marker, JS::GCCellPtr thing) {
2959 MOZ_ASSERT(thing);
2960
2961 mozilla::Maybe<AutoGeckoProfilerEntry> profilingStackFrame;
2962 if (JSContext* cx = TlsContext.get()) {
2963 profilingStackFrame.emplace(cx, "UnmarkGrayGCThing",
2964 JS::ProfilingCategoryPair::GCCC_UnmarkGray);
2965 }
2966
2967 UnmarkGrayTracer unmarker(marker);
2968 unmarker.unmark(thing);
2969 return unmarker.unmarkedAny;
2970 }
2971
2972 JS_PUBLIC_API bool JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr thing) {
2973 MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
2974 MOZ_ASSERT(!JS::RuntimeHeapIsCycleCollecting());
2975
2976 JSRuntime* rt = thing.asCell()->runtimeFromMainThread();
2977 if (thing.asCell()->zone()->isGCPreparing()) {
2978 // Mark bits are being cleared in preparation for GC.
2979 return false;
2980 }
2981
2982 MOZ_ASSERT(thing.asCell()->isMarkedGray());
2983 return UnmarkGrayGCThingUnchecked(&rt->gc.marker(), thing);
2984 }
2985
2986 void js::gc::UnmarkGrayGCThingRecursively(TenuredCell* cell) {
2987 JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr(cell, cell->getTraceKind()));
2988 }
2989
2990 bool js::UnmarkGrayShapeRecursively(Shape* shape) {
2991 return JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr(shape));
2992 }
2993
2994 #ifdef DEBUG
2995 Cell* js::gc::UninlinedForwarded(const Cell* cell) { return Forwarded(cell); }
2996 #endif
2997
2998 namespace js::debug {
2999
3000 MarkInfo GetMarkInfo(void* vp) {
3001 GCRuntime& gc = TlsGCContext.get()->runtime()->gc;
3002 if (gc.nursery().isInside(vp)) {
3003 ChunkBase* chunk = js::gc::detail::GetGCAddressChunkBase(vp);
3004 return chunk->getKind() == js::gc::ChunkKind::NurseryFromSpace
3005 ? MarkInfo::NURSERY_FROMSPACE
3006 : MarkInfo::NURSERY_TOSPACE;
3007 }
3008
3009 if (gc.isPointerWithinBufferAlloc(vp)) {
3010 return MarkInfo::BUFFER;
3011 }
3012
3013 if (!gc.isPointerWithinTenuredCell(vp)) {
3014 return MarkInfo::UNKNOWN;
3015 }
3016
3017 if (!IsCellPointerValid(vp)) {
3018 return MarkInfo::UNKNOWN;
3019 }
3020
3021 TenuredCell* cell = reinterpret_cast<TenuredCell*>(vp);
3022 if (cell->isMarkedGray()) {
3023 return MarkInfo::GRAY;
3024 }
3025 if (cell->isMarkedBlack()) {
3026 return MarkInfo::BLACK;
3027 }
3028 return MarkInfo::UNMARKED;
3029 }
3030
3031 uintptr_t* GetMarkWordAddress(Cell* cell) {
3032 if (!cell->isTenured()) {
3033 return nullptr;
3034 }
3035
3036 MarkBitmapWord* wordp;
3037 uintptr_t mask;
3038 ArenaChunkBase* chunk = gc::detail::GetCellChunkBase(&cell->asTenured());
3039 chunk->markBits.getMarkWordAndMask(&cell->asTenured(), ColorBit::BlackBit,
3040 &wordp, &mask);
3041 return reinterpret_cast<uintptr_t*>(wordp);
3042 }
3043
3044 uintptr_t GetMarkMask(Cell* cell, uint32_t colorBit) {
3045 MOZ_ASSERT(colorBit == 0 || colorBit == 1);
3046
3047 if (!cell->isTenured()) {
3048 return 0;
3049 }
3050
3051 ColorBit bit = colorBit == 0 ? ColorBit::BlackBit : ColorBit::GrayOrBlackBit;
3052 MarkBitmapWord* wordp;
3053 uintptr_t mask;
3054 ArenaChunkBase* chunk = gc::detail::GetCellChunkBase(&cell->asTenured());
3055 chunk->markBits.getMarkWordAndMask(&cell->asTenured(), bit, &wordp, &mask);
3056 return mask;
3057 }
3058
3059 } // namespace js::debug