-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathMarking.cpp
3963 lines (3378 loc) · 125 KB
/
Marking.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gc/Marking-inl.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/ReentrancyGuard.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Unused.h"
#include <algorithm>
#include <type_traits>
#include "jsfriendapi.h"
#include "builtin/ModuleObject.h"
#include "debugger/DebugAPI.h"
#include "gc/GCInternals.h"
#include "gc/Policy.h"
#include "jit/IonCode.h"
#include "js/GCTypeMacros.h" // JS_FOR_EACH_PUBLIC_{,TAGGED_}GC_POINTER_TYPE
#include "js/SliceBudget.h"
#include "util/DiagnosticAssertions.h"
#include "util/Memory.h"
#include "util/Poison.h"
#include "vm/ArgumentsObject.h"
#include "vm/ArrayObject.h"
#include "vm/BigIntType.h"
#include "vm/EnvironmentObject.h"
#include "vm/GeneratorObject.h"
#include "vm/RegExpShared.h"
#include "vm/Scope.h"
#include "vm/Shape.h"
#include "vm/SymbolType.h"
#include "vm/TypedArrayObject.h"
#include "wasm/WasmJS.h"
#include "gc/GC-inl.h"
#include "gc/Nursery-inl.h"
#include "gc/PrivateIterators-inl.h"
#include "gc/WeakMap-inl.h"
#include "gc/Zone-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Realm-inl.h"
#include "vm/StringType-inl.h"
using namespace js;
using namespace js::gc;
using JS::MapTypeToTraceKind;
using mozilla::DebugOnly;
using mozilla::IntegerRange;
using mozilla::PodCopy;
// [SMDOC] GC Tracing
//
// Tracing Overview
// ================
//
// Tracing, in this context, refers to an abstract visitation of some or all of
// the GC-controlled heap. The effect of tracing an edge of the graph depends
// on the subclass of the JSTracer on whose behalf we are tracing.
//
// Marking
// -------
//
// The primary JSTracer is the GCMarker. The marking tracer causes the target
// of each traversed edge to be marked black and the target edge's children to
// be marked either gray (in the gc algorithm sense) or immediately black.
//
// Callback
// --------
//
// The secondary JSTracer is the CallbackTracer. This simply invokes a callback
// on each edge in a child.
//
// The following is a rough outline of the general struture of the tracing
// internals.
//
/* clang-format off */
// //
// .---------. .---------. .--------------------------. .----------. //
// |TraceEdge| |TraceRoot| |TraceManuallyBarrieredEdge| ... |TraceRange| ... etc. //
// '---------' '---------' '--------------------------' '----------' //
// \ \ / / //
// \ \ .-----------------. / / //
// o------------->o-|TraceEdgeInternal|-o<----------------------o //
// '-----------------' //
// / \ //
// / \ //
// .---------. .----------. .-----------------. //
// |DoMarking| |DoCallback|-------> |<JSTraceCallback>|-----------> //
// '---------' '----------' '-----------------' //
// | //
// | //
// .-----------. //
// o------------->|traverse(T)| . //
// /_\ '-----------' ' . //
// | . . ' . //
// | . . ' . //
// | . . ' . //
// | .--------------. .--------------. ' . .-----------------------. //
// | |markAndScan(T)| |markAndPush(T)| ' - |markAndTraceChildren(T)| //
// | '--------------' '--------------' '-----------------------' //
// | | \ | //
// | | \ | //
// | .----------------------. .----------------. .------------------. //
// | |eagerlyMarkChildren(T)| |pushMarkStackTop|<===Oo |T::traceChildren()|--> //
// | '----------------------' '----------------' || '------------------' //
// | | || || //
// | | || || //
// | | || || //
// o<-----------------o<========================OO============Oo //
// //
// //
// Legend: //
// ------ Direct calls //
// . . . Static dispatch //
// ====== Dispatch through a manual stack. //
// //
/* clang-format on */
/*** Tracing Invariants *****************************************************/
#if defined(DEBUG)
template <typename T>
static inline bool IsThingPoisoned(T* thing) {
const uint8_t poisonBytes[] = {
JS_FRESH_NURSERY_PATTERN, JS_SWEPT_NURSERY_PATTERN,
JS_ALLOCATED_NURSERY_PATTERN, JS_FRESH_TENURED_PATTERN,
JS_MOVED_TENURED_PATTERN, JS_SWEPT_TENURED_PATTERN,
JS_ALLOCATED_TENURED_PATTERN, JS_FREED_HEAP_PTR_PATTERN,
JS_FREED_CHUNK_PATTERN, JS_FREED_ARENA_PATTERN,
JS_SWEPT_TI_PATTERN, JS_SWEPT_CODE_PATTERN,
JS_RESET_VALUE_PATTERN, JS_POISONED_JSSCRIPT_DATA_PATTERN,
JS_OOB_PARSE_NODE_PATTERN, JS_LIFO_UNDEFINED_PATTERN,
JS_LIFO_UNINITIALIZED_PATTERN,
};
const int numPoisonBytes = sizeof(poisonBytes) / sizeof(poisonBytes[0]);
uint32_t* p =
reinterpret_cast<uint32_t*>(reinterpret_cast<FreeSpan*>(thing) + 1);
// Note: all free patterns are odd to make the common, not-poisoned case a
// single test.
if ((*p & 1) == 0) {
return false;
}
for (int i = 0; i < numPoisonBytes; ++i) {
const uint8_t pb = poisonBytes[i];
const uint32_t pw = pb | (pb << 8) | (pb << 16) | (pb << 24);
if (*p == pw) {
return true;
}
}
return false;
}
bool js::IsTracerKind(JSTracer* trc, JS::CallbackTracer::TracerKind kind) {
return trc->isCallbackTracer() &&
trc->asCallbackTracer()->getTracerKind() == kind;
}
#endif
bool ThingIsPermanentAtomOrWellKnownSymbol(JSString* str) {
return str->isPermanentAtom();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JSLinearString* str) {
return str->isPermanentAtom();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JSAtom* atom) {
return atom->isPermanent();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(PropertyName* name) {
return name->isPermanent();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JS::Symbol* sym) {
return sym->isWellKnownSymbol();
}
template <typename T>
static inline bool IsOwnedByOtherRuntime(JSRuntime* rt, T thing) {
bool other = thing->runtimeFromAnyThread() != rt;
MOZ_ASSERT_IF(other, ThingIsPermanentAtomOrWellKnownSymbol(thing) ||
thing->zoneFromAnyThread()->isSelfHostingZone());
return other;
}
template <typename T>
void js::CheckTracedThing(JSTracer* trc, T* thing) {
#ifdef DEBUG
MOZ_ASSERT(trc);
MOZ_ASSERT(thing);
if (!trc->checkEdges()) {
return;
}
if (IsForwarded(thing)) {
MOZ_ASSERT(IsTracerKind(trc, JS::CallbackTracer::TracerKind::Moving) ||
trc->isTenuringTracer());
thing = Forwarded(thing);
}
/* This function uses data that's not available in the nursery. */
if (IsInsideNursery(thing)) {
return;
}
/*
* Permanent atoms and things in the self-hosting zone are not associated
* with this runtime, but will be ignored during marking.
*/
if (IsOwnedByOtherRuntime(trc->runtime(), thing)) {
return;
}
Zone* zone = thing->zoneFromAnyThread();
JSRuntime* rt = trc->runtime();
MOZ_ASSERT(zone->runtimeFromAnyThread() == rt);
bool isGcMarkingTracer = trc->isMarkingTracer();
bool isUnmarkGrayTracer =
IsTracerKind(trc, JS::CallbackTracer::TracerKind::UnmarkGray);
bool isClearEdgesTracer =
IsTracerKind(trc, JS::CallbackTracer::TracerKind::ClearEdges);
if (TlsContext.get()->isMainThreadContext()) {
// If we're on the main thread we must have access to the runtime and zone.
MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
MOZ_ASSERT(CurrentThreadCanAccessZone(zone));
} else {
MOZ_ASSERT(
isGcMarkingTracer || isUnmarkGrayTracer || isClearEdgesTracer ||
IsTracerKind(trc, JS::CallbackTracer::TracerKind::Moving) ||
IsTracerKind(trc, JS::CallbackTracer::TracerKind::GrayBuffering) ||
IsTracerKind(trc, JS::CallbackTracer::TracerKind::Sweeping));
MOZ_ASSERT_IF(!isClearEdgesTracer, CurrentThreadIsPerformingGC());
}
// It shouldn't be possible to trace into zones used by helper threads, except
// for use of ClearEdgesTracer by GCManagedDeletePolicy on a helper thread.
MOZ_ASSERT_IF(!isClearEdgesTracer, !zone->usedByHelperThread());
MOZ_ASSERT(thing->isAligned());
MOZ_ASSERT(MapTypeToTraceKind<std::remove_pointer_t<T>>::kind ==
thing->getTraceKind());
if (isGcMarkingTracer) {
GCMarker* gcMarker = GCMarker::fromTracer(trc);
MOZ_ASSERT(zone->shouldMarkInZone());
MOZ_ASSERT_IF(gcMarker->shouldCheckCompartments(),
zone->isCollectingFromAnyThread() || zone->isAtomsZone());
MOZ_ASSERT_IF(gcMarker->markColor() == MarkColor::Gray,
!zone->isGCMarkingBlackOnly() || zone->isAtomsZone());
MOZ_ASSERT(!(zone->isGCSweeping() || zone->isGCFinished() ||
zone->isGCCompacting()));
// Check that we don't stray from the current compartment and zone without
// using TraceCrossCompartmentEdge.
Compartment* comp = thing->maybeCompartment();
MOZ_ASSERT_IF(gcMarker->tracingCompartment && comp,
gcMarker->tracingCompartment == comp);
MOZ_ASSERT_IF(gcMarker->tracingZone,
gcMarker->tracingZone == zone || zone->isAtomsZone());
}
/*
* Try to assert that the thing is allocated.
*
* We would like to assert that the thing is not in the free list, but this
* check is very slow. Instead we check whether the thing has been poisoned:
* if it has not then we assume it is allocated, but if it has then it is
* either free or uninitialized in which case we check the free list.
*
* Further complications are that background sweeping may be running and
* concurrently modifiying the free list and that tracing is done off
* thread during compacting GC and reading the contents of the thing by
* IsThingPoisoned would be racy in this case.
*/
MOZ_ASSERT_IF(JS::RuntimeHeapIsBusy() && !zone->isGCSweeping() &&
!zone->isGCFinished() && !zone->isGCCompacting(),
!IsThingPoisoned(thing) ||
!InFreeList(thing->asTenured().arena(), thing));
#endif
}
template <typename T>
void js::CheckTracedThing(JSTracer* trc, T thing) {
ApplyGCThingTyped(thing, [](auto t) { CheckTracedThing(t); });
}
namespace js {
#define IMPL_CHECK_TRACED_THING(_, type, _1, _2) \
template void CheckTracedThing<type>(JSTracer*, type*);
JS_FOR_EACH_TRACEKIND(IMPL_CHECK_TRACED_THING);
#undef IMPL_CHECK_TRACED_THING
} // namespace js
static inline bool ShouldMarkCrossCompartment(GCMarker* marker, JSObject* src,
Cell* dstCell) {
MarkColor color = marker->markColor();
if (!dstCell->isTenured()) {
MOZ_ASSERT(color == MarkColor::Black);
return false;
}
TenuredCell& dst = dstCell->asTenured();
JS::Zone* dstZone = dst.zone();
if (!src->zone()->isGCMarking() && !dstZone->isGCMarking()) {
return false;
}
if (color == MarkColor::Black) {
// Check our sweep groups are correct: we should never have to
// mark something in a zone that we have started sweeping.
MOZ_ASSERT_IF(!dst.isMarkedBlack(), !dstZone->isGCSweeping());
/*
* Having black->gray edges violates our promise to the cycle collector so
* we ensure that gray things we encounter when marking black end up getting
* marked black.
*
* This can happen for two reasons:
*
* 1) If we're collecting a compartment and it has an edge to an uncollected
* compartment it's possible that the source and destination of the
* cross-compartment edge should be gray, but the source was marked black by
* the write barrier.
*
* 2) If we yield during gray marking and the write barrier marks a gray
* thing black.
*
* We handle the first case before returning whereas the second case happens
* as part of normal marking.
*/
if (dst.isMarkedGray() && !dstZone->isGCMarking()) {
UnmarkGrayGCThingUnchecked(marker->runtime(),
JS::GCCellPtr(&dst, dst.getTraceKind()));
return false;
}
return dstZone->isGCMarking();
} else {
// Check our sweep groups are correct as above.
MOZ_ASSERT_IF(!dst.isMarkedAny(), !dstZone->isGCSweeping());
if (dstZone->isGCMarkingBlackOnly()) {
/*
* The destination compartment is being not being marked gray now,
* but it will be later, so record the cell so it can be marked gray
* at the appropriate time.
*/
if (!dst.isMarkedAny()) {
DelayCrossCompartmentGrayMarking(src);
}
return false;
}
return dstZone->isGCMarkingBlackAndGray();
}
}
static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
Cell* dstCell) {
if (!trc->isMarkingTracer()) {
return true;
}
return ShouldMarkCrossCompartment(GCMarker::fromTracer(trc), src, dstCell);
}
static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
const Value& val) {
return val.isGCThing() &&
ShouldTraceCrossCompartment(trc, src, val.toGCThing());
}
static void AssertShouldMarkInZone(Cell* thing) {
MOZ_ASSERT(thing->asTenured().zone()->shouldMarkInZone());
}
static void AssertShouldMarkInZone(JSString* str) {
#ifdef DEBUG
Zone* zone = str->zone();
MOZ_ASSERT(zone->shouldMarkInZone() || zone->isAtomsZone());
#endif
}
static void AssertShouldMarkInZone(JS::Symbol* sym) {
#ifdef DEBUG
Zone* zone = sym->asTenured().zone();
MOZ_ASSERT(zone->shouldMarkInZone() || zone->isAtomsZone());
#endif
}
#ifdef DEBUG
void js::gc::AssertRootMarkingPhase(JSTracer* trc) {
MOZ_ASSERT_IF(trc->isMarkingTracer(),
trc->runtime()->gc.state() == State::NotActive ||
trc->runtime()->gc.state() == State::MarkRoots);
}
#endif
/*** Tracing Interface ******************************************************/
template <typename T>
bool DoCallback(JS::CallbackTracer* trc, T** thingp, const char* name);
template <typename T>
bool DoCallback(JS::CallbackTracer* trc, T* thingp, const char* name);
template <typename T>
void DoMarking(GCMarker* gcmarker, T* thing);
template <typename T>
void DoMarking(GCMarker* gcmarker, const T& thing);
template <typename T>
static void TraceExternalEdgeHelper(JSTracer* trc, T* thingp,
const char* name) {
MOZ_ASSERT(InternalBarrierMethods<T>::isMarkable(*thingp));
TraceEdgeInternal(trc, ConvertToBase(thingp), name);
}
JS_PUBLIC_API void js::UnsafeTraceManuallyBarrieredEdge(JSTracer* trc,
JSObject** thingp,
const char* name) {
TraceEdgeInternal(trc, ConvertToBase(thingp), name);
}
template <typename T>
static void UnsafeTraceRootHelper(JSTracer* trc, T* thingp, const char* name) {
MOZ_ASSERT(thingp);
js::TraceNullableRoot(trc, thingp, name);
}
namespace js {
class AbstractGeneratorObject;
class SavedFrame;
} // namespace js
#define DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION(type) \
JS_PUBLIC_API void js::gc::TraceExternalEdge(JSTracer* trc, type* thingp, \
const char* name) { \
TraceExternalEdgeHelper(trc, thingp, name); \
}
// Define TraceExternalEdge for each public GC pointer type.
JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION)
JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION)
// Also, for the moment, define TraceExternalEdge for internal GC pointer types.
DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION(AbstractGeneratorObject*)
DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION(SavedFrame*)
#undef DEFINE_TRACE_EXTERNAL_EDGE_FUNCTION
#define DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(type) \
JS_PUBLIC_API void JS::UnsafeTraceRoot(JSTracer* trc, type* thingp, \
const char* name) { \
UnsafeTraceRootHelper(trc, thingp, name); \
}
// Define UnsafeTraceRoot for each public GC pointer type.
JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DEFINE_UNSAFE_TRACE_ROOT_FUNCTION)
JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DEFINE_UNSAFE_TRACE_ROOT_FUNCTION)
// Also, for the moment, define UnsafeTraceRoot for internal GC pointer types.
DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(AbstractGeneratorObject*)
DEFINE_UNSAFE_TRACE_ROOT_FUNCTION(SavedFrame*)
#undef DEFINE_UNSAFE_TRACE_ROOT_FUNCTION
namespace js {
namespace gc {
#define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type) \
template bool TraceEdgeInternal<type>(JSTracer*, type*, const char*); \
template void TraceRangeInternal<type>(JSTracer*, size_t len, type*, \
const char*);
#define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND(_1, type, _2, _3) \
INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type*)
JS_FOR_EACH_TRACEKIND(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND)
JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS)
#undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND
#undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS
} // namespace gc
} // namespace js
// In debug builds, makes a note of the current compartment before calling a
// trace hook or traceChildren() method on a GC thing.
class MOZ_RAII AutoSetTracingSource {
#ifdef DEBUG
GCMarker* marker = nullptr;
#endif
public:
template <typename T>
AutoSetTracingSource(JSTracer* trc, T* thing) {
#ifdef DEBUG
if (trc->isMarkingTracer() && thing) {
marker = GCMarker::fromTracer(trc);
MOZ_ASSERT(!marker->tracingZone);
marker->tracingZone = thing->asTenured().zone();
MOZ_ASSERT(!marker->tracingCompartment);
marker->tracingCompartment = thing->maybeCompartment();
}
#endif
}
~AutoSetTracingSource() {
#ifdef DEBUG
if (marker) {
marker->tracingZone = nullptr;
marker->tracingCompartment = nullptr;
}
#endif
}
};
// In debug builds, clear the trace hook compartment. This happens
// after the trace hook has called back into one of our trace APIs and we've
// checked the traced thing.
class MOZ_RAII AutoClearTracingSource {
#ifdef DEBUG
GCMarker* marker = nullptr;
JS::Zone* prevZone = nullptr;
Compartment* prevCompartment = nullptr;
#endif
public:
explicit AutoClearTracingSource(JSTracer* trc) {
#ifdef DEBUG
if (trc->isMarkingTracer()) {
marker = GCMarker::fromTracer(trc);
prevZone = marker->tracingZone;
marker->tracingZone = nullptr;
prevCompartment = marker->tracingCompartment;
marker->tracingCompartment = nullptr;
}
#endif
}
~AutoClearTracingSource() {
#ifdef DEBUG
if (marker) {
marker->tracingZone = prevZone;
marker->tracingCompartment = prevCompartment;
}
#endif
}
};
template <typename T>
void js::TraceManuallyBarrieredCrossCompartmentEdge(JSTracer* trc,
JSObject* src, T* dst,
const char* name) {
// Clear expected compartment for cross-compartment edge.
AutoClearTracingSource acts(trc);
if (ShouldTraceCrossCompartment(trc, src, *dst)) {
TraceEdgeInternal(trc, dst, name);
}
}
template void js::TraceManuallyBarrieredCrossCompartmentEdge<Value>(
JSTracer*, JSObject*, Value*, const char*);
template void js::TraceManuallyBarrieredCrossCompartmentEdge<JSObject*>(
JSTracer*, JSObject*, JSObject**, const char*);
template void js::TraceManuallyBarrieredCrossCompartmentEdge<BaseScript*>(
JSTracer*, JSObject*, BaseScript**, const char*);
template <typename T>
void js::TraceWeakMapKeyEdgeInternal(JSTracer* trc, Zone* weakMapZone,
T** thingp, const char* name) {
// We can't use ShouldTraceCrossCompartment here because that assumes the
// source of the edge is a CCW object which could be used to delay gray
// marking. Instead, assert that the weak map zone is in the same marking
// state as the target thing's zone and therefore we can go ahead and mark it.
#ifdef DEBUG
auto thing = *thingp;
if (trc->isMarkingTracer()) {
MOZ_ASSERT(weakMapZone->isGCMarking());
MOZ_ASSERT(weakMapZone->gcState() == thing->zone()->gcState());
}
#endif
// Clear expected compartment for cross-compartment edge.
AutoClearTracingSource acts(trc);
TraceEdgeInternal(trc, thingp, name);
}
template void js::TraceWeakMapKeyEdgeInternal<JSObject>(JSTracer*, Zone*,
JSObject**,
const char*);
template void js::TraceWeakMapKeyEdgeInternal<BaseScript>(JSTracer*, Zone*,
BaseScript**,
const char*);
template <typename T>
void js::TraceProcessGlobalRoot(JSTracer* trc, T* thing, const char* name) {
AssertRootMarkingPhase(trc);
MOZ_ASSERT(ThingIsPermanentAtomOrWellKnownSymbol(thing));
// We have to mark permanent atoms and well-known symbols through a special
// method because the default DoMarking implementation automatically skips
// them. Fortunately, atoms (permanent and non) cannot refer to other GC
// things so they do not need to go through the mark stack and may simply
// be marked directly. Moreover, well-known symbols can refer only to
// permanent atoms, so likewise require no subsquent marking.
CheckTracedThing(trc, *ConvertToBase(&thing));
AutoClearTracingSource acts(trc);
if (trc->isMarkingTracer()) {
thing->asTenured().markIfUnmarked(gc::MarkColor::Black);
} else {
DoCallback(trc->asCallbackTracer(), ConvertToBase(&thing), name);
}
}
template void js::TraceProcessGlobalRoot<JSAtom>(JSTracer*, JSAtom*,
const char*);
template void js::TraceProcessGlobalRoot<JS::Symbol>(JSTracer*, JS::Symbol*,
const char*);
static Cell* TraceGenericPointerRootAndType(JSTracer* trc, Cell* thing,
JS::TraceKind kind,
const char* name) {
return MapGCThingTyped(thing, kind, [trc, name](auto t) -> Cell* {
TraceRoot(trc, &t, name);
return t;
});
}
void js::TraceGenericPointerRoot(JSTracer* trc, Cell** thingp,
const char* name) {
MOZ_ASSERT(thingp);
Cell* thing = *thingp;
if (!thing) {
return;
}
Cell* traced =
TraceGenericPointerRootAndType(trc, thing, thing->getTraceKind(), name);
if (traced != thing) {
*thingp = traced;
}
}
void js::TraceManuallyBarrieredGenericPointerEdge(JSTracer* trc, Cell** thingp,
const char* name) {
MOZ_ASSERT(thingp);
Cell* thing = *thingp;
if (!*thingp) {
return;
}
auto traced = MapGCThingTyped(thing, thing->getTraceKind(),
[trc, name](auto t) -> Cell* {
TraceManuallyBarrieredEdge(trc, &t, name);
return t;
});
if (traced != thing) {
*thingp = traced;
}
}
void js::TraceGCCellPtrRoot(JSTracer* trc, JS::GCCellPtr* thingp,
const char* name) {
Cell* thing = thingp->asCell();
if (!thing) {
return;
}
Cell* traced =
TraceGenericPointerRootAndType(trc, thing, thingp->kind(), name);
if (!traced) {
*thingp = JS::GCCellPtr();
} else if (traced != thingp->asCell()) {
*thingp = JS::GCCellPtr(traced, thingp->kind());
}
}
// This method is responsible for dynamic dispatch to the real tracer
// implementation. Consider replacing this choke point with virtual dispatch:
// a sufficiently smart C++ compiler may be able to devirtualize some paths.
template <typename T>
bool js::gc::TraceEdgeInternal(JSTracer* trc, T* thingp, const char* name) {
#define IS_SAME_TYPE_OR(name, type, _, _1) std::is_same_v<type*, T> ||
static_assert(JS_FOR_EACH_TRACEKIND(IS_SAME_TYPE_OR)
std::is_same_v<T, JS::Value> ||
std::is_same_v<T, jsid> || std::is_same_v<T, TaggedProto>,
"Only the base cell layout types are allowed into "
"marking/tracing internals");
#undef IS_SAME_TYPE_OR
if (trc->isMarkingTracer()) {
DoMarking(GCMarker::fromTracer(trc), *thingp);
return true;
}
if (trc->isTenuringTracer()) {
static_cast<TenuringTracer*>(trc)->traverse(thingp);
return true;
}
MOZ_ASSERT(trc->isCallbackTracer());
return DoCallback(trc->asCallbackTracer(), thingp, name);
}
template <typename T>
void js::gc::TraceRangeInternal(JSTracer* trc, size_t len, T* vec,
const char* name) {
JS::AutoTracingIndex index(trc);
for (auto i : IntegerRange(len)) {
if (InternalBarrierMethods<T>::isMarkable(vec[i])) {
TraceEdgeInternal(trc, &vec[i], name);
}
++index;
}
}
/*** GC Marking Interface ***************************************************/
namespace js {
using HasNoImplicitEdgesType = bool;
template <typename T>
struct ImplicitEdgeHolderType {
using Type = HasNoImplicitEdgesType;
};
// For now, we only handle JSObject* and BaseScript* keys, but the linear time
// algorithm can be easily extended by adding in more types here, then making
// GCMarker::traverse<T> call markImplicitEdges.
template <>
struct ImplicitEdgeHolderType<JSObject*> {
using Type = JSObject*;
};
template <>
struct ImplicitEdgeHolderType<BaseScript*> {
using Type = BaseScript*;
};
void GCMarker::markEphemeronValues(gc::Cell* markedCell,
WeakEntryVector& values) {
DebugOnly<size_t> initialLen = values.length();
for (const auto& markable : values) {
markable.weakmap->markKey(this, markedCell, markable.key);
}
// The vector should not be appended to during iteration because the key is
// already marked, and even in cases where we have a multipart key, we
// should only be inserting entries for the unmarked portions.
MOZ_ASSERT(values.length() == initialLen);
}
template <typename T>
void GCMarker::markImplicitEdgesHelper(T markedThing) {
if (!isWeakMarking()) {
return;
}
Zone* zone = markedThing->asTenured().zone();
MOZ_ASSERT(zone->isGCMarking());
MOZ_ASSERT(!zone->isGCSweeping());
auto p = zone->gcWeakKeys().get(markedThing);
if (!p) {
return;
}
WeakEntryVector& markables = p->value;
// markedThing might be a key in a debugger weakmap, which can end up marking
// values that are in a different compartment.
AutoClearTracingSource acts(this);
markEphemeronValues(markedThing, markables);
markables.clear(); // If key address is reused, it should do nothing
}
template <>
void GCMarker::markImplicitEdgesHelper(HasNoImplicitEdgesType) {}
template <typename T>
void GCMarker::markImplicitEdges(T* thing) {
markImplicitEdgesHelper<typename ImplicitEdgeHolderType<T*>::Type>(thing);
}
template void GCMarker::markImplicitEdges(JSObject*);
template void GCMarker::markImplicitEdges(BaseScript*);
} // namespace js
template <typename T>
static inline bool ShouldMark(GCMarker* gcmarker, T thing) {
// Don't trace things that are owned by another runtime.
if (IsOwnedByOtherRuntime(gcmarker->runtime(), thing)) {
return false;
}
// Don't mark things outside a zone if we are in a per-zone GC.
return thing->zone()->shouldMarkInZone();
}
template <>
bool ShouldMark<JSObject*>(GCMarker* gcmarker, JSObject* obj) {
// Don't trace things that are owned by another runtime.
if (IsOwnedByOtherRuntime(gcmarker->runtime(), obj)) {
return false;
}
// We may mark a Nursery thing outside the context of the
// MinorCollectionTracer because of a pre-barrier. The pre-barrier is not
// needed in this case because we perform a minor collection before each
// incremental slice.
if (IsInsideNursery(obj)) {
return false;
}
// Don't mark things outside a zone if we are in a per-zone GC. It is
// faster to check our own arena, which we can do since we know that
// the object is tenured.
return obj->asTenured().zone()->shouldMarkInZone();
}
// JSStrings can also be in the nursery. See ShouldMark<JSObject*> for comments.
template <>
bool ShouldMark<JSString*>(GCMarker* gcmarker, JSString* str) {
if (IsOwnedByOtherRuntime(gcmarker->runtime(), str)) {
return false;
}
if (IsInsideNursery(str)) {
return false;
}
return str->asTenured().zone()->shouldMarkInZone();
}
// BigInts can also be in the nursery. See ShouldMark<JSObject*> for comments.
template <>
bool ShouldMark<JS::BigInt*>(GCMarker* gcmarker, JS::BigInt* bi) {
if (IsOwnedByOtherRuntime(gcmarker->runtime(), bi)) {
return false;
}
if (IsInsideNursery(bi)) {
return false;
}
return bi->asTenured().zone()->shouldMarkInZone();
}
template <typename T>
void DoMarking(GCMarker* gcmarker, T* thing) {
// Do per-type marking precondition checks.
if (!ShouldMark(gcmarker, thing)) {
return;
}
CheckTracedThing(gcmarker, thing);
AutoClearTracingSource acts(gcmarker);
gcmarker->traverse(thing);
// Mark the compartment as live.
SetMaybeAliveFlag(thing);
}
template <typename T>
void DoMarking(GCMarker* gcmarker, const T& thing) {
ApplyGCThingTyped(thing, [gcmarker](auto t) { DoMarking(gcmarker, t); });
}
JS_PUBLIC_API void js::gc::PerformIncrementalReadBarrier(JS::GCCellPtr thing) {
// Optimized marking for read barriers. This is called from
// ExposeGCThingToActiveJS which has already checked the prerequisites for
// performing a read barrier. This means we can skip a bunch of checks and
// call info the tracer directly.
MOZ_ASSERT(thing);
MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting());
TenuredCell* cell = &thing.asCell()->asTenured();
Zone* zone = cell->zone();
MOZ_ASSERT(zone->needsIncrementalBarrier());
// Skip disptaching on known tracer type.
GCMarker* gcmarker = GCMarker::fromTracer(zone->barrierTracer());
// Mark the argument, as DoMarking above.
ApplyGCThingTyped(thing, [gcmarker](auto thing) {
MOZ_ASSERT(ShouldMark(gcmarker, thing));
CheckTracedThing(gcmarker, thing);
AutoClearTracingSource acts(gcmarker);
gcmarker->traverse(thing);
});
}
// The simplest traversal calls out to the fully generic traceChildren function
// to visit the child edges. In the absence of other traversal mechanisms, this
// function will rapidly grow the stack past its bounds and crash the process.
// Thus, this generic tracing should only be used in cases where subsequent
// tracing will not recurse.
template <typename T>
void js::GCMarker::markAndTraceChildren(T* thing) {
if (ThingIsPermanentAtomOrWellKnownSymbol(thing)) {
return;
}
if (mark(thing)) {
AutoSetTracingSource asts(this, thing);
thing->traceChildren(this);
}
}
namespace js {
template <>
void GCMarker::traverse(BaseShape* thing) {
markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(JS::Symbol* thing) {
markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(JS::BigInt* thing) {
markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(RegExpShared* thing) {
markAndTraceChildren(thing);
}
} // namespace js
// Strings, Shapes, and Scopes are extremely common, but have simple patterns of
// recursion. We traverse trees of these edges immediately, with aggressive,
// manual inlining, implemented by eagerlyTraceChildren.
template <typename T>
void js::GCMarker::markAndScan(T* thing) {
if (ThingIsPermanentAtomOrWellKnownSymbol(thing)) {
return;
}
if (mark(thing)) {
eagerlyMarkChildren(thing);
}
}
namespace js {
template <>
void GCMarker::traverse(JSString* thing) {
markAndScan(thing);
}
template <>
void GCMarker::traverse(Shape* thing) {
markAndScan(thing);
}
template <>
void GCMarker::traverse(js::Scope* thing) {
markAndScan(thing);
}
} // namespace js
// Object and ObjectGroup are extremely common and can contain arbitrarily
// nested graphs, so are not trivially inlined. In this case we use a mark
// stack to control recursion. JitCode shares none of these properties, but is
// included for historical reasons. JSScript normally cannot recurse, but may
// be used as a weakmap key and thereby recurse into weakmapped values.
template <typename T>
void js::GCMarker::markAndPush(T* thing) {
if (!mark(thing)) {
return;
}
pushTaggedPtr(thing);
}
namespace js {
template <>
void GCMarker::traverse(JSObject* thing) {
markAndPush(thing);
}
template <>
void GCMarker::traverse(ObjectGroup* thing) {
markAndPush(thing);
}
template <>
void GCMarker::traverse(jit::JitCode* thing) {
markAndPush(thing);
}
template <>
void GCMarker::traverse(BaseScript* thing) {
markAndPush(thing);
}
} // namespace js
namespace js {
template <>
void GCMarker::traverse(AccessorShape* thing) {