Debian Codegraph @

js/src/gc/GCMarker.h

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 #ifndef gc_GCMarker_h
8 #define gc_GCMarker_h
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/Variant.h"
12 #include "mozilla/XorShift128PlusRNG.h"
13
14 #include "gc/Barrier.h"
15 #include "js/HashTable.h"
16 #include "js/TracingAPI.h"
17 #include "js/TypeDecls.h"
18 #include "threading/ProtectedData.h"
19
20 class JSRope;
21
22 namespace JS {
23 class SliceBudget;
24 }
25
26 namespace js {
27
28 class GCMarker;
29 class WeakMapBase;
30
31 #ifdef DEBUG
32 // Force stack resizing to ensure OOM test coverage in debug builds.
33 static const size_t MARK_STACK_BASE_CAPACITY = 4;
34 #else
35 static const size_t MARK_STACK_BASE_CAPACITY = 4096;
36 #endif
37
38 enum class SlotsOrElementsKind {
39 Unused = 0, // Must match SlotsOrElementsRangeTag
40 Elements,
41 FixedSlots,
42 DynamicSlots
43 };
44
45 namespace gc {
46
47 enum IncrementalProgress { NotFinished = 0, Finished };
48
49 class AutoSetMarkColor;
50 class AutoUpdateMarkStackRanges;
51 struct Cell;
52 class MarkStackIter;
53 class ParallelMarker;
54 class UnmarkGrayTracer;
55
56 // Ephemeron edges have two source nodes and one target, and mark the target
57 // with the minimum (least-marked) color of the sources. Currently, one of
58 // those sources will always be a WeakMapBase, so this will refer to its color
59 // at the time the edge is traced through. The other source's color will be
60 // given by the current mark color of the GCMarker.
61 struct EphemeronEdge {
62 MarkColor color;
63 Cell* target;
64
65 EphemeronEdge(MarkColor color_, Cell* cell) : color(color_), target(cell) {}
66 };
67
68 using EphemeronEdgeVector = Vector<EphemeronEdge, 2, js::SystemAllocPolicy>;
69
70 using EphemeronEdgeTable = HashMap<Cell*, EphemeronEdgeVector,
71 PointerHasher<Cell*>, js::SystemAllocPolicy>;
72
73 /*
74 * The mark stack. Pointers in this stack are "gray" in the GC sense, but
75 * their references may be marked either black or gray (in the CC sense).
76 *
77 * When the mark stack is full, the GC does not call js::TraceChildren to mark
78 * the reachable "children" of the thing. Rather the thing is put aside and
79 * js::TraceChildren is called later when the mark stack is empty.
80 *
81 * To implement such delayed marking of the children with minimal overhead for
82 * the normal case of sufficient stack, we link arenas into a list using
83 * Arena::setNextDelayedMarkingArena(). The head of the list is stored in
84 * GCMarker::delayedMarkingList. GCMarker::delayMarkingChildren() adds arenas
85 * to the list as necessary while markAllDelayedChildren() pops the arenas from
86 * the stack until it is empty.
87 */
88 class MarkStack {
89 public:
90 /*
91 * We use a common mark stack to mark GC things of different types and use
92 * the explicit tags to distinguish them when it cannot be deduced from
93 * the context of push or pop operation.
94 */
95 enum Tag {
96 SlotsOrElementsRangeTag = 0, // Must match SlotsOrElementsKind::Unused.
97 ObjectTag,
98 SymbolTag,
99 JitCodeTag,
100 ScriptTag,
101 TempRopeTag,
102
103 LastTag = TempRopeTag
104 };
105
106 static const uintptr_t TagMask = 7;
107 static_assert(TagMask >= uintptr_t(LastTag),
108 "The tag mask must subsume the tags.");
109 static_assert(TagMask <= gc::CellAlignMask,
110 "The tag mask must be embeddable in a Cell*.");
111
112 class TaggedPtr {
113 uintptr_t bits;
114
115 Cell* ptr() const;
116
117 explicit TaggedPtr(uintptr_t bits);
118
119 public:
120 TaggedPtr(Tag tag, Cell* ptr);
121 static TaggedPtr fromBits(uintptr_t bits);
122
123 uintptr_t asBits() const;
124 Tag tag() const;
125 template <typename T>
126 T* as() const;
127
128 JSObject* asRangeObject() const;
129 JSRope* asTempRope() const;
130
131 void assertValid() const;
132 };
133
134 class SlotsOrElementsRange {
135 uintptr_t startAndKind_;
136 TaggedPtr ptr_;
137
138 static constexpr size_t StartShift = 2;
139 static constexpr size_t KindMask = (1 << StartShift) - 1;
140
141 SlotsOrElementsRange(uintptr_t startAndKind, uintptr_t ptr);
142
143 public:
144 SlotsOrElementsRange(SlotsOrElementsKind kind, JSObject* obj, size_t start);
145 static SlotsOrElementsRange fromBits(uintptr_t startAndKind, uintptr_t ptr);
146
147 void assertValid() const;
148
149 uintptr_t asBits0() const;
150 uintptr_t asBits1() const;
151
152 SlotsOrElementsKind kind() const;
153 size_t start() const;
154 TaggedPtr ptr() const;
155
156 void setStart(size_t newStart);
157 void setEmpty();
158 };
159
160 MarkStack();
161 ~MarkStack();
162
163 MarkStack(const MarkStack& other) = delete;
164 MarkStack& operator=(const MarkStack& other) = delete;
165
166 void swap(MarkStack& other);
167
168 // The unit for capacity is mark stack words.
169 size_t capacity() const { return capacity_; }
170 #ifdef JS_GC_ZEAL
171 void setMaxCapacity(size_t maxCapacity);
172 #endif
173
174 size_t position() const { return topIndex_; }
175
176 [[nodiscard]] bool init();
177 [[nodiscard]] bool resetStackCapacity();
178
179 template <typename T>
180 [[nodiscard]] bool push(T* ptr);
181 void infalliblePush(const SlotsOrElementsRange& range);
182 void infalliblePush(JSObject* obj, SlotsOrElementsKind kind, size_t start);
183 [[nodiscard]] bool push(const TaggedPtr& ptr);
184 void infalliblePush(const TaggedPtr& ptr);
185
186 // GCMarker::eagerlyMarkChildren uses unused marking stack as temporary
187 // storage to hold rope pointers.
188 [[nodiscard]] bool pushTempRope(JSRope* rope);
189
190 bool isEmpty() const { return position() == 0; }
191 bool hasEntries() const { return !isEmpty(); }
192
193 Tag peekTag() const;
194 TaggedPtr popPtr();
195 SlotsOrElementsRange popSlotsOrElementsRange();
196
197 void clearAndResetCapacity();
198 void clearAndFreeStack();
199
200 void poisonUnused();
201
202 [[nodiscard]] bool ensureSpace(size_t count);
203
204 static size_t moveWork(GCMarker* marker, MarkStack& dst, MarkStack& src,
205 bool allowDistribute);
206
207 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
208
209 private:
210 uintptr_t at(size_t index) const {
211 MOZ_ASSERT(topIndex_ <= capacity_);
212 MOZ_ASSERT(index < topIndex_);
213 return stack_[index];
214 }
215 uintptr_t* ptr(size_t index) {
216 MOZ_ASSERT(topIndex_ <= capacity_);
217 MOZ_ASSERT(index <= topIndex_);
218 return stack_ + index;
219 }
220
221 // Return a pointer to the first unused word beyond the top of the stack.
222 uintptr_t* end() { return ptr(topIndex_); }
223
224 // Grow the stack, ensuring there is space to push |count| more words.
225 [[nodiscard]] bool enlarge(size_t count);
226
227 [[nodiscard]] bool resize(size_t newCapacity);
228
229 TaggedPtr peekPtr() const;
230
231 [[nodiscard]] bool pushTaggedPtr(Tag tag, Cell* ptr);
232
233 bool indexIsEntryBase(size_t index) const;
234
235 // Area of memory containing the stack.
236 MainThreadOrGCTaskData<uintptr_t*> stack_;
237
238 // Size of the stack in words.
239 MainThreadOrGCTaskData<size_t> capacity_;
240
241 // Index of the top of the stack.
242 MainThreadOrGCTaskData<size_t> topIndex_;
243
244 #ifdef JS_GC_ZEAL
245 // The maximum stack capacity to grow to.
246 MainThreadOrGCTaskData<size_t> maxCapacity_{SIZE_MAX};
247 #endif
248
249 #ifdef DEBUG
250 MainThreadOrGCTaskData<bool> elementsRangesAreValid;
251 friend class js::GCMarker;
252 #endif
253
254 friend class MarkStackIter;
255 };
256
257 static_assert(unsigned(SlotsOrElementsKind::Unused) ==
258 unsigned(MarkStack::SlotsOrElementsRangeTag),
259 "To split the mark stack we depend on being able to tell the "
260 "difference between SlotsOrElementsRange::startAndKind_ and a "
261 "tagged SlotsOrElementsRange");
262
263 class MOZ_STACK_CLASS MarkStackIter {
264 MarkStack& stack_;
265 size_t pos_;
266
267 public:
268 explicit MarkStackIter(MarkStack& stack);
269
270 bool done() const;
271 void next();
272
273 MarkStack::Tag peekTag() const;
274 MarkStack::TaggedPtr peekPtr() const;
275 bool isSlotsOrElementsRange() const;
276 MarkStack::SlotsOrElementsRange slotsOrElementsRange() const;
277 void setSlotsOrElementsRange(const MarkStack::SlotsOrElementsRange& range);
278
279 private:
280 size_t position() const;
281 };
282
283 // Bitmask of options to parameterize MarkingTracerT.
284 namespace MarkingOptions {
285 enum : uint32_t {
286 None = 0,
287
288 // Set the compartment's hasMarkedCells flag for roots.
289 MarkRootCompartments = 1,
290
291 // The marking tracer is operating in parallel. Use appropriate atomic
292 // accesses to update the mark bits correctly.
293 ParallelMarking = 2,
294
295 // Mark any implicit edges if we are in weak marking mode.
296 MarkImplicitEdges = 4,
297 };
298 } // namespace MarkingOptions
299
300 // A default set of marking options that works during normal marking and weak
301 // marking modes. Used for barriers and testing code.
302 constexpr uint32_t NormalMarkingOptions = MarkingOptions::MarkImplicitEdges;
303
304 template <uint32_t markingOptions>
305 class MarkingTracerT
306 : public GenericTracerImpl<MarkingTracerT<markingOptions>> {
307 public:
308 MarkingTracerT(JSRuntime* runtime, GCMarker* marker);
309 virtual ~MarkingTracerT() = default;
310
311 template <typename T>
312 void onEdge(T** thingp, const char* name);
313 friend class GenericTracerImpl<MarkingTracerT<markingOptions>>;
314
315 GCMarker* getMarker();
316 };
317
318 using MarkingTracer = MarkingTracerT<MarkingOptions::None>;
319 using RootMarkingTracer = MarkingTracerT<MarkingOptions::MarkRootCompartments>;
320 using WeakMarkingTracer = MarkingTracerT<MarkingOptions::MarkImplicitEdges>;
321 using ParallelMarkingTracer = MarkingTracerT<MarkingOptions::ParallelMarking>;
322
323 enum ShouldReportMarkTime : bool {
324 ReportMarkTime = true,
325 DontReportMarkTime = false
326 };
327
328 } /* namespace gc */
329
330 class GCMarker {
331 enum MarkingState : uint8_t {
332 // Have not yet started marking.
333 NotActive,
334
335 // Root marking mode. This sets the hasMarkedCells flag on compartments
336 // containing objects and scripts, which is used to make sure we clean up
337 // dead compartments.
338 RootMarking,
339
340 // Main marking mode. Weakmap marking will be populating the
341 // gcEphemeronEdges tables but not consulting them. The state will
342 // transition to WeakMarking until it is done, then back to RegularMarking.
343 RegularMarking,
344
345 // Like RegularMarking but with multiple threads running in parallel.
346 ParallelMarking,
347
348 // Same as RegularMarking except now every marked obj/script is immediately
349 // looked up in the gcEphemeronEdges table to find edges generated by
350 // weakmap keys, and traversing them to their values. Transitions back to
351 // RegularMarking when done.
352 WeakMarking,
353 };
354
355 public:
356 explicit GCMarker(JSRuntime* rt);
357 [[nodiscard]] bool init();
358
359 JSRuntime* runtime() { return runtime_; }
360 JSTracer* tracer() {
361 return tracer_.match([](auto& t) -> JSTracer* { return &t; });
362 }
363
364 #ifdef JS_GC_ZEAL
365 void setMaxCapacity(size_t maxCap) { stack.setMaxCapacity(maxCap); }
366 #endif
367
368 bool isActive() const { return state != NotActive; }
369 bool isRegularMarking() const { return state == RegularMarking; }
370 bool isParallelMarking() const { return state == ParallelMarking; }
371 bool isWeakMarking() const { return state == WeakMarking; }
372
373 gc::MarkColor markColor() const { return markColor_; }
374
375 bool isDrained() const { return stack.isEmpty() && otherStack.isEmpty(); }
376
377 bool hasEntriesForCurrentColor() { return stack.hasEntries(); }
378 bool hasBlackEntries() const { return hasEntries(gc::MarkColor::Black); }
379 bool hasGrayEntries() const { return hasEntries(gc::MarkColor::Gray); }
380 bool hasEntries(gc::MarkColor color) const;
381
382 bool canDonateWork() const;
383 bool shouldDonateWork() const;
384
385 void start();
386 void stop();
387 void reset();
388
389 [[nodiscard]] bool markUntilBudgetExhausted(
390 JS::SliceBudget& budget,
391 gc::ShouldReportMarkTime reportTime = gc::ReportMarkTime);
392
393 void setRootMarkingMode(bool newState);
394
395 bool enterWeakMarkingMode();
396 void leaveWeakMarkingMode();
397
398 void enterParallelMarkingMode(gc::ParallelMarker* pm);
399 void leaveParallelMarkingMode();
400
401 // Do not use linear-time weak marking for the rest of this collection.
402 // Currently, this will only be triggered by an OOM when updating needed data
403 // structures.
404 void abortLinearWeakMarking();
405
406 #ifdef DEBUG
407 // We can't check atom marking if the helper thread lock is already held by
408 // the current thread. This allows us to disable the check.
409 void setCheckAtomMarking(bool check);
410
411 bool shouldCheckCompartments() { return strictCompartmentChecking; }
412
413 bool markOneObjectForTest(JSObject* obj);
414 #endif
415
416 bool markCurrentColorInParallel(JS::SliceBudget& budget);
417
418 template <uint32_t markingOptions, gc::MarkColor>
419 bool markOneColor(JS::SliceBudget& budget);
420
421 static size_t moveWork(GCMarker* dst, GCMarker* src, bool allowDistribute);
422
423 [[nodiscard]] bool initStack();
424 void resetStackCapacity();
425 void freeStack();
426
427 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
428
429 static GCMarker* fromTracer(JSTracer* trc) {
430 MOZ_ASSERT(trc->isMarkingTracer());
431 auto* marker = reinterpret_cast<GCMarker*>(uintptr_t(trc) -
432 offsetof(GCMarker, tracer_));
433 MOZ_ASSERT(marker->tracer() == trc);
434 return marker;
435 }
436
437 // Internal public methods, for ease of use by the rest of the GC:
438
439 // If |thing| is unmarked, mark it and then traverse its children.
440 template <uint32_t, typename T>
441 void markAndTraverse(T* thing);
442
443 template <typename T>
444 void markImplicitEdges(T* markedThing);
445
446 private:
447 /*
448 * Care must be taken changing the mark color from gray to black. The cycle
449 * collector depends on the invariant that there are no black to gray edges
450 * in the GC heap. This invariant lets the CC not trace through black
451 * objects. If this invariant is violated, the cycle collector may free
452 * objects that are still reachable.
453 */
454 void setMarkColor(gc::MarkColor newColor);
455 friend class js::gc::AutoSetMarkColor;
456
457 template <typename Tracer>
458 void setMarkingStateAndTracer(MarkingState prev, MarkingState next);
459
460 // The mutator can shift object elements which could invalidate any elements
461 // index on the mark stack. Change the index to be relative to the elements
462 // allocation (to ignore shifted elements) while the mutator is running.
463 void updateRangesAtStartOfSlice();
464 void updateRangesAtEndOfSlice();
465 friend class gc::AutoUpdateMarkStackRanges;
466
467 template <uint32_t markingOptions>
468 bool processMarkStackTop(JS::SliceBudget& budget);
469 friend class gc::GCRuntime;
470
471 // Helper methods that coerce their second argument to the base pointer
472 // type.
473 template <uint32_t markingOptions, typename S>
474 void markAndTraverseObjectEdge(S source, JSObject* target) {
475 markAndTraverseEdge<markingOptions>(source, target);
476 }
477 template <uint32_t markingOptions, typename S>
478 void markAndTraverseStringEdge(S source, JSString* target) {
479 markAndTraverseEdge<markingOptions>(source, target);
480 }
481
482 template <uint32_t markingOptions, typename S, typename T>
483 void markAndTraverseEdge(S* source, T* target);
484 template <uint32_t markingOptions, typename S, typename T>
485 void markAndTraverseEdge(S* source, const T& target);
486
487 template <uint32_t markingOptions>
488 bool markAndTraversePrivateGCThing(JSObject* source, gc::TenuredCell* target);
489
490 template <uint32_t markingOptions>
491 bool markAndTraverseSymbol(JSObject* source, JS::Symbol* target);
492
493 template <typename S, typename T>
494 void checkTraversedEdge(S source, T* target);
495
496 // Mark the given GC thing, but do not trace its children. Return true
497 // if the thing became marked.
498 template <uint32_t markingOptions, typename T>
499 [[nodiscard]] bool mark(T* thing);
500
501 // Traverse a GC thing's children, using a strategy depending on the type.
502 // This can either processing them immediately or push them onto the mark
503 // stack for later.
504 #define DEFINE_TRAVERSE_METHOD(_1, Type, _2, _3) \
505 template <uint32_t> \
506 void traverse(Type* thing);
507 JS_FOR_EACH_TRACEKIND(DEFINE_TRAVERSE_METHOD)
508 #undef DEFINE_TRAVERSE_METHOD
509
510 // Process a marked thing's children by calling T::traceChildren().
511 template <uint32_t markingOptions, typename T>
512 void traceChildren(T* thing);
513
514 // Process a marked thing's children recursively using an iterative loop and
515 // manual dispatch, for kinds where this is possible.
516 template <uint32_t markingOptions, typename T>
517 void scanChildren(T* thing);
518
519 // Push a marked thing onto the mark stack. Its children will be marked later.
520 template <uint32_t markingOptions, typename T>
521 void pushThing(T* thing);
522
523 template <uint32_t markingOptions>
524 void eagerlyMarkChildren(JSLinearString* str);
525 template <uint32_t markingOptions>
526 void eagerlyMarkChildren(JSRope* rope);
527 template <uint32_t markingOptions>
528 void eagerlyMarkChildren(JSString* str);
529 template <uint32_t markingOptions>
530 void eagerlyMarkChildren(Shape* shape);
531 template <uint32_t markingOptions>
532 void eagerlyMarkChildren(PropMap* map);
533 template <uint32_t markingOptions>
534 void eagerlyMarkChildren(Scope* scope);
535
536 template <typename T>
537 inline void pushTaggedPtr(T* ptr);
538
539 inline void pushValueRange(JSObject* obj, SlotsOrElementsKind kind,
540 size_t start, size_t end);
541
542 // Mark through edges whose target color depends on the colors of two source
543 // entities (eg a WeakMap and one of its keys), and push the target onto the
544 // mark stack.
545 void markEphemeronEdges(gc::EphemeronEdgeVector& edges,
546 gc::MarkColor srcColor);
547 friend class JS::Zone;
548
549 #ifdef DEBUG
550 void checkZone(void* p);
551 #else
552 void checkZone(void* p) {}
553 #endif
554
555 template <uint32_t markingOptions>
556 bool doMarking(JS::SliceBudget& budget, gc::ShouldReportMarkTime reportTime);
557
558 void delayMarkingChildrenOnOOM(gc::Cell* cell);
559
560 /*
561 * The JSTracer used for marking. This can change depending on the current
562 * state.
563 */
564 mozilla::Variant<gc::MarkingTracer, gc::RootMarkingTracer,
565 gc::WeakMarkingTracer, gc::ParallelMarkingTracer>
566 tracer_;
567
568 JSRuntime* const runtime_;
569
570 // The main mark stack, holding entries of color |markColor_|.
571 gc::MarkStack stack;
572
573 // The auxiliary mark stack, which may contain entries of the other color.
574 gc::MarkStack otherStack;
575
576 // Track whether we're using the main or auxiliary stack.
577 MainThreadOrGCTaskData<bool> haveSwappedStacks;
578
579 // The current mark stack color.
580 MainThreadOrGCTaskData<gc::MarkColor> markColor_;
581
582 MainThreadOrGCTaskData<gc::ParallelMarker*> parallelMarker_;
583
584 Vector<JS::GCCellPtr, 0, SystemAllocPolicy> unmarkGrayStack;
585 friend class gc::UnmarkGrayTracer;
586
587 /* Track the state of marking. */
588 MainThreadOrGCTaskData<MarkingState> state;
589
590 public:
591 /*
592 * Whether weakmaps can be marked incrementally.
593 *
594 * JSGC_INCREMENTAL_WEAKMAP_ENABLED
595 * pref: javascript.options.mem.incremental_weakmap
596 */
597 MainThreadOrGCTaskData<bool> incrementalWeakMapMarkingEnabled;
598
599 /* Random number generator state. */
600 MainThreadOrGCTaskData<mozilla::non_crypto::XorShift128PlusRNG> random;
601
602 #ifdef DEBUG
603 private:
604 /* Assert that start and stop are called with correct ordering. */
605 MainThreadOrGCTaskData<bool> started;
606
607 /*
608 * Whether to check that atoms traversed are present in atom marking
609 * bitmap.
610 */
611 MainThreadOrGCTaskData<bool> checkAtomMarking;
612
613 /*
614 * If this is true, all marked objects must belong to a compartment being
615 * GCed. This is used to look for compartment bugs.
616 */
617 MainThreadOrGCTaskData<bool> strictCompartmentChecking;
618
619 public:
620 /*
621 * The compartment and zone of the object whose trace hook is currently being
622 * called, if any. Used to catch cross-compartment edges traced without use of
623 * TraceCrossCompartmentEdge.
624 */
625 MainThreadOrGCTaskData<Compartment*> tracingCompartment;
626 MainThreadOrGCTaskData<Zone*> tracingZone;
627 #endif // DEBUG
628 };
629
630 namespace gc {
631
632 /*
633 * Temporarily change the mark color while this class is on the stack.
634 *
635 * During incremental sweeping this also transitions zones in the
636 * current sweep group into the Mark or MarkGray state as appropriate.
637 */
638 class MOZ_RAII AutoSetMarkColor {
639 GCMarker& marker_;
640 MarkColor initialColor_;
641
642 public:
643 AutoSetMarkColor(GCMarker& marker, MarkColor newColor)
644 : marker_(marker), initialColor_(marker.markColor()) {
645 marker_.setMarkColor(newColor);
646 }
647
648 AutoSetMarkColor(GCMarker& marker, CellColor newColor)
649 : AutoSetMarkColor(marker, AsMarkColor(newColor)) {}
650
651 ~AutoSetMarkColor() { marker_.setMarkColor(initialColor_); }
652 };
653
654 } /* namespace gc */
655
656 } /* namespace js */
657
658 #endif /* gc_GCMarker_h */