This repository has been archived by the owner on Jan 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
GC.cpp
4352 lines (3801 loc) · 158 KB
/
GC.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++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* 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 "MMgc.h"
#include "StaticAssert.h"
#include "avmplus.h"
#include "ITelemetry.h"
namespace MMgc
{
#ifdef MMGC_MEMORY_PROFILER
// get detailed info on each size class allocators
const bool dumpSizeClassState = false;
#endif
/*virtual*/
void GCCallback::presweep() {}
/*virtual*/
void GCCallback::postsweep() {}
/*virtual*/
void GCCallback::prereap() {}
/*virtual*/
void GCCallback::postreap() {}
/*virtual*/
void GCCallback::prereap(void* /*rcobj*/) {}
////////////// GC //////////////////////////////////////////////////////////
// Size classes for our GC. From 8 to 128, size classes are spaced
// evenly 8 bytes apart. The finest granularity we can achieve is
// 8 bytes, as pointers must be 8-byte aligned thanks to our use
// of the bottom 3 bits of 32-bit atoms for Special Purposes.
// Above that, the size classes have been chosen to maximize the
// number of items that fit in a 4096-byte block, given our block
// header information.
const int16_t GC::kSizeClasses[kNumSizeClasses] = {
8, 16, 24, 32, 40, 48, 56, 64, 72, 80, //0-9
88, 96, 104, 112, 120, 128, 144, 160, 168, 176, //10-19
184, 192, 200, 216, 224, 240, 256, 280, 296, 328, //20-29
352, 392, 432, 488, 560, 656, 784, 984, 1312, 1968 //30-39
};
/* kSizeClassIndex[] generated with this code:
kSizeClassIndex[0] = 0;
for (var i:int = 1; i < kNumSizeClasses; i++)
for (var j:int = (kSizeClasses[i-1]>>3), n=(kSizeClasses[i]>>3); j < n; j++)
kSizeClassIndex[j] = i;
*/
// index'd by size>>3 - 1
const uint8_t GC::kSizeClassIndex[246] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 17, 17,
18, 19, 20, 21, 22, 23, 23, 24, 25, 25,
26, 26, 27, 27, 27, 28, 28, 29, 29, 29,
29, 30, 30, 30, 31, 31, 31, 31, 31, 32,
32, 32, 32, 32, 33, 33, 33, 33, 33, 33,
33, 34, 34, 34, 34, 34, 34, 34, 34, 34,
35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 37, 37,
37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39
};
const static int gcPartitionMap[] = GC_SLICE_TO_PARTITION_MAP;
const static int kGCPartitionMapSize = sizeof(gcPartitionMap) / sizeof(int);
static inline int SmallGCAllocHeapPartition(int index) { GCAssert(kGCPartitionMapSize == kNumGCPartitions); GCAssert(index < kNumGCPartitions); return gcPartitionMap[index]; }
static inline int LargeGCAllocHeapPartition(int index) { GCAssert(kGCPartitionMapSize == kNumGCPartitions); GCAssert(index < kNumGCPartitions); return gcPartitionMap[index]; }
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4355) // 'this': used in base member initializer list
#endif
GC::GC(GCHeap *gcheap, GCConfig& config)
:
greedy(config.mode == GCConfig::kGreedyGC),
nogc(config.mode == GCConfig::kDisableGC),
incremental(config.mode == GCConfig::kIncrementalGC),
drcEnabled(config.mode != GCConfig::kDisableGC && config.drc),
findUnmarkedPointers(false),
#ifdef GCDEBUG
validateDefRef(config.validateDRC),
keepDRCHistory(config.validateDRC),
#endif
dontAddToZCTDuringCollection(false),
incrementalValidation(config.incrementalValidation),
#ifdef GCDEBUG
// check for missing write barriers at every Alloc
incrementalValidationPedantic(false),
#endif
rcRootSegments(NULL),
policy(this, gcheap, config),
t0(VMPI_getPerformanceCounter()),
lastStartMarkIncrementCount(0),
sweeps(0),
sweepStart(0),
emptyWeakRef(0),
#ifdef VMCFG_TELEMETRY
m_telemetry(NULL),
#endif
m_gcThread(0),
m_stackBaseSaved(0),
destroying(false),
marking(false),
collecting(false),
performingDRCValidationTrace(false),
presweeping(false),
markerActive(0),
stackCleaned(true),
rememberedStackTop(0),
stackEnter(0),
enterCount(0),
#ifdef VMCFG_SELECTABLE_EXACT_TRACING
runtimeSelectableExactnessFlag(config.exactTracing ? kVirtualGCTrace : 0),
#endif
#ifdef MMGC_MARKSTACK_ALLOWANCE
m_incrementalWork(config.markstackAllowance),
m_barrierWork(config.markstackAllowance),
#endif
m_markStackOverflow(false),
mark_item_recursion_control(20), // About 3KB as measured with GCC 4.1 on MacOS X (144 bytes / frame), May 2009
sizeClassIndex(kSizeClassIndex), // see comment in GC.h
pageMap(),
heap(gcheap),
finalizedValue(true),
smallEmptyPageList(NULL),
largeEmptyPageList(NULL),
remainingQuickListBudget(0),
victimIterator(0),
m_roots(0),
m_callbacks(0),
zct(),
lockedObjects(NULL)
#ifdef MMGC_CONSERVATIVE_PROFILER
, demos(0)
#endif
#ifdef MMGC_WEAKREF_PROFILER
, weaklings(0)
#endif
#ifdef MMGC_DELETION_PROFILER
, deletos(0)
#endif
#ifdef DEBUGGER
, m_sampler(NULL)
#endif
{
// sanity check for all our types
MMGC_STATIC_ASSERT(sizeof(int8_t) == 1);
MMGC_STATIC_ASSERT(sizeof(uint8_t) == 1);
MMGC_STATIC_ASSERT(sizeof(int16_t) == 2);
MMGC_STATIC_ASSERT(sizeof(uint16_t) == 2);
MMGC_STATIC_ASSERT(sizeof(int32_t) == 4);
MMGC_STATIC_ASSERT(sizeof(uint32_t) == 4);
MMGC_STATIC_ASSERT(sizeof(int64_t) == 8);
MMGC_STATIC_ASSERT(sizeof(uint64_t) == 8);
MMGC_STATIC_ASSERT(sizeof(intptr_t) == sizeof(void *));
MMGC_STATIC_ASSERT(sizeof(uintptr_t) == sizeof(void *));
#ifdef MMGC_64BIT
MMGC_STATIC_ASSERT(sizeof(intptr_t) == 8);
MMGC_STATIC_ASSERT(sizeof(uintptr_t) == 8);
#else
MMGC_STATIC_ASSERT(sizeof(intptr_t) == 4);
MMGC_STATIC_ASSERT(sizeof(uintptr_t) == 4);
#endif
MMGC_STATIC_ASSERT(sizeof(GCLargeAlloc::LargeBlock) % 8 == 0);
MMGC_STATIC_ASSERT(sizeof(gcbits_t) == 1);
// Policy code relies on INT_MAX being 32 bit int max.
MMGC_STATIC_ASSERT(INT_MAX == 0x7fffffff);
// The size tables above are derived based on a block size of 4096; this
// assert keeps us honest. Talk to Lars if you get into trouble here.
//
// Also it appears that some GCDEBUG-mode guards in SetPageMapValue,
// GetPageMapValue, ClearPageMapValue know that the block size is 4096.
GCAssert(GCHeap::kBlockSize == 4096);
GCAssert(!(greedy && incremental));
zct.SetGC(this);
#ifdef VMCFG_TELEMETRY
VMPI_memset(m_dependentMemory, 0, sizeof(size_t) * typeCount);
#endif
VMPI_lockInit(&m_gcLock);
VMPI_lockInit(&m_rootListLock);
// Global budget for blocks on the quick lists of small-object allocators. This
// budget serves as a throttle on the free lists during times when the GC is not
// running; when the GC is running the periodic flushing of the quick lists
// makes the budget irrelevant. The budget is global so that very active allocators
// can have long free lists at the expense of inactive allocators, which must have
// short ones.
//
// This is somewhat arbitrary: 4 blocks per allocator. Must initialize this before we
// create allocators because they will request a budget when they're created. The
// total budget /must/ accomodate at least one block per alloc, and makes very little
// sense if it is not at least two blocks per alloc. (Note no memory is allocated, it's
// just a budget.)
//
// See comment in GCAlloc.cpp for more about the quick lists.
//### FIXME: Need to adjust for partitions? Many partitions will have only one size
//### of object, so providing for all the others inflates the budget.
remainingQuickListBudget = (3*kNumSizeClasses*kNumGCPartitions) * 4 * GCHeap::kBlockSize;
//### FIXME: Many partitions will not contain all types of storage or all size classes.
//### We should have a way to avoid creating the unnecessary GCAlloc instances.
//### This means at least being prepared for null entries in the allocator arrays, however,
//### which we are explicitly attempting to avoid here.
// Create all the allocators up front (not lazy)
// so that we don't have to check the pointers for
// NULL on every allocation.
for (int i=0; i<kNumSizeClasses; i++) {
for (int j=0; j<kNumGCPartitions; j++) {
containsPointersNonfinalizedAllocs[i][j] = mmfx_new(GCAlloc(this, kSizeClasses[i], true, false, false, i, j, SmallGCAllocHeapPartition(j), 0));
containsPointersFinalizedAllocs[i][j] = mmfx_new(GCAlloc(this, kSizeClasses[i], true, false, true, i, j, SmallGCAllocHeapPartition(j), 0));
containsPointersRCAllocs[i][j] = mmfx_new(GCAlloc(this, kSizeClasses[i], true, true, true, i, j, SmallGCAllocHeapPartition(j), 0));
noPointersNonfinalizedAllocs[i][j] = mmfx_new(GCAlloc(this, kSizeClasses[i], false, false, false, i, j, SmallGCAllocHeapPartition(j), 0));
noPointersFinalizedAllocs[i][j] = mmfx_new(GCAlloc(this, kSizeClasses[i], false, false, true, i, j, SmallGCAllocHeapPartition(j), 0));
}
}
/* Bibop allocators are a little tricky:
*
* - For the float allocator the /payload/ size is 8, because that's the smallest payload supported
*
* - For the float4 allocator the /total/ size must be divisible by 16; in this case GCAlloc guarantees
* 16-byte aligned allocations. We check that this guarantee is not violated in the implementation
* of GC::AllocBibopType() specialized for float4 (GC-inlines.h). In the case where DebugSize == 24
* this leads to a situation where the float4 allocator uses a size-48 object where a size-40 object
* would have been enough, if not for the divisibility requirement.
*
* For MMGC_MEMORY_INFO builds the bibop allocators waste a lot of space for these boxes, but frankly
* it's no worse than for double boxes, and anyway if the common case is fully typed code with Vector
* (this will be true for float and float4 especially) then the box cost is not a big deal.
*/
// Find a slice mapped to kBibopPartition.
// If none exists, just use slice 0 as a placeholder.
// Bibop allocations are only used when float/float4 are enabled.
// They are not used at present (2015.09.22), and we should probably just not create the allocators at all.
int bibopSlice = -1;
for (int i = 0; i < kNumGCPartitions; i++)
{
if (SmallGCAllocHeapPartition(i) == kBibopPartition)
{
bibopSlice = i;
break;
}
}
if (bibopSlice < 0)
bibopSlice = 0;
#if !defined MMGC_MEMORY_INFO
#if USER_POINTER_WORDS != 0
#error "GC::GC cannot handle this value of USER_POINTER_WORDS"
#endif
bibopAllocFloat = mmfx_new(GCAlloc(this, 8, false, false, false, /*sizeclass*/0, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloatType));
bibopAllocFloat4 = mmfx_new(GCAlloc(this, 16, false, false, false, /*sizeclass*/1, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloat4Type));
#else
#if USER_POINTER_WORDS != 2 && USER_POINTER_WORDS != 4
#error "GC::GC cannot handle this value of USER_POINTER_WORDS"
#endif
#ifdef MMGC_64BIT
#if USER_POINTER_WORDS == 2
GCAssert(DebugSize() == 24);
bibopAllocFloat = mmfx_new(GCAlloc(this, int(32), false, false, false, /*sizeclass*/3, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloatType));
bibopAllocFloat4 = mmfx_new(GCAlloc(this, int(48), false, false, false, /*sizeclass*/5 /*See above*/, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloat4Type));
#else
GCAssert(DebugSize() == 32);
bibopAllocFloat = mmfx_new(GCAlloc(this, int(40), false, false, false, /*sizeclass*/4, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloatType));
bibopAllocFloat4 = mmfx_new(GCAlloc(this, int(48), false, false, false, /*sizeclass*/5, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloat4Type));
#endif
#else // !MMGC_64BIT
#if USER_POINTER_WORDS == 2
GCAssert(DebugSize() == 16);
bibopAllocFloat = mmfx_new(GCAlloc(this, int(24), false, false, false, /*sizeclass*/2, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloatType));
bibopAllocFloat4 = mmfx_new(GCAlloc(this, int(32), false, false, false, /*sizeclass*/3, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloat4Type));
#else
GCAssert(DebugSize() == 24);
bibopAllocFloat = mmfx_new(GCAlloc(this, int(32), false, false, false, /*sizeclass*/3, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloatType));
bibopAllocFloat4 = mmfx_new(GCAlloc(this, int(48), false, false, false, /*sizeclass*/5 /*See above*/, bibopSlice, kBibopPartition, avmplus::AtomConstants::kBibopFloat4Type));
#endif
#endif
#endif
for (int i = 0; i < kNumGCPartitions; i++)
largeAllocs[i] = mmfx_new(GCLargeAlloc(this, LargeGCAllocHeapPartition(i)));
// See comment in GC.h
allocsTable[kRCObject] = &containsPointersRCAllocs;
allocsTable[kRCObject|kFinalize] = &containsPointersRCAllocs;
allocsTable[kRCObject|kContainsPointers] = &containsPointersRCAllocs;
allocsTable[kRCObject|kFinalize|kContainsPointers] = &containsPointersRCAllocs;
allocsTable[kContainsPointers] = &containsPointersNonfinalizedAllocs;
allocsTable[kContainsPointers|kFinalize] = &containsPointersFinalizedAllocs;
allocsTable[kFinalize] = &noPointersFinalizedAllocs;
allocsTable[0] = &noPointersNonfinalizedAllocs;
VMPI_memset(m_bitsFreelists, 0, sizeof(uint32_t*) * kNumSizeClasses * kNumGCPartitions);
m_bitsNext = (uint32_t*)heapAlloc(1, kGCBitmapPartition);
// precondition for emptyPageList
GCAssert(offsetof(GCLargeAlloc::LargeBlock, next) == offsetof(GCAlloc::GCBlock, next));
for(int i=0; i<GCV_COUNT; i++)
{
SetGCContextVariable(i, NULL);
}
allocaInit();
MMGC_GCENTER(this);
emptyWeakRef = new (this) GCWeakRef(NULL); // Note, we don't profile this one because the profiler is not yet allocated
m_incrementalWork.SetDeadItem(emptyWeakRef); // The empty weak ref is as good an object as any for this
#ifdef MMGC_CONSERVATIVE_PROFILER
if (demos == NULL && heap->profiler != NULL)
demos = new AllocationSiteProfiler(this, "Conservative scanning volume incurred by allocation site");
#endif
#ifdef MMGC_WEAKREF_PROFILER
if (weaklings == NULL && heap->profiler != NULL)
weaklings = new WeakRefAllocationSiteProfiler(this, "Weak reference allocation volume by allocation site");
#endif
#ifdef MMGC_DELETION_PROFILER
if (deletos == NULL && heap->profiler != NULL)
deletos = new DeletionProfiler(this, "Explicit deletion of managed storage");
#endif
gcheap->AddGC(this);
gcheap->AddOOMCallback(this);
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
GC::~GC()
{
#ifdef MMGC_CONSERVATIVE_PROFILER
if (demos != NULL)
{
GCLog("Exactly traced percentage: %u\n", policy.queryExactPercentage());
demos->dumpTopBacktraces(30, demos->BY_COUNT);
delete demos;
demos = NULL;
}
#endif
#ifdef MMGC_WEAKREF_PROFILER
if (weaklings != NULL)
{
GCLog("Peak weakref population: %u\n", weaklings->peakPopulation);
GCLog("Probes: %llu accesses: %llu ratio: %f\n",
(unsigned long long)weakRefs.probes,
(unsigned long long)weakRefs.accesses,
(double)weakRefs.probes/(double)weakRefs.accesses);
GCLog("GCs: %u, scanned: %llu, removed: %llu\n",
weaklings->collections,
(unsigned long long)weaklings->scannedAtGC,
(unsigned long long)weaklings->removedAtGC);
weaklings->dumpTopBacktraces(30, weaklings->BY_COUNT);
delete weaklings;
weaklings = NULL;
}
#endif
#ifdef MMGC_HEAP_GRAPH
printBlacklist();
#endif
policy.shutdown();
allocaShutdown();
// Do this before calling GCHeap::RemoveGC as GCAutoEnter::Destroy
// expect this GC to still be the active GC and GCHeap::RemoveGC clears
// the active GC.
if(stackEnter != NULL) {
stackEnter->Destroy(false);
}
heap->RemoveGC(this);
heap->RemoveOOMCallback(this);
// Force all objects to be destroyed
destroying = true;
{
MMGC_GCENTER(this);
ForceSweepAtShutdown();
}
for (int i=0; i < kNumSizeClasses; i++) {
for (int j=0; j < kNumGCPartitions; j++) {
mmfx_delete(containsPointersNonfinalizedAllocs[i][j]);
mmfx_delete(containsPointersFinalizedAllocs[i][j]);
mmfx_delete(containsPointersRCAllocs[i][j]);
mmfx_delete(noPointersNonfinalizedAllocs[i][j]);
mmfx_delete(noPointersFinalizedAllocs[i][j]);
}
}
mmfx_delete(bibopAllocFloat);
mmfx_delete(bibopAllocFloat4);
for (int i = 0; i < kNumGCPartitions; i++) {
if (largeAllocs[i]) {
mmfx_delete(largeAllocs[i]);
}
}
// Go through m_bitsFreelist and collect list of all pointers
// that are on page boundaries into new list, pageList
void **pageList = NULL;
for(int i=0, n=kNumSizeClasses; i<n; i++) {
for (int j=0, m=kNumGCPartitions; j<m; j++) {
uint32_t* bitsFreelist = m_bitsFreelists[i][j];
while(bitsFreelist) {
uint32_t *next = *(uint32_t**)bitsFreelist;
if((uintptr_t(bitsFreelist) & GCHeap::kOffsetMask) == 0) {
*((void**)bitsFreelist) = pageList;
pageList = (void**)bitsFreelist;
}
bitsFreelist = next;
}
}
}
// Go through page list and free all pages on it
while (pageList) {
void **next = (void**) *pageList;
heapFree((void*)pageList, /*siz*/0, kGCBitmapPartition);
pageList = next;
}
pageMap.DestroyPageMapVia(heap);
GCAssert(!m_roots);
GCAssert(!m_callbacks);
// apparently the player can't be made to clean up so keep it from crashing at least
while(m_roots) {
m_roots->Destroy();
}
while(m_callbacks) {
m_callbacks->Destroy();
}
zct.Destroy();
#ifdef MMGC_DELETION_PROFILER
/* 'deletos' should only be deleted after ForceSweepAtShutdown()
* as that can lead to ProfileExplicitDeletion() calls
*/
if (deletos != NULL)
{
deletos->dumpTopBacktraces(30, deletos->BY_COUNT);
delete deletos;
deletos = NULL;
}
#endif
GCAssertMsg(GetNumBlocks() == 0, "GC accounting off");
GCAssertMsg(enterCount == 0, "GC enter/exit paths broken");
VMPI_lockDestroy(&m_gcLock);
VMPI_lockDestroy(&m_rootListLock);
}
void GC::Collect(bool scanStack, bool okToShrinkHeapTarget)
{
GCAssertMsg(!scanStack || onThread(), "Full collection with stack scan requested however the GC isn't associated with a thread, missing MMGC_GCENTER macro.");
if (nogc || markerActive || collecting || Reaping()) {
return;
}
TELEMETRY_METHOD(getTelemetry(), ".gc.Collect");
ReapZCT(scanStack);
if(!marking)
StartIncrementalMark();
if(marking)
FinishIncrementalMark(scanStack, okToShrinkHeapTarget);
#ifdef GCDEBUG
// Dumping the stack trace at GC time can be very helpful with stack walk bugs
// where something was created, stored away in untraced, unmanaged memory and not
// reachable by the conservative stack walk
//DumpStackTrace();
FindUnmarkedPointers();
#endif
// Sweep eagerly - this gives us the best effect, especially since FinishIncrementalMark
// is not freeing empty blocks that do not hold finalizable objects.
SweepNeedsSweeping();
policy.fullCollectionComplete();
}
void GC::Collect(double allocationBudgetFractionUsed)
{
if (allocationBudgetFractionUsed < 0.25) allocationBudgetFractionUsed = 0.25;
if (allocationBudgetFractionUsed > 1.0) allocationBudgetFractionUsed = 1.0;
// Spec says "if the parameter exceeds the fraction used ..."
if (policy.queryAllocationBudgetFractionUsed() <= allocationBudgetFractionUsed)
return;
GC::Collect(true, false);
}
REALLY_INLINE void GC::Push_StackMemory(const void* p, uint32_t size, const void* baseptr)
{
GCAssert(p != NULL);
GCAssert(!IsPointerToGCPage(GetRealPointer(p)) || !IsPointerToGCObject(GetRealPointer(p)));
if (!m_incrementalWork.Push_StackMemory(p, size, baseptr))
SignalMarkStackOverflow_NonGCObject();
}
REALLY_INLINE bool GC::Push_RootProtector(const void* p)
{
GCAssert(p != NULL);
GCAssert(!IsPointerToGCPage(GetRealPointer(p)) || !IsPointerToGCObject(GetRealPointer(p)));
if (!m_incrementalWork.Push_RootProtector(p)) {
SignalMarkStackOverflow_NonGCObject();
return false;
}
return true;
}
REALLY_INLINE void GC::Push_LargeObjectProtector(const void* p)
{
GCAssert(p != NULL);
GCAssert(IsPointerToGCPage(GetRealPointer(p)) && IsPointerToGCObject(GetRealPointer(p)));
if (!m_incrementalWork.Push_LargeObjectProtector(p))
SignalMarkStackOverflow_NonGCObject();
}
REALLY_INLINE void GC::Push_LargeExactObjectTail(const void* p, size_t cursor)
{
GCAssert(p != NULL);
GCAssert(cursor != 0);
GCAssert(IsPointerToGCPage(GetRealPointer(p)) && IsPointerToGCObject(GetRealPointer(p)));
if (!m_incrementalWork.Push_LargeExactObjectTail(p, cursor))
SignalMarkStackOverflow_NonGCObject();
}
REALLY_INLINE void GC::Push_LargeObjectChunk(const void *p, uint32_t size, const void* baseptr)
{
GCAssert(p != NULL);
GCAssert(IsPointerToGCPage(p));
GCAssert(IsPointerToGCPage((char*)p + size - 1));
if (!m_incrementalWork.Push_LargeObjectChunk(p, size, baseptr))
SignalMarkStackOverflow_NonGCObject();
}
REALLY_INLINE void GC::Push_LargeRootChunk(const void *p, uint32_t size, const void* baseptr)
{
GCAssert(p != NULL);
GCAssert(!IsPointerToGCPage(p));
GCAssert(!IsPointerToGCPage((char*)p + size - 1));
if (!m_incrementalWork.Push_LargeRootChunk(p, size, baseptr))
SignalMarkStackOverflow_NonGCObject();
}
REALLY_INLINE void GC::Push_GCObject(const void *p)
{
#ifdef GCDEBUG
WorkItemInvariants_GCObject(p);
#endif
if (!m_incrementalWork.Push_GCObject(p))
SignalMarkStackOverflow_GCObject(p);
}
void GC::Push_GCObject_MayFail(const void *p)
{
#ifdef GCDEBUG
WorkItemInvariants_GCObject(p);
#endif
m_incrementalWork.Push_GCObject(p);
}
#ifdef GCDEBUG
void GC::WorkItemInvariants_GCObject(const void *p)
{
GCAssert(p != NULL);
GCAssert(IsPointerToGCObject(GetRealPointer(p)));
GCAssert(ContainsPointers(p));
GCAssert(!IsRCObject(p) || ((RCObject*)p)->composite != 0);
GCAssert((GetGCBits(GetRealPointer(p)) & (kQueued|kMark)) == kQueued);
}
#endif
void GC::AbortInProgressMarking()
{
ClearMarkStack();
m_barrierWork.Clear();
ClearMarks();
#ifdef MMGC_HEAP_GRAPH
markerGraph.clear();
#endif
marking = false;
}
#ifdef GCDEBUG
void GC::DRCValidationTrace(bool scanStack)
{
if(marking) {
AbortInProgressMarking();
}
performingDRCValidationTrace = true;
MarkNonstackRoots();
MarkQueueAndStack(scanStack);
#ifdef GCDEBUG
// If we're doing a mark to validate DRC then also pin
// RCObjects here.
VMPI_callWithRegistersSaved(ZCT::DoPinProgramStack, &zct);
#endif
if(m_markStackOverflow) {
// oh well
AbortInProgressMarking();
validateDefRef = false;
GCLog("Warning: Mark stack overflow during DRC validation, disabling validation.");
}
performingDRCValidationTrace = false;
}
#endif
GC::RCRootSegment::RCRootSegment(GC* gc, void* mem, size_t size)
: StackMemory(gc, mem, size)
, mem(mem)
, size(size)
, prev(NULL)
, next(NULL)
{}
void* GC::AllocRCRoot(size_t size)
{
const int hdr_size = (sizeof(void*) + 7) & ~7;
GCHeap::CheckForAllocSizeOverflow(size, hdr_size);
union {
char* block;
uintptr_t* block_u;
};
block = mmfx_new_array_opt(char, size + hdr_size, MMgc::kZero);
void* mem = (void*)(block + hdr_size);
RCRootSegment *segment = new RCRootSegment(this, mem, size);
*block_u = (uintptr_t)segment;
AddRCRootSegment(segment);
return mem;
}
void GC::FreeRCRoot(void* mem)
{
const int hdr_size = (sizeof(void*) + 7) & ~7;
union {
char* block;
RCRootSegment** segmentp;
};
block = (char*)mem - hdr_size;
RCRootSegment* segment = *segmentp;
RemoveRCRootSegment(segment);
delete segment;
mmfx_delete_array(block);
}
void GC::CollectionWork()
{
if (nogc)
return;
TELEMETRY_METHOD(getTelemetry(), ".gc.CollectionWork");
if (incremental) {
// If we're reaping don't do any work, this simplifies policy event timing and improves
// incrementality.
if (!collecting && !Reaping()) {
if (!marking) {
StartIncrementalMark();
}
else if (policy.queryEndOfCollectionCycle()) {
FinishIncrementalMark(true);
}
else {
IncrementalMark();
}
}
}
else {
// non-incremental collection
Collect();
}
}
// Note, the interaction with the policy manager in Alloc() should
// be the same as in AllocDouble(), which is defined in GC.h.
// In Alloc we have separate cases for large and small objects. We want
// small-object allocation to be as fast as possible. Hence the relative
// mess of #ifdefs below, and the following explanation.
//
// Normally we round up size to 8 bytes and add DebugSize and that sum is
// the size that determines whether we use the small-object allocator or
// the large-object one:
//
// requestSize = ((size + 7) & ~7) + DebugSize()
//
// Then we shift that three places and subtract 1 to obtain the allocator
// index:
//
// index = (requestSize >> 3) - 1
// = ((((size + 7) & ~7) + DebugSize()) >> 3) - 1
//
// We want to optimize this. Consider the case of a Release build where
// DebugSize() == 0:
//
// = (((size + 7) & ~7) >> 3) - 1
//
// Observe that the & ~7 is redundant because those bits will be lost,
// and that 1 = (8 >> 3)
//
// = ((size + 7) >> 3) - (8 >> 3)
// = (size + 7 - 8) >> 3
// index = (size - 1) >> 3
//
// In Release builds, the guard for small object allocation is
//
// guard = requestSize <= kLargestAlloc
// = ((size + 7) & ~7) <= kLargestAlloc
//
// Yet the /effective/ guard, given that not all the bits of size are used
// subsequently, is simply
//
// guard = size <= kLargestAlloc
//
// To see this, consider that if size < kLargestAlloc then requestSize <= kLargestAlloc
// and if size > kLargestAlloc then requestSize > kLargestAlloc, because requestSize
// is rounded up to an 8-byte boundary and kLargestAlloc is already rounded to an 8-byte
// boundary.
//
// So in the small-object case in Release builds we use the simpler guard, and defer
// the rounding and allocation overflow checking to the large-object case.
#ifdef MMGC_MEMORY_INFO
#ifndef GCDEBUG
#error "Really need MMGC_MEMORY_INFO to imply GCDEBUG"
#endif
#endif
#ifdef MMGC_MEMORY_PROFILER
#ifndef MMGC_HOOKS
#error "Really need MMGC_MEMORY_PROFILER to imply MMGC_HOOKS"
#endif
#endif
#ifdef GCDEBUG
void GC::AllocPrologue(size_t size)
{
GCAssertMsg(size > 0, "cannot allocate a 0 sized block");
GCAssertMsg(onThread(), "GC called from different thread!");
GCAssertMsg(!Destroying(), "GC allocations during shutdown are illegal.");
if(!nogc && stackEnter == NULL) {
GCAssertMsg(false, "A MMGC_GCENTER macro must exist on the stack");
GCHeap::SignalInconsistentHeapState("MMGC_GCENTER missing");
/*NOTREACHED*/
return;
}
// always be marking in pedantic mode
if(incrementalValidationPedantic) {
if(!marking) {
if (!Reaping()) {
StartIncrementalMark();
}
}
}
}
void* GC::AllocEpilogue(void* item, int flags)
{
// Note GetUserPointer(item) only required for DEBUG builds and for non-NULL pointers.
if(item != NULL) {
item = GetUserPointer(item);
bool shouldZero = (flags & kZero) || incrementalValidationPedantic;
// in debug mode memory is poisoned so we have to clear it here
// in release builds memory is zero'd to start and on free/sweep
// in pedantic mode uninitialized data can trip the write barrier
// detector, only do it for pedantic because otherwise we want the
// mutator to get the poisoned data so it crashes if it relies on
// uninitialized values
if(shouldZero) {
VMPI_memset(item, 0, Size(item));
}
}
return item;
}
#endif
void *GC::Alloc(size_t size, int flags, int partition)
{
GCAssert(partition < kNumGCPartitions);
#ifdef GCDEBUG
AllocPrologue(size);
#endif
#ifdef AVMPLUS_SAMPLER
avmplus::AvmCore *core = (avmplus::AvmCore*)GetGCContextVariable(GCV_AVMCORE);
if(core)
core->sampleCheck();
#endif
#if defined GCDEBUG || defined MMGC_MEMORY_PROFILER
const size_t askSize = size; // preserve this for statistics gathering and profiling
#endif
#if defined GCDEBUG
GCHeap::CheckForAllocSizeOverflow(size, 7+DebugSize());
size = (size+7)&~7; // round up to multiple of 8
size += DebugSize(); // add in some (possibly zero) multiple of 8 bytes for debug information
#endif
void *item; // the allocated object (a user pointer!), or NULL
// In Release builds the calls to the underlying Allocs should end up being compiled
// as tail calls with reasonable compilers. Try to keep it that way.
if (size <= kLargestAlloc)
{
// This is the fast lookup table implementation to find the right allocator.
// The table has been lifted into an instance variable because the Player is
// compiled with PIC and GCC generates somewhat gnarly code for that.
#ifdef GCDEBUG
const unsigned index = sizeClassIndex[(size>>3)-1];
#else
const unsigned index = sizeClassIndex[(size-1)>>3];
#endif
// The table avoids a five-way decision tree.
Allocators* allocs = allocsTable[flags & (kRCObject|kFinalizable|kContainsPointers)];
// assert that I fit
GCAssert(size <= (*allocs)[index][partition]->GetItemSize());
// assert that I don't fit (makes sure we don't waste space)
GCAssert( (index==0) || (size > (*allocs)[index-1][partition]->GetItemSize()));
#if defined GCDEBUG || defined MMGC_MEMORY_PROFILER
item = (*allocs)[index][partition]->Alloc(askSize, flags);
#else
item = (*allocs)[index][partition]->Alloc(flags);
#endif
}
else
{
#ifndef GCDEBUG
GCHeap::CheckForAllocSizeOverflow(size, 7+DebugSize());
size = (size+7)&~7; // round up to multiple of 8
size += DebugSize();
#endif
#if defined GCDEBUG || defined MMGC_MEMORY_PROFILER
item = largeAllocs[partition]->Alloc(askSize, size, flags);
#else
item = largeAllocs[partition]->Alloc(size, flags);
#endif
}
// Hooks are run by the lower-level allocators, which also signal
// allocation work and trigger GC.
GCAssert(item != NULL || (flags & kCanFail) != 0);
#ifdef GCDEBUG
item = AllocEpilogue(item, flags);
#endif
return item;
}
#if defined GCDEBUG || defined AVMPLUS_SAMPLER || defined MMGC_MEMORY_PROFILER
void *GC::AllocSlow(GCAlloc* bibopAlloc)
{
#ifdef GCDEBUG
AllocPrologue(bibopAlloc->m_itemSize);
#endif
#ifdef AVMPLUS_SAMPLER
avmplus::AvmCore *core = (avmplus::AvmCore*)GetGCContextVariable(GCV_AVMCORE);
if(core)
core->sampleCheck();
#endif
void* item;
#if defined GCDEBUG || defined MMGC_MEMORY_PROFILER
item = bibopAlloc->Alloc(/*sizeof(float)*/ bibopAlloc == bibopAllocFloat4? 16:4, /*flags*/0);
#else
item = bibopAlloc->Alloc(/*flags*/0);
#endif
GCAssert(item != NULL);
#ifdef GCDEBUG
item = AllocEpilogue(item, 0);
#endif
return item;
}
#endif
// Mmmm.... gcc -O3 inlines Alloc into this in Release builds :-)
void *GC::OutOfLineAllocExtra(size_t size, size_t extra, int flags, int partition)
{
return AllocExtra(size, extra, flags, partition);
}
void GC::AbortFree(const void* item)
{
// Always clear the contents to avoid false retention of data: the
// object will henceforth be scanned conservatively, and it may be
// reachable from the stack or from other objects (dangling pointers
// caused by improper use of Free(), or non-pointers interpreted
// as pointers by the conservative scanner).
// wmaddox 2015.08.12
//
// The comment above is not accurate: We no longer clear the gc traceable
// bit, and the tracer may be invoked on the subject of an aborted free.
// The change occurred in tamarin-redux changeset 5840 on 2011.01.23, which
// reverts a change made in changset 5581 on 2010.11.29. This is
// discussed in bugzilla 626612, which removed the MMgc::setExact() API.
// A documented consequence is that GC tracers may now be invoked on
// objects whose bodies had been zeroed out, but had not finished
// construction. The GC invariants were updated to require that tracers
// tolerate an all-zeros bit pattern in all pointer fields. The documented
// invariants impose no such requirement on non-pointer fields, but it is
// apparent from the code and surrounding discussion that a tracer may be
// expected to tolerate an object that has been completely zeroed out.
//
// It is believed that tracers can be invoked on such objects only
// during initialization and as a result of an aborted free. Class
// TracedListData in avmplusList.h maintains its length in a non-canonical
// form, in which a logical length of zero is not represented by an
// actual zero value within the object. That scheme will break if the claim
// made here is false.
Zero(item);
// It would not be right to clear the finalized bit if we could get here other
// than via operator delete, but there's code in the GC interface to ensure
// that GC::Free and FreeNotNull are not invoked on finalized objects. Thus
// we're OK clearing the finalized bit here without worrying about whether the
// destructor needs to be run.
//
// Weakly held or exactly traced objects do not have similar correctness issues.
//
// See Bugzilla 589102 for more information.
ClearFinalized(item);
if(HasWeakRef(item))
ClearWeakRef(item);
}
void GC::Zero(const void* userptr)
{
if (IsFinalized(userptr)) {
GCFinalizedObject* obj = (GCFinalizedObject*)userptr;
VMPI_memset((char*)obj + sizeof(GCFinalizedObject), 0, GC::Size(obj) - sizeof(GCFinalizedObject));