-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsCycleCollector.cpp
3965 lines (3334 loc) · 122 KB
/
nsCycleCollector.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/. */
//
// This file implements a garbage-cycle collector based on the paper
//
// Concurrent Cycle Collection in Reference Counted Systems
// Bacon & Rajan (2001), ECOOP 2001 / Springer LNCS vol 2072
//
// We are not using the concurrent or acyclic cases of that paper; so
// the green, red and orange colors are not used.
//
// The collector is based on tracking pointers of four colors:
//
// Black nodes are definitely live. If we ever determine a node is
// black, it's ok to forget about, drop from our records.
//
// White nodes are definitely garbage cycles. Once we finish with our
// scanning, we unlink all the white nodes and expect that by
// unlinking them they will self-destruct (since a garbage cycle is
// only keeping itself alive with internal links, by definition).
//
// Snow-white is an addition to the original algorithm. A snow-white node
// has reference count zero and is just waiting for deletion.
//
// Grey nodes are being scanned. Nodes that turn grey will turn
// either black if we determine that they're live, or white if we
// determine that they're a garbage cycle. After the main collection
// algorithm there should be no grey nodes.
//
// Purple nodes are *candidates* for being scanned. They are nodes we
// haven't begun scanning yet because they're not old enough, or we're
// still partway through the algorithm.
//
// XPCOM objects participating in garbage-cycle collection are obliged
// to inform us when they ought to turn purple; that is, when their
// refcount transitions from N+1 -> N, for nonzero N. Furthermore we
// require that *after* an XPCOM object has informed us of turning
// purple, they will tell us when they either transition back to being
// black (incremented refcount) or are ultimately deleted.
// Incremental cycle collection
//
// Beyond the simple state machine required to implement incremental
// collection, the CC needs to be able to compensate for things the browser
// is doing during the collection. There are two kinds of problems. For each
// of these, there are two cases to deal with: purple-buffered C++ objects
// and JS objects.
// The first problem is that an object in the CC's graph can become garbage.
// This is bad because the CC touches the objects in its graph at every
// stage of its operation.
//
// All cycle collected C++ objects that die during a cycle collection
// will end up actually getting deleted by the SnowWhiteKiller. Before
// the SWK deletes an object, it checks if an ICC is running, and if so,
// if the object is in the graph. If it is, the CC clears mPointer and
// mParticipant so it does not point to the raw object any more. Because
// objects could die any time the CC returns to the mutator, any time the CC
// accesses a PtrInfo it must perform a null check on mParticipant to
// ensure the object has not gone away.
//
// JS objects don't always run finalizers, so the CC can't remove them from
// the graph when they die. Fortunately, JS objects can only die during a GC,
// so if a GC is begun during an ICC, the browser synchronously finishes off
// the ICC, which clears the entire CC graph. If the GC and CC are scheduled
// properly, this should be rare.
//
// The second problem is that objects in the graph can be changed, say by
// being addrefed or released, or by having a field updated, after the object
// has been added to the graph. The problem is that ICC can miss a newly
// created reference to an object, and end up unlinking an object that is
// actually alive.
//
// The basic idea of the solution, from "An on-the-fly Reference Counting
// Garbage Collector for Java" by Levanoni and Petrank, is to notice if an
// object has had an additional reference to it created during the collection,
// and if so, don't collect it during the current collection. This avoids having
// to rerun the scan as in Bacon & Rajan 2001.
//
// For cycle collected C++ objects, we modify AddRef to place the object in
// the purple buffer, in addition to Release. Then, in the CC, we treat any
// objects in the purple buffer as being alive, after graph building has
// completed. Because they are in the purple buffer, they will be suspected
// in the next CC, so there's no danger of leaks. This is imprecise, because
// we will treat as live an object that has been Released but not AddRefed
// during graph building, but that's probably rare enough that the additional
// bookkeeping overhead is not worthwhile.
//
// For JS objects, the cycle collector is only looking at gray objects. If a
// gray object is touched during ICC, it will be made black by UnmarkGray.
// Thus, if a JS object has become black during the ICC, we treat it as live.
// Merged JS zones have to be handled specially: we scan all zone globals.
// If any are black, we treat the zone as being black.
// Safety
//
// An XPCOM object is either scan-safe or scan-unsafe, purple-safe or
// purple-unsafe.
//
// An nsISupports object is scan-safe if:
//
// - It can be QI'ed to |nsXPCOMCycleCollectionParticipant|, though
// this operation loses ISupports identity (like nsIClassInfo).
// - Additionally, the operation |traverse| on the resulting
// nsXPCOMCycleCollectionParticipant does not cause *any* refcount
// adjustment to occur (no AddRef / Release calls).
//
// A non-nsISupports ("native") object is scan-safe by explicitly
// providing its nsCycleCollectionParticipant.
//
// An object is purple-safe if it satisfies the following properties:
//
// - The object is scan-safe.
//
// When we receive a pointer |ptr| via
// |nsCycleCollector::suspect(ptr)|, we assume it is purple-safe. We
// can check the scan-safety, but have no way to ensure the
// purple-safety; objects must obey, or else the entire system falls
// apart. Don't involve an object in this scheme if you can't
// guarantee its purple-safety. The easiest way to ensure that an
// object is purple-safe is to use nsCycleCollectingAutoRefCnt.
//
// When we have a scannable set of purple nodes ready, we begin
// our walks. During the walks, the nodes we |traverse| should only
// feed us more scan-safe nodes, and should not adjust the refcounts
// of those nodes.
//
// We do not |AddRef| or |Release| any objects during scanning. We
// rely on the purple-safety of the roots that call |suspect| to
// hold, such that we will clear the pointer from the purple buffer
// entry to the object before it is destroyed. The pointers that are
// merely scan-safe we hold only for the duration of scanning, and
// there should be no objects released from the scan-safe set during
// the scan.
//
// We *do* call |Root| and |Unroot| on every white object, on
// either side of the calls to |Unlink|. This keeps the set of white
// objects alive during the unlinking.
//
#if !defined(__MINGW32__)
# ifdef WIN32
# include <crtdbg.h>
# include <errno.h>
# endif
#endif
#include "base/process_util.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/CycleCollectedJSRuntime.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/HashTable.h"
#include "mozilla/HoldDropJSObjects.h"
/* This must occur *after* base/process_util.h to avoid typedefs conflicts. */
#include <stdint.h>
#include <stdio.h>
#include <utility>
#include "GeckoProfiler.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoGlobalTimelineMarker.h"
#include "mozilla/Likely.h"
#include "mozilla/LinkedList.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/MruCache.h"
#include "mozilla/PoisonIOInterposer.h"
#include "mozilla/SegmentedVector.h"
#include "mozilla/Telemetry.h"
#include "mozilla/ThreadLocal.h"
#include "mozilla/UniquePtr.h"
#include "nsCycleCollectionNoteRootCallback.h"
#include "nsCycleCollectionParticipant.h"
#include "nsCycleCollector.h"
#include "nsDeque.h"
#include "nsDumpUtils.h"
#include "nsExceptionHandler.h"
#include "nsIConsoleService.h"
#include "nsICycleCollectorListener.h"
#include "nsIFile.h"
#include "nsIMemoryReporter.h"
#include "nsISerialEventTarget.h"
#include "nsPrintfCString.h"
#include "nsTArray.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"
#include "prenv.h"
#include "xpcpublic.h"
using namespace mozilla;
struct NurseryPurpleBufferEntry {
void* mPtr;
nsCycleCollectionParticipant* mParticipant;
nsCycleCollectingAutoRefCnt* mRefCnt;
};
#define NURSERY_PURPLE_BUFFER_SIZE 2048
bool gNurseryPurpleBufferEnabled = true;
NurseryPurpleBufferEntry gNurseryPurpleBufferEntry[NURSERY_PURPLE_BUFFER_SIZE];
uint32_t gNurseryPurpleBufferEntryCount = 0;
void ClearNurseryPurpleBuffer();
static void SuspectUsingNurseryPurpleBuffer(
void* aPtr, nsCycleCollectionParticipant* aCp,
nsCycleCollectingAutoRefCnt* aRefCnt) {
MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
MOZ_ASSERT(gNurseryPurpleBufferEnabled);
if (gNurseryPurpleBufferEntryCount == NURSERY_PURPLE_BUFFER_SIZE) {
ClearNurseryPurpleBuffer();
}
gNurseryPurpleBufferEntry[gNurseryPurpleBufferEntryCount] = {aPtr, aCp,
aRefCnt};
++gNurseryPurpleBufferEntryCount;
}
//#define COLLECT_TIME_DEBUG
// Enable assertions that are useful for diagnosing errors in graph
// construction.
//#define DEBUG_CC_GRAPH
#define DEFAULT_SHUTDOWN_COLLECTIONS 5
// One to do the freeing, then another to detect there is no more work to do.
#define NORMAL_SHUTDOWN_COLLECTIONS 2
// Cycle collector environment variables
//
// MOZ_CC_LOG_ALL: If defined, always log cycle collector heaps.
//
// MOZ_CC_LOG_SHUTDOWN: If defined, log cycle collector heaps at shutdown.
//
// MOZ_CC_LOG_THREAD: If set to "main", only automatically log main thread
// CCs. If set to "worker", only automatically log worker CCs. If set to "all",
// log either. The default value is "all". This must be used with either
// MOZ_CC_LOG_ALL or MOZ_CC_LOG_SHUTDOWN for it to do anything.
//
// MOZ_CC_LOG_PROCESS: If set to "main", only automatically log main process
// CCs. If set to "content", only automatically log tab CCs. If set to
// "plugins", only automatically log plugin CCs. If set to "all", log
// everything. The default value is "all". This must be used with either
// MOZ_CC_LOG_ALL or MOZ_CC_LOG_SHUTDOWN for it to do anything.
//
// MOZ_CC_ALL_TRACES: If set to "all", any cycle collector
// logging done will be WantAllTraces, which disables
// various cycle collector optimizations to give a fuller picture of
// the heap. If set to "shutdown", only shutdown logging will be WantAllTraces.
// The default is none.
//
// MOZ_CC_RUN_DURING_SHUTDOWN: In non-DEBUG or builds, if this is set,
// run cycle collections at shutdown.
//
// MOZ_CC_LOG_DIRECTORY: The directory in which logs are placed (such as
// logs from MOZ_CC_LOG_ALL and MOZ_CC_LOG_SHUTDOWN, or other uses
// of nsICycleCollectorListener)
// Various parameters of this collector can be tuned using environment
// variables.
struct nsCycleCollectorParams {
bool mLogAll;
bool mLogShutdown;
bool mAllTracesAll;
bool mAllTracesShutdown;
bool mLogThisThread;
nsCycleCollectorParams()
: mLogAll(PR_GetEnv("MOZ_CC_LOG_ALL") != nullptr),
mLogShutdown(PR_GetEnv("MOZ_CC_LOG_SHUTDOWN") != nullptr),
mAllTracesAll(false),
mAllTracesShutdown(false) {
const char* logThreadEnv = PR_GetEnv("MOZ_CC_LOG_THREAD");
bool threadLogging = true;
if (logThreadEnv && !!strcmp(logThreadEnv, "all")) {
if (NS_IsMainThread()) {
threadLogging = !strcmp(logThreadEnv, "main");
} else {
threadLogging = !strcmp(logThreadEnv, "worker");
}
}
const char* logProcessEnv = PR_GetEnv("MOZ_CC_LOG_PROCESS");
bool processLogging = true;
if (logProcessEnv && !!strcmp(logProcessEnv, "all")) {
switch (XRE_GetProcessType()) {
case GeckoProcessType_Default:
processLogging = !strcmp(logProcessEnv, "main");
break;
case GeckoProcessType_Plugin:
processLogging = !strcmp(logProcessEnv, "plugins");
break;
case GeckoProcessType_Content:
processLogging = !strcmp(logProcessEnv, "content");
break;
default:
processLogging = false;
break;
}
}
mLogThisThread = threadLogging && processLogging;
const char* allTracesEnv = PR_GetEnv("MOZ_CC_ALL_TRACES");
if (allTracesEnv) {
if (!strcmp(allTracesEnv, "all")) {
mAllTracesAll = true;
} else if (!strcmp(allTracesEnv, "shutdown")) {
mAllTracesShutdown = true;
}
}
}
bool LogThisCC(bool aIsShutdown) {
return (mLogAll || (aIsShutdown && mLogShutdown)) && mLogThisThread;
}
bool AllTracesThisCC(bool aIsShutdown) {
return mAllTracesAll || (aIsShutdown && mAllTracesShutdown);
}
};
#ifdef COLLECT_TIME_DEBUG
class TimeLog {
public:
TimeLog() : mLastCheckpoint(TimeStamp::Now()) {}
void Checkpoint(const char* aEvent) {
TimeStamp now = TimeStamp::Now();
double dur = (now - mLastCheckpoint).ToMilliseconds();
if (dur >= 0.5) {
printf("cc: %s took %.1fms\n", aEvent, dur);
}
mLastCheckpoint = now;
}
private:
TimeStamp mLastCheckpoint;
};
#else
class TimeLog {
public:
TimeLog() = default;
void Checkpoint(const char* aEvent) {}
};
#endif
////////////////////////////////////////////////////////////////////////
// Base types
////////////////////////////////////////////////////////////////////////
class PtrInfo;
class EdgePool {
public:
// EdgePool allocates arrays of void*, primarily to hold PtrInfo*.
// However, at the end of a block, the last two pointers are a null
// and then a void** pointing to the next block. This allows
// EdgePool::Iterators to be a single word but still capable of crossing
// block boundaries.
EdgePool() {
mSentinelAndBlocks[0].block = nullptr;
mSentinelAndBlocks[1].block = nullptr;
}
~EdgePool() {
MOZ_ASSERT(!mSentinelAndBlocks[0].block && !mSentinelAndBlocks[1].block,
"Didn't call Clear()?");
}
void Clear() {
EdgeBlock* b = EdgeBlocks();
while (b) {
EdgeBlock* next = b->Next();
delete b;
b = next;
}
mSentinelAndBlocks[0].block = nullptr;
mSentinelAndBlocks[1].block = nullptr;
}
#ifdef DEBUG
bool IsEmpty() {
return !mSentinelAndBlocks[0].block && !mSentinelAndBlocks[1].block;
}
#endif
private:
struct EdgeBlock;
union PtrInfoOrBlock {
// Use a union to avoid reinterpret_cast and the ensuing
// potential aliasing bugs.
PtrInfo* ptrInfo;
EdgeBlock* block;
};
struct EdgeBlock {
enum { EdgeBlockSize = 16 * 1024 };
PtrInfoOrBlock mPointers[EdgeBlockSize];
EdgeBlock() {
mPointers[EdgeBlockSize - 2].block = nullptr; // sentinel
mPointers[EdgeBlockSize - 1].block = nullptr; // next block pointer
}
EdgeBlock*& Next() { return mPointers[EdgeBlockSize - 1].block; }
PtrInfoOrBlock* Start() { return &mPointers[0]; }
PtrInfoOrBlock* End() { return &mPointers[EdgeBlockSize - 2]; }
};
// Store the null sentinel so that we can have valid iterators
// before adding any edges and without adding any blocks.
PtrInfoOrBlock mSentinelAndBlocks[2];
EdgeBlock*& EdgeBlocks() { return mSentinelAndBlocks[1].block; }
EdgeBlock* EdgeBlocks() const { return mSentinelAndBlocks[1].block; }
public:
class Iterator {
public:
Iterator() : mPointer(nullptr) {}
explicit Iterator(PtrInfoOrBlock* aPointer) : mPointer(aPointer) {}
Iterator(const Iterator& aOther) = default;
Iterator& operator++() {
if (!mPointer->ptrInfo) {
// Null pointer is a sentinel for link to the next block.
mPointer = (mPointer + 1)->block->mPointers;
}
++mPointer;
return *this;
}
PtrInfo* operator*() const {
if (!mPointer->ptrInfo) {
// Null pointer is a sentinel for link to the next block.
return (mPointer + 1)->block->mPointers->ptrInfo;
}
return mPointer->ptrInfo;
}
bool operator==(const Iterator& aOther) const {
return mPointer == aOther.mPointer;
}
bool operator!=(const Iterator& aOther) const {
return mPointer != aOther.mPointer;
}
#ifdef DEBUG_CC_GRAPH
bool Initialized() const { return mPointer != nullptr; }
#endif
private:
PtrInfoOrBlock* mPointer;
};
class Builder;
friend class Builder;
class Builder {
public:
explicit Builder(EdgePool& aPool)
: mCurrent(&aPool.mSentinelAndBlocks[0]),
mBlockEnd(&aPool.mSentinelAndBlocks[0]),
mNextBlockPtr(&aPool.EdgeBlocks()) {}
Iterator Mark() { return Iterator(mCurrent); }
void Add(PtrInfo* aEdge) {
if (mCurrent == mBlockEnd) {
EdgeBlock* b = new EdgeBlock();
*mNextBlockPtr = b;
mCurrent = b->Start();
mBlockEnd = b->End();
mNextBlockPtr = &b->Next();
}
(mCurrent++)->ptrInfo = aEdge;
}
private:
// mBlockEnd points to space for null sentinel
PtrInfoOrBlock* mCurrent;
PtrInfoOrBlock* mBlockEnd;
EdgeBlock** mNextBlockPtr;
};
size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
size_t n = 0;
EdgeBlock* b = EdgeBlocks();
while (b) {
n += aMallocSizeOf(b);
b = b->Next();
}
return n;
}
};
#ifdef DEBUG_CC_GRAPH
# define CC_GRAPH_ASSERT(b) MOZ_ASSERT(b)
#else
# define CC_GRAPH_ASSERT(b)
#endif
#define CC_TELEMETRY(_name, _value) \
do { \
if (NS_IsMainThread()) { \
Telemetry::Accumulate(Telemetry::CYCLE_COLLECTOR##_name, _value); \
} else { \
Telemetry::Accumulate(Telemetry::CYCLE_COLLECTOR_WORKER##_name, _value); \
} \
} while (0)
enum NodeColor { black, white, grey };
// This structure should be kept as small as possible; we may expect
// hundreds of thousands of them to be allocated and touched
// repeatedly during each cycle collection.
class PtrInfo final {
public:
// mParticipant knows a more concrete type.
void* mPointer;
nsCycleCollectionParticipant* mParticipant;
uint32_t mColor : 2;
uint32_t mInternalRefs : 30;
uint32_t mRefCount;
private:
EdgePool::Iterator mFirstChild;
static const uint32_t kInitialRefCount = UINT32_MAX - 1;
public:
PtrInfo(void* aPointer, nsCycleCollectionParticipant* aParticipant)
: mPointer(aPointer),
mParticipant(aParticipant),
mColor(grey),
mInternalRefs(0),
mRefCount(kInitialRefCount),
mFirstChild() {
MOZ_ASSERT(aParticipant);
// We initialize mRefCount to a large non-zero value so
// that it doesn't look like a JS object to the cycle collector
// in the case where the object dies before being traversed.
MOZ_ASSERT(!IsGrayJS() && !IsBlackJS());
}
// Allow NodePool::NodeBlock's constructor to compile.
PtrInfo()
: mPointer{nullptr},
mParticipant{nullptr},
mColor{0},
mInternalRefs{0},
mRefCount{0} {
MOZ_ASSERT_UNREACHABLE("should never be called");
}
bool IsGrayJS() const { return mRefCount == 0; }
bool IsBlackJS() const { return mRefCount == UINT32_MAX; }
bool WasTraversed() const { return mRefCount != kInitialRefCount; }
EdgePool::Iterator FirstChild() const {
CC_GRAPH_ASSERT(mFirstChild.Initialized());
return mFirstChild;
}
// this PtrInfo must be part of a NodePool
EdgePool::Iterator LastChild() const {
CC_GRAPH_ASSERT((this + 1)->mFirstChild.Initialized());
return (this + 1)->mFirstChild;
}
void SetFirstChild(EdgePool::Iterator aFirstChild) {
CC_GRAPH_ASSERT(aFirstChild.Initialized());
mFirstChild = aFirstChild;
}
// this PtrInfo must be part of a NodePool
void SetLastChild(EdgePool::Iterator aLastChild) {
CC_GRAPH_ASSERT(aLastChild.Initialized());
(this + 1)->mFirstChild = aLastChild;
}
void AnnotatedReleaseAssert(bool aCondition, const char* aMessage);
};
void PtrInfo::AnnotatedReleaseAssert(bool aCondition, const char* aMessage) {
if (aCondition) {
return;
}
const char* piName = "Unknown";
if (mParticipant) {
piName = mParticipant->ClassName();
}
nsPrintfCString msg("%s, for class %s", aMessage, piName);
CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::CycleCollector,
msg);
MOZ_CRASH();
}
/**
* A structure designed to be used like a linked list of PtrInfo, except
* it allocates many PtrInfos at a time.
*/
class NodePool {
private:
// The -2 allows us to use |NodeBlockSize + 1| for |mEntries|, and fit
// |mNext|, all without causing slop.
enum { NodeBlockSize = 4 * 1024 - 2 };
struct NodeBlock {
// We create and destroy NodeBlock using moz_xmalloc/free rather than new
// and delete to avoid calling its constructor and destructor.
NodeBlock() : mNext{nullptr} {
MOZ_ASSERT_UNREACHABLE("should never be called");
// Ensure NodeBlock is the right size (see the comment on NodeBlockSize
// above).
static_assert(
sizeof(NodeBlock) == 81904 || // 32-bit; equals 19.996 x 4 KiB pages
sizeof(NodeBlock) ==
131048, // 64-bit; equals 31.994 x 4 KiB pages
"ill-sized NodeBlock");
}
~NodeBlock() { MOZ_ASSERT_UNREACHABLE("should never be called"); }
NodeBlock* mNext;
PtrInfo mEntries[NodeBlockSize + 1]; // +1 to store last child of last node
};
public:
NodePool() : mBlocks(nullptr), mLast(nullptr) {}
~NodePool() { MOZ_ASSERT(!mBlocks, "Didn't call Clear()?"); }
void Clear() {
NodeBlock* b = mBlocks;
while (b) {
NodeBlock* n = b->mNext;
free(b);
b = n;
}
mBlocks = nullptr;
mLast = nullptr;
}
#ifdef DEBUG
bool IsEmpty() { return !mBlocks && !mLast; }
#endif
class Builder;
friend class Builder;
class Builder {
public:
explicit Builder(NodePool& aPool)
: mNextBlock(&aPool.mBlocks), mNext(aPool.mLast), mBlockEnd(nullptr) {
MOZ_ASSERT(!aPool.mBlocks && !aPool.mLast, "pool not empty");
}
PtrInfo* Add(void* aPointer, nsCycleCollectionParticipant* aParticipant) {
if (mNext == mBlockEnd) {
NodeBlock* block = static_cast<NodeBlock*>(malloc(sizeof(NodeBlock)));
if (!block) {
return nullptr;
}
*mNextBlock = block;
mNext = block->mEntries;
mBlockEnd = block->mEntries + NodeBlockSize;
block->mNext = nullptr;
mNextBlock = &block->mNext;
}
return new (mozilla::KnownNotNull, mNext++)
PtrInfo(aPointer, aParticipant);
}
private:
NodeBlock** mNextBlock;
PtrInfo*& mNext;
PtrInfo* mBlockEnd;
};
class Enumerator;
friend class Enumerator;
class Enumerator {
public:
explicit Enumerator(NodePool& aPool)
: mFirstBlock(aPool.mBlocks),
mCurBlock(nullptr),
mNext(nullptr),
mBlockEnd(nullptr),
mLast(aPool.mLast) {}
bool IsDone() const { return mNext == mLast; }
bool AtBlockEnd() const { return mNext == mBlockEnd; }
PtrInfo* GetNext() {
MOZ_ASSERT(!IsDone(), "calling GetNext when done");
if (mNext == mBlockEnd) {
NodeBlock* nextBlock = mCurBlock ? mCurBlock->mNext : mFirstBlock;
mNext = nextBlock->mEntries;
mBlockEnd = mNext + NodeBlockSize;
mCurBlock = nextBlock;
}
return mNext++;
}
private:
// mFirstBlock is a reference to allow an Enumerator to be constructed
// for an empty graph.
NodeBlock*& mFirstBlock;
NodeBlock* mCurBlock;
// mNext is the next value we want to return, unless mNext == mBlockEnd
// NB: mLast is a reference to allow enumerating while building!
PtrInfo* mNext;
PtrInfo* mBlockEnd;
PtrInfo*& mLast;
};
size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
// We don't measure the things pointed to by mEntries[] because those
// pointers are non-owning.
size_t n = 0;
NodeBlock* b = mBlocks;
while (b) {
n += aMallocSizeOf(b);
b = b->mNext;
}
return n;
}
private:
NodeBlock* mBlocks;
PtrInfo* mLast;
};
struct PtrToNodeHashPolicy {
using Key = PtrInfo*;
using Lookup = void*;
static js::HashNumber hash(const Lookup& aLookup) {
return mozilla::HashGeneric(aLookup);
}
static bool match(const Key& aKey, const Lookup& aLookup) {
return aKey->mPointer == aLookup;
}
};
struct WeakMapping {
// map and key will be null if the corresponding objects are GC marked
PtrInfo* mMap;
PtrInfo* mKey;
PtrInfo* mKeyDelegate;
PtrInfo* mVal;
};
class CCGraphBuilder;
struct CCGraph {
NodePool mNodes;
EdgePool mEdges;
nsTArray<WeakMapping> mWeakMaps;
uint32_t mRootCount;
private:
friend CCGraphBuilder;
mozilla::HashSet<PtrInfo*, PtrToNodeHashPolicy> mPtrInfoMap;
bool mOutOfMemory;
static const uint32_t kInitialMapLength = 16384;
public:
CCGraph()
: mRootCount(0), mPtrInfoMap(kInitialMapLength), mOutOfMemory(false) {}
~CCGraph() = default;
void Init() { MOZ_ASSERT(IsEmpty(), "Failed to call CCGraph::Clear"); }
void Clear() {
mNodes.Clear();
mEdges.Clear();
mWeakMaps.Clear();
mRootCount = 0;
mPtrInfoMap.clearAndCompact();
mOutOfMemory = false;
}
#ifdef DEBUG
bool IsEmpty() {
return mNodes.IsEmpty() && mEdges.IsEmpty() && mWeakMaps.IsEmpty() &&
mRootCount == 0 && mPtrInfoMap.empty();
}
#endif
PtrInfo* FindNode(void* aPtr);
void RemoveObjectFromMap(void* aObject);
uint32_t MapCount() const { return mPtrInfoMap.count(); }
size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
size_t n = 0;
n += mNodes.SizeOfExcludingThis(aMallocSizeOf);
n += mEdges.SizeOfExcludingThis(aMallocSizeOf);
// We don't measure what the WeakMappings point to, because the
// pointers are non-owning.
n += mWeakMaps.ShallowSizeOfExcludingThis(aMallocSizeOf);
n += mPtrInfoMap.shallowSizeOfExcludingThis(aMallocSizeOf);
return n;
}
};
PtrInfo* CCGraph::FindNode(void* aPtr) {
auto p = mPtrInfoMap.lookup(aPtr);
return p ? *p : nullptr;
}
void CCGraph::RemoveObjectFromMap(void* aObj) {
auto p = mPtrInfoMap.lookup(aObj);
if (p) {
PtrInfo* pinfo = *p;
pinfo->mPointer = nullptr;
pinfo->mParticipant = nullptr;
mPtrInfoMap.remove(p);
}
}
static nsISupports* CanonicalizeXPCOMParticipant(nsISupports* aIn) {
nsISupports* out = nullptr;
aIn->QueryInterface(NS_GET_IID(nsCycleCollectionISupports),
reinterpret_cast<void**>(&out));
return out;
}
struct nsPurpleBufferEntry {
nsPurpleBufferEntry(void* aObject, nsCycleCollectingAutoRefCnt* aRefCnt,
nsCycleCollectionParticipant* aParticipant)
: mObject(aObject), mRefCnt(aRefCnt), mParticipant(aParticipant) {}
nsPurpleBufferEntry(nsPurpleBufferEntry&& aOther)
: mObject(nullptr), mRefCnt(nullptr), mParticipant(nullptr) {
Swap(aOther);
}
void Swap(nsPurpleBufferEntry& aOther) {
std::swap(mObject, aOther.mObject);
std::swap(mRefCnt, aOther.mRefCnt);
std::swap(mParticipant, aOther.mParticipant);
}
void Clear() {
mRefCnt->RemoveFromPurpleBuffer();
mRefCnt = nullptr;
mObject = nullptr;
mParticipant = nullptr;
}
~nsPurpleBufferEntry() {
if (mRefCnt) {
mRefCnt->RemoveFromPurpleBuffer();
}
}
void* mObject;
nsCycleCollectingAutoRefCnt* mRefCnt;
nsCycleCollectionParticipant* mParticipant; // nullptr for nsISupports
};
class nsCycleCollector;
struct nsPurpleBuffer {
private:
uint32_t mCount;
// Try to match the size of a jemalloc bucket, to minimize slop bytes.
// - On 32-bit platforms sizeof(nsPurpleBufferEntry) is 12, so mEntries'
// Segment is 16,372 bytes.
// - On 64-bit platforms sizeof(nsPurpleBufferEntry) is 24, so mEntries'
// Segment is 32,760 bytes.
static const uint32_t kEntriesPerSegment = 1365;
static const size_t kSegmentSize =
sizeof(nsPurpleBufferEntry) * kEntriesPerSegment;
typedef SegmentedVector<nsPurpleBufferEntry, kSegmentSize,
InfallibleAllocPolicy>
PurpleBufferVector;
PurpleBufferVector mEntries;
public:
nsPurpleBuffer() : mCount(0) {
static_assert(
sizeof(PurpleBufferVector::Segment) == 16372 || // 32-bit
sizeof(PurpleBufferVector::Segment) == 32760 || // 64-bit
sizeof(PurpleBufferVector::Segment) == 32744, // 64-bit Windows
"ill-sized nsPurpleBuffer::mEntries");
}
~nsPurpleBuffer() = default;
// This method compacts mEntries.
template <class PurpleVisitor>
void VisitEntries(PurpleVisitor& aVisitor) {
Maybe<AutoRestore<bool>> ar;
if (NS_IsMainThread()) {
ar.emplace(gNurseryPurpleBufferEnabled);
gNurseryPurpleBufferEnabled = false;
ClearNurseryPurpleBuffer();
}
if (mEntries.IsEmpty()) {
return;
}
uint32_t oldLength = mEntries.Length();
uint32_t keptLength = 0;
auto revIter = mEntries.IterFromLast();
auto iter = mEntries.Iter();
// After iteration this points to the first empty entry.
auto firstEmptyIter = mEntries.Iter();
auto iterFromLastEntry = mEntries.IterFromLast();
for (; !iter.Done(); iter.Next()) {
nsPurpleBufferEntry& e = iter.Get();
if (e.mObject) {
if (!aVisitor.Visit(*this, &e)) {
return;
}
}
// Visit call above may have cleared the entry, or the entry was empty
// already.
if (!e.mObject) {
// Try to find a non-empty entry from the end of the vector.
for (; !revIter.Done(); revIter.Prev()) {
nsPurpleBufferEntry& otherEntry = revIter.Get();
if (&e == &otherEntry) {
break;
}
if (otherEntry.mObject) {
if (!aVisitor.Visit(*this, &otherEntry)) {
return;
}
// Visit may have cleared otherEntry.
if (otherEntry.mObject) {
e.Swap(otherEntry);
revIter.Prev(); // We've swapped this now empty entry.
break;
}
}
}
}
// Entry is non-empty even after the Visit call, ensure it is kept
// in mEntries.
if (e.mObject) {
firstEmptyIter.Next();
++keptLength;
}
if (&e == &revIter.Get()) {
break;
}
}
// There were some empty entries.
if (oldLength != keptLength) {
// While visiting entries, some new ones were possibly added. This can
// happen during CanSkip. Move all such new entries to be after other
// entries. Note, we don't call Visit on newly added entries!
if (&iterFromLastEntry.Get() != &mEntries.GetLast()) {
iterFromLastEntry.Next(); // Now pointing to the first added entry.
auto& iterForNewEntries = iterFromLastEntry;
while (!iterForNewEntries.Done()) {
MOZ_ASSERT(!firstEmptyIter.Done());
MOZ_ASSERT(!firstEmptyIter.Get().mObject);
firstEmptyIter.Get().Swap(iterForNewEntries.Get());
firstEmptyIter.Next();
iterForNewEntries.Next();
}
}
mEntries.PopLastN(oldLength - keptLength);
}