-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathgcenv.ee.cpp
1753 lines (1518 loc) · 59.5 KB
/
gcenv.ee.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
* GCENV.EE.CPP
*
* GCToEEInterface implementation
*
*
*/
#include "gcrefmap.h"
void GCToEEInterface::SuspendEE(SUSPEND_REASON reason)
{
WRAPPER_NO_CONTRACT;
static_assert_no_msg(SUSPEND_FOR_GC == (int)ThreadSuspend::SUSPEND_FOR_GC);
static_assert_no_msg(SUSPEND_FOR_GC_PREP == (int)ThreadSuspend::SUSPEND_FOR_GC_PREP);
_ASSERTE(reason == SUSPEND_FOR_GC || reason == SUSPEND_FOR_GC_PREP);
g_pDebugInterface->SuspendForGarbageCollectionStarted();
ThreadSuspend::SuspendEE((ThreadSuspend::SUSPEND_REASON)reason);
g_pDebugInterface->SuspendForGarbageCollectionCompleted();
}
void GCToEEInterface::RestartEE(bool bFinishedGC)
{
WRAPPER_NO_CONTRACT;
g_pDebugInterface->ResumeForGarbageCollectionStarted();
ThreadSuspend::RestartEE(bFinishedGC, TRUE);
}
VOID GCToEEInterface::SyncBlockCacheWeakPtrScan(HANDLESCANPROC scanProc, uintptr_t lp1, uintptr_t lp2)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
SyncBlockCache::GetSyncBlockCache()->GCWeakPtrScan(scanProc, lp1, lp2);
}
void GCToEEInterface::BeforeGcScanRoots(int condemned, bool is_bgc, bool is_concurrent)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef VERIFY_HEAP
if (is_bgc)
{
// Validate byrefs pinned by IL stubs since the last GC.
StubHelpers::ProcessByrefValidationList();
}
#endif // VERIFY_HEAP
Interop::OnBeforeGCScanRoots(is_concurrent);
}
//EE can perform post stack scanning action, while the
// user threads are still suspended
VOID GCToEEInterface::AfterGcScanRoots (int condemned, int max_gen,
ScanContext* sc)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef FEATURE_COMINTEROP
// Go through all the only app domain and detach all the *unmarked* RCWs to prevent
// the RCW cache from resurrecting them.
::GetAppDomain()->DetachRCWs();
#endif // FEATURE_COMINTEROP
Interop::OnAfterGCScanRoots(sc->concurrent);
}
/*
* Scan all stack roots
*/
static void ScanStackRoots(Thread * pThread, promote_func* fn, ScanContext* sc)
{
GCCONTEXT gcctx;
gcctx.f = fn;
gcctx.sc = sc;
gcctx.cf = NULL;
ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
// Either we are in a concurrent situation (in which case the thread is unknown to
// us), or we are performing a synchronous GC and we are the GC thread, holding
// the threadstore lock.
_ASSERTE(dbgOnly_IsSpecialEEThread() ||
GetThreadNULLOk() == NULL ||
// this is for background GC threads which always call this when EE is suspended.
IsGCSpecialThread() ||
(GetThread() == ThreadSuspend::GetSuspensionThread() && ThreadStore::HoldingThreadStore()));
Frame* pTopFrame = pThread->GetFrame();
Object ** topStack = (Object **)pTopFrame;
if ((pTopFrame != ((Frame*)-1))
&& (pTopFrame->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr())) {
// It is an InlinedCallFrame. Get SP from it.
InlinedCallFrame* pInlinedFrame = (InlinedCallFrame*)pTopFrame;
topStack = (Object **)pInlinedFrame->GetCallSiteSP();
}
sc->stack_limit = (uintptr_t)topStack;
#ifdef FEATURE_CONSERVATIVE_GC
if (g_pConfig->GetGCConservative())
{
// Conservative stack root reporting
// We will treat everything on stack as a pinned interior GC pointer
// Since we report every thing as pinned, we don't need to run following code for relocation phase.
if (sc->promotion)
{
Object ** bottomStack = (Object **) pThread->GetCachedStackBase();
Object ** walk;
for (walk = topStack; walk < bottomStack; walk ++)
{
if (((void*)*walk > (void*)bottomStack || (void*)*walk < (void*)topStack) &&
((void*)*walk >= (void*)g_lowest_address && (void*)*walk <= (void*)g_highest_address)
)
{
//DbgPrintf("promote " FMT_ADDR " : " FMT_ADDR "\n", walk, *walk);
fn(walk, sc, GC_CALL_INTERIOR|GC_CALL_PINNED);
}
}
}
// Also ask the explicit Frames to report any references they might know about.
// Generally these will be a subset of the objects reported below but there's
// nothing that guarantees that and in the specific case of a GC protect frame the
// references it protects may live at a lower address than the frame itself (and
// thus escape the stack range we scanned above).
Frame *pFrame = pThread->GetFrame();
while (pFrame != FRAME_TOP)
{
pFrame->GcScanRoots(fn, sc);
pFrame = pFrame->PtrNextFrame();
}
}
else
#endif
{
unsigned flagsStackWalk = ALLOW_ASYNC_STACK_WALK | ALLOW_INVALID_OBJECTS;
#if defined(FEATURE_EH_FUNCLETS)
flagsStackWalk |= GC_FUNCLET_REFERENCE_REPORTING;
#endif // defined(FEATURE_EH_FUNCLETS)
pThread->StackWalkFrames( GcStackCrawlCallBack, &gcctx, flagsStackWalk);
}
GCFrame* pGCFrame = pThread->GetGCFrame();
while (pGCFrame != NULL)
{
pGCFrame->GcScanRoots(fn, sc);
pGCFrame = pGCFrame->PtrNextFrame();
}
}
static void ScanTailCallArgBufferRoots(Thread* pThread, promote_func* fn, ScanContext* sc)
{
TailCallTls* tls = pThread->GetTailCallTls();
// Keep loader associated with CallTailCallTarget alive.
if (sc->promotion)
{
#ifndef DACCESS_COMPILE
const PortableTailCallFrame* frame = tls->GetFrame();
if (frame->NextCall != NULL)
{
MethodDesc* pMD = NonVirtualEntry2MethodDesc((PCODE)frame->NextCall);
if (pMD != NULL)
GcReportLoaderAllocator(fn, sc, pMD->GetLoaderAllocator());
}
#endif
}
TailCallArgBuffer* argBuffer = tls->GetArgBuffer();
if (argBuffer == NULL || argBuffer->GCDesc == NULL)
return;
if (argBuffer->State == TAILCALLARGBUFFER_ABANDONED)
return;
bool instArgOnly = argBuffer->State == TAILCALLARGBUFFER_INSTARG_ONLY;
GCRefMapDecoder decoder(static_cast<PTR_BYTE>(argBuffer->GCDesc));
while (!decoder.AtEnd())
{
int pos = decoder.CurrentPos();
int token = decoder.ReadToken();
PTR_TADDR ppObj = dac_cast<PTR_TADDR>(((BYTE*)argBuffer->Args) + pos * sizeof(TADDR));
switch (token)
{
case GCREFMAP_SKIP:
break;
case GCREFMAP_REF:
if (!instArgOnly)
fn(dac_cast<PTR_PTR_Object>(ppObj), sc, CHECK_APP_DOMAIN);
break;
case GCREFMAP_INTERIOR:
if (!instArgOnly)
PromoteCarefully(fn, dac_cast<PTR_PTR_Object>(ppObj), sc, GC_CALL_INTERIOR);
break;
case GCREFMAP_METHOD_PARAM:
if (sc->promotion)
{
#ifndef DACCESS_COMPILE
MethodDesc *pMDReal = dac_cast<PTR_MethodDesc>(*ppObj);
if (pMDReal != NULL)
GcReportLoaderAllocator(fn, sc, pMDReal->GetLoaderAllocator());
#endif
}
break;
case GCREFMAP_TYPE_PARAM:
if (sc->promotion)
{
#ifndef DACCESS_COMPILE
MethodTable *pMTReal = dac_cast<PTR_MethodTable>(*ppObj);
if (pMTReal != NULL)
GcReportLoaderAllocator(fn, sc, pMTReal->GetLoaderAllocator());
#endif
}
break;
default:
_ASSERTE(!"Unhandled GCREFMAP token in arg buffer GC desc");
break;
}
}
}
void GCToEEInterface::GcScanRoots(promote_func* fn, int condemned, int max_gen, ScanContext* sc)
{
STRESS_LOG1(LF_GCROOTS, LL_INFO10, "GCScan: Promotion Phase = %d\n", sc->promotion);
Thread* pThread = NULL;
while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
{
STRESS_LOG2(LF_GC | LF_GCROOTS, LL_INFO100, "{ Starting scan of Thread %p ID = %x\n", pThread, pThread->GetThreadId());
if (GCHeapUtilities::GetGCHeap()->IsThreadUsingAllocationContextHeap(
pThread->GetAllocContext(), sc->thread_number))
{
sc->thread_under_crawl = pThread;
#ifdef FEATURE_EVENT_TRACE
sc->dwEtwRootKind = kEtwGCRootKindStack;
#endif // FEATURE_EVENT_TRACE
ScanStackRoots(pThread, fn, sc);
ScanTailCallArgBufferRoots(pThread, fn, sc);
#ifdef FEATURE_EVENT_TRACE
sc->dwEtwRootKind = kEtwGCRootKindOther;
#endif // FEATURE_EVENT_TRACE
}
STRESS_LOG2(LF_GC | LF_GCROOTS, LL_INFO100, "Ending scan of Thread %p ID = 0x%x }\n", pThread, pThread->GetThreadId());
}
// In server GC, we should be competing for marking the statics
// It's better to do this *after* stack scanning, because this way
// we can make up for imbalances in stack scanning
// This would not apply to the initial mark phase in background GC,
// but it would apply to blocking Gen 2 collections and the final
// marking stage in background GC where we catch up to the user program
if (GCHeapUtilities::MarkShouldCompeteForStatics())
{
if (condemned == max_gen && sc->promotion)
{
SystemDomain::EnumAllStaticGCRefs(fn, sc);
}
}
}
void GCToEEInterface::GcStartWork (int condemned, int max_gen)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef VERIFY_HEAP
// Validate byrefs pinned by IL stubs since the last GC.
StubHelpers::ProcessByrefValidationList();
#endif // VERIFY_HEAP
ExecutionManager::CleanupCodeHeaps();
#ifdef FEATURE_EVENT_TRACE
ETW::TypeSystemLog::Cleanup();
#endif
Interop::OnGCStarted(condemned);
if (condemned == max_gen)
{
ThreadStore::s_pThreadStore->OnMaxGenerationGCStarted();
}
}
void GCToEEInterface::GcDone(int condemned)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
Interop::OnGCFinished(condemned);
}
bool GCToEEInterface::RefCountedHandleCallbacks(Object * pObject)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef FEATURE_COMINTEROP
//<REVISIT_TODO>@todo optimize the access to the ref-count
ComCallWrapper* pWrap = ComCallWrapper::GetWrapperForObject((OBJECTREF)pObject);
if (pWrap != NULL && pWrap->IsWrapperActive())
return true;
#endif
#ifdef FEATURE_COMWRAPPERS
bool isRooted = false;
if (ComWrappersNative::HasManagedObjectComWrapper((OBJECTREF)pObject, &isRooted))
return isRooted;
#endif
#ifdef FEATURE_OBJCMARSHAL
bool isReferenced = false;
if (ObjCMarshalNative::IsTrackedReference((OBJECTREF)pObject, &isReferenced))
return isReferenced;
#endif
return false;
}
void GCToEEInterface::SyncBlockCacheDemote(int max_gen)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
SyncBlockCache::GetSyncBlockCache()->GCDone(TRUE, max_gen);
}
void GCToEEInterface::SyncBlockCachePromotionsGranted(int max_gen)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
SyncBlockCache::GetSyncBlockCache()->GCDone(FALSE, max_gen);
}
uint32_t GCToEEInterface::GetActiveSyncBlockCount()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
return SyncBlockCache::GetSyncBlockCache()->GetActiveCount();
}
gc_alloc_context * GCToEEInterface::GetAllocContext()
{
WRAPPER_NO_CONTRACT;
Thread* pThread = ::GetThreadNULLOk();
if (!pThread)
{
return nullptr;
}
return pThread->GetAllocContext();
}
void GCToEEInterface::GcEnumAllocContexts(enum_alloc_context_func* fn, void* param)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (GCHeapUtilities::UseThreadAllocationContexts())
{
Thread * pThread = NULL;
while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
{
fn(pThread->GetAllocContext(), param);
}
}
else
{
fn(&g_global_alloc_context, param);
}
}
uint8_t* GCToEEInterface::GetLoaderAllocatorObjectForGC(Object* pObject)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
return pObject->GetGCSafeMethodTable()->GetLoaderAllocatorObjectForGC();
}
bool GCToEEInterface::IsPreemptiveGCDisabled()
{
WRAPPER_NO_CONTRACT;
Thread* pThread = ::GetThreadNULLOk();
return (pThread && pThread->PreemptiveGCDisabled());
}
bool GCToEEInterface::EnablePreemptiveGC()
{
WRAPPER_NO_CONTRACT;
Thread* pThread = ::GetThreadNULLOk();
if (pThread && pThread->PreemptiveGCDisabled())
{
pThread->EnablePreemptiveGC();
return true;
}
return false;
}
void GCToEEInterface::DisablePreemptiveGC()
{
WRAPPER_NO_CONTRACT;
Thread* pThread = ::GetThreadNULLOk();
if (pThread)
{
pThread->DisablePreemptiveGC();
}
}
Thread* GCToEEInterface::GetThread()
{
WRAPPER_NO_CONTRACT;
return ::GetThreadNULLOk();
}
//
// Diagnostics code
//
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
// Tracks all surviving objects (moved or otherwise).
inline bool ShouldTrackSurvivorsForProfilerOrEtw()
{
#ifdef GC_PROFILING
if (CORProfilerTrackGC())
return true;
#endif
#ifdef FEATURE_EVENT_TRACE
if (ETW::GCLog::ShouldTrackMovementForEtw())
return true;
#endif
return false;
}
// Only tracks surviving objects in compacting GCs (moved or otherwise).
inline bool ShouldTrackSurvivorsInCompactingGCsForProfiler()
{
#ifdef GC_PROFILING
if (CORProfilerTrackGCMovedObjects())
return true;
#endif
return false;
}
#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
void ProfScanRootsHelper(Object** ppObject, ScanContext *pSC, uint32_t dwFlags)
{
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
Object *pObj = *ppObject;
if (dwFlags & GC_CALL_INTERIOR)
{
pObj = GCHeapUtilities::GetGCHeap()->GetContainingObject(pObj, true);
if (pObj == nullptr)
return;
}
ScanRootsHelper(pObj, ppObject, pSC, dwFlags);
#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
}
// TODO - at some point we would like to completely decouple profiling
// from ETW tracing using a pattern similar to this, where the
// ProfilingScanContext has flags about whether or not certain things
// should be tracked, and each one of these ProfilerShouldXYZ functions
// will check these flags and determine what to do based upon that.
// GCProfileWalkHeapWorker can, in turn, call those methods without fear
// of things being ifdef'd out.
// Returns TRUE if GC profiling is enabled and the profiler
// should scan dependent handles, FALSE otherwise.
BOOL ProfilerShouldTrackConditionalWeakTableElements()
{
#if defined(GC_PROFILING)
return CORProfilerTrackConditionalWeakTableElements();
#else
return FALSE;
#endif // defined (GC_PROFILING)
}
// If GC profiling is enabled, informs the profiler that we are done
// tracing dependent handles.
void ProfilerEndConditionalWeakTableElementReferences(void* heapId)
{
#if defined (GC_PROFILING)
(&g_profControlBlock)->EndConditionalWeakTableElementReferences(heapId);
#else
UNREFERENCED_PARAMETER(heapId);
#endif // defined (GC_PROFILING)
}
// If GC profiling is enabled, informs the profiler that we are done
// tracing root references.
void ProfilerEndRootReferences2(void* heapId)
{
#if defined (GC_PROFILING)
(&g_profControlBlock)->EndRootReferences2(heapId);
#else
UNREFERENCED_PARAMETER(heapId);
#endif // defined (GC_PROFILING)
}
void GcScanRootsForProfilerAndETW(promote_func* fn, int condemned, int max_gen, ScanContext* sc)
{
Thread* pThread = NULL;
while ((pThread = ThreadStore::GetThreadList(pThread)) != NULL)
{
sc->thread_under_crawl = pThread;
#ifdef FEATURE_EVENT_TRACE
sc->dwEtwRootKind = kEtwGCRootKindStack;
#endif // FEATURE_EVENT_TRACE
ScanStackRoots(pThread, fn, sc);
ScanTailCallArgBufferRoots(pThread, fn, sc);
#ifdef FEATURE_EVENT_TRACE
sc->dwEtwRootKind = kEtwGCRootKindOther;
#endif // FEATURE_EVENT_TRACE
}
}
void ScanHandleForProfilerAndETW(Object** pRef, Object* pSec, uint32_t flags, ScanContext* context, bool isDependent)
{
ProfilingScanContext* pSC = (ProfilingScanContext*)context;
#ifdef GC_PROFILING
// Give the profiler the objectref.
if (pSC->fProfilerPinned)
{
if (!isDependent)
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackGC());
(&g_profControlBlock)->RootReference2(
(uint8_t *)*pRef,
kEtwGCRootKindHandle,
(EtwGCRootFlags)flags,
pRef,
&pSC->pHeapId);
END_PROFILER_CALLBACK();
}
else
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackConditionalWeakTableElements());
(&g_profControlBlock)->ConditionalWeakTableElementReference(
(uint8_t*)*pRef,
(uint8_t*)pSec,
pRef,
&pSC->pHeapId);
END_PROFILER_CALLBACK();
}
}
#endif // GC_PROFILING
#if defined(FEATURE_EVENT_TRACE)
// Notify ETW of the handle
if (ETW::GCLog::ShouldWalkHeapRootsForEtw())
{
ETW::GCLog::RootReference(
pRef,
*pRef, // object being rooted
pSec, // pSecondaryNodeForDependentHandle
isDependent,
pSC,
0, // dwGCFlags,
flags); // ETW handle flags
}
#endif // defined(FEATURE_EVENT_TRACE)
}
// This is called only if we've determined that either:
// a) The Profiling API wants to do a walk of the heap, and it has pinned the
// profiler in place (so it cannot be detached), and it's thus safe to call into the
// profiler, OR
// b) ETW infrastructure wants to do a walk of the heap either to log roots,
// objects, or both.
// This can also be called to do a single walk for BOTH a) and b) simultaneously. Since
// ETW can ask for roots, but not objects
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
void GCProfileWalkHeapWorker(BOOL fProfilerPinned, BOOL fShouldWalkHeapRootsForEtw, BOOL fShouldWalkHeapObjectsForEtw)
{
{
ProfilingScanContext SC(fProfilerPinned);
unsigned max_generation = GCHeapUtilities::GetGCHeap()->GetMaxGeneration();
// **** Scan roots: Only scan roots if profiling API wants them or ETW wants them.
if (fProfilerPinned || fShouldWalkHeapRootsForEtw)
{
GcScanRootsForProfilerAndETW(&ProfScanRootsHelper, max_generation, max_generation, &SC);
SC.dwEtwRootKind = kEtwGCRootKindFinalizer;
GCHeapUtilities::GetGCHeap()->DiagScanFinalizeQueue(&ProfScanRootsHelper, &SC);
// Handles are kept independent of wks/svr/concurrent builds
SC.dwEtwRootKind = kEtwGCRootKindHandle;
GCHeapUtilities::GetGCHeap()->DiagScanHandles(&ScanHandleForProfilerAndETW, max_generation, &SC);
// indicate that regular handle scanning is over, so we can flush the buffered roots
// to the profiler. (This is for profapi only. ETW will flush after the
// entire heap was is complete, via ETW::GCLog::EndHeapDump.)
if (fProfilerPinned)
{
ProfilerEndRootReferences2(&SC.pHeapId);
}
}
// **** Scan dependent handles: only if the profiler supports it or ETW wants roots
if ((fProfilerPinned && ProfilerShouldTrackConditionalWeakTableElements()) ||
fShouldWalkHeapRootsForEtw)
{
// GcScanDependentHandlesForProfiler double-checks
// CORProfilerTrackConditionalWeakTableElements() before calling into the profiler
ProfilingScanContext* pSC = &SC;
// we'll re-use pHeapId (which was either unused (0) or freed by EndRootReferences2
// (-1)), so reset it to NULL
_ASSERTE((*((size_t *)(&pSC->pHeapId)) == (size_t)(-1)) ||
(*((size_t *)(&pSC->pHeapId)) == (size_t)(0)));
pSC->pHeapId = NULL;
GCHeapUtilities::GetGCHeap()->DiagScanDependentHandles(&ScanHandleForProfilerAndETW, max_generation, &SC);
// indicate that dependent handle scanning is over, so we can flush the buffered roots
// to the profiler. (This is for profapi only. ETW will flush after the
// entire heap was is complete, via ETW::GCLog::EndHeapDump.)
if (fProfilerPinned && ProfilerShouldTrackConditionalWeakTableElements())
{
ProfilerEndConditionalWeakTableElementReferences(&SC.pHeapId);
}
}
ProfilerWalkHeapContext profilerWalkHeapContext(fProfilerPinned, SC.pvEtwContext);
// **** Walk objects on heap: only if profiling API wants them or ETW wants them.
if (fProfilerPinned || fShouldWalkHeapObjectsForEtw)
{
GCHeapUtilities::GetGCHeap()->DiagWalkHeap(&HeapWalkHelper, &profilerWalkHeapContext, max_generation, true /* walk the large object heap */);
}
#ifdef FEATURE_EVENT_TRACE
// **** Done! Indicate to ETW helpers that the heap walk is done, so any buffers
// should be flushed into the ETW stream
if (fShouldWalkHeapObjectsForEtw || fShouldWalkHeapRootsForEtw)
{
ETW::GCLog::EndHeapDump(&profilerWalkHeapContext);
}
#endif // FEATURE_EVENT_TRACE
}
}
#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
void GCProfileWalkHeap(bool etwOnly)
{
BOOL fWalkedHeapForProfiler = FALSE;
#ifdef FEATURE_EVENT_TRACE
if (ETW::GCLog::ShouldWalkStaticsAndCOMForEtw())
ETW::GCLog::WalkStaticsAndCOMForETW();
BOOL fShouldWalkHeapRootsForEtw = ETW::GCLog::ShouldWalkHeapRootsForEtw();
BOOL fShouldWalkHeapObjectsForEtw = ETW::GCLog::ShouldWalkHeapObjectsForEtw();
#else // !FEATURE_EVENT_TRACE
BOOL fShouldWalkHeapRootsForEtw = FALSE;
BOOL fShouldWalkHeapObjectsForEtw = FALSE;
#endif // FEATURE_EVENT_TRACE
#if defined (GC_PROFILING)
{
BEGIN_PROFILER_CALLBACK(!etwOnly && CORProfilerTrackGC());
GCProfileWalkHeapWorker(TRUE /* fProfilerPinned */, fShouldWalkHeapRootsForEtw, fShouldWalkHeapObjectsForEtw);
fWalkedHeapForProfiler = TRUE;
END_PROFILER_CALLBACK();
}
#endif // defined (GC_PROFILING)
#if defined (GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
// we need to walk the heap if one of GC_PROFILING or FEATURE_EVENT_TRACE
// is defined, since both of them make use of the walk heap worker.
if (!fWalkedHeapForProfiler &&
(fShouldWalkHeapRootsForEtw || fShouldWalkHeapObjectsForEtw))
{
GCProfileWalkHeapWorker(FALSE /* fProfilerPinned */, fShouldWalkHeapRootsForEtw, fShouldWalkHeapObjectsForEtw);
}
#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
}
void WalkFReachableObjects(bool isCritical, void* objectID)
{
(&g_profControlBlock)->FinalizeableObjectQueued(isCritical, (ObjectID)objectID);
}
static fq_walk_fn g_FQWalkFn = &WalkFReachableObjects;
void GCToEEInterface::DiagGCStart(int gen, bool isInduced)
{
#ifdef GC_PROFILING
DiagUpdateGenerationBounds();
GarbageCollectionStartedCallback(gen, isInduced);
{
BEGIN_PROFILER_CALLBACK(CORProfilerTrackGC());
size_t context = 0;
// When we're walking objects allocated by class, then we don't want to walk the large
// object heap because then it would count things that may have been around for a while.
GCHeapUtilities::GetGCHeap()->DiagWalkHeap(&AllocByClassHelper, (void *)&context, 0, false);
// Notify that we've reached the end of the Gen 0 scan
(&g_profControlBlock)->EndAllocByClass(&context);
END_PROFILER_CALLBACK();
}
#endif // GC_PROFILING
}
void GCToEEInterface::DiagUpdateGenerationBounds()
{
#ifdef GC_PROFILING
if (CORProfilerTrackGC() || CORProfilerTrackBasicGC())
UpdateGenerationBounds();
#endif // GC_PROFILING
}
void GCToEEInterface::DiagGCEnd(size_t index, int gen, int reason, bool fConcurrent)
{
#ifdef GC_PROFILING
// We were only doing generation bounds and GC finish callback for non concurrent GCs so
// I am keeping that behavior to not break profilers. But if BasicGC monitoring is enabled
// we will do these for all GCs.
if (!fConcurrent)
{
GCProfileWalkHeap(false);
}
if (CORProfilerTrackBasicGC() || (!fConcurrent && CORProfilerTrackGC()))
{
DiagUpdateGenerationBounds();
GarbageCollectionFinishedCallback();
}
#endif // GC_PROFILING
}
void GCToEEInterface::DiagWalkFReachableObjects(void* gcContext)
{
#ifdef GC_PROFILING
BEGIN_PROFILER_CALLBACK(CORProfilerTrackGC());
GCHeapUtilities::GetGCHeap()->DiagWalkFinalizeQueue(gcContext, g_FQWalkFn);
END_PROFILER_CALLBACK();
#endif //GC_PROFILING
}
// Note on last parameter: when calling this for bgc, only ETW
// should be sending these events so that existing profapi profilers
// don't get confused.
void WalkMovedReferences(uint8_t* begin, uint8_t* end,
ptrdiff_t reloc,
void* context,
bool fCompacting,
bool fBGC)
{
ETW::GCLog::MovedReference(begin, end,
(fCompacting ? reloc : 0),
(size_t)context,
fCompacting,
!fBGC);
}
void GCToEEInterface::DiagWalkSurvivors(void* gcContext, bool fCompacting)
{
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
if (ShouldTrackSurvivorsForProfilerOrEtw() ||
(fCompacting && ShouldTrackSurvivorsInCompactingGCsForProfiler()))
{
size_t context = 0;
ETW::GCLog::BeginMovedReferences(&context);
GCHeapUtilities::GetGCHeap()->DiagWalkSurvivorsWithType(gcContext, &WalkMovedReferences, (void*)context, walk_for_gc);
ETW::GCLog::EndMovedReferences(context);
}
#endif //GC_PROFILING || FEATURE_EVENT_TRACE
}
void GCToEEInterface::DiagWalkUOHSurvivors(void* gcContext, int gen)
{
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
if (ShouldTrackSurvivorsForProfilerOrEtw())
{
size_t context = 0;
ETW::GCLog::BeginMovedReferences(&context);
GCHeapUtilities::GetGCHeap()->DiagWalkSurvivorsWithType(gcContext, &WalkMovedReferences, (void*)context, walk_for_uoh, gen);
ETW::GCLog::EndMovedReferences(context);
}
#endif //GC_PROFILING || FEATURE_EVENT_TRACE
}
void GCToEEInterface::DiagWalkBGCSurvivors(void* gcContext)
{
#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
if (ShouldTrackSurvivorsForProfilerOrEtw())
{
size_t context = 0;
ETW::GCLog::BeginMovedReferences(&context);
GCHeapUtilities::GetGCHeap()->DiagWalkSurvivorsWithType(gcContext, &WalkMovedReferences, (void*)context, walk_for_bgc);
ETW::GCLog::EndMovedReferences(context);
}
#endif //GC_PROFILING || FEATURE_EVENT_TRACE
}
void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
{
assert(args != nullptr);
int stompWBCompleteActions = SWB_PASS;
bool is_runtime_suspended = args->is_runtime_suspended;
switch (args->operation)
{
case WriteBarrierOp::StompResize:
// StompResize requires a new card table, a new lowest address, and
// a new highest address
assert(args->card_table != nullptr);
assert(args->lowest_address != nullptr);
assert(args->highest_address != nullptr);
// We are sensitive to the order of writes here (more comments on this further in the method)
// In particular g_card_table must be written before writing the heap bounds.
// For platforms with weak memory ordering we will issue fences, for x64/x86 we are ok
// as long as compiler does not reorder these writes.
// That is unlikely since we have method calls in between.
// Just to be robust agains possible refactoring/inlining we will do a compiler-fenced store here.
VolatileStoreWithoutBarrier(&g_card_table, args->card_table);
#ifdef FEATURE_MANUALLY_MANAGED_CARD_BUNDLES
assert(args->card_bundle_table != nullptr);
g_card_bundle_table = args->card_bundle_table;
#endif
#ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
if (g_sw_ww_enabled_for_gc_heap && (args->write_watch_table != nullptr))
{
assert(args->is_runtime_suspended);
g_sw_ww_table = args->write_watch_table;
}
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
stompWBCompleteActions |= ::StompWriteBarrierResize(is_runtime_suspended, args->requires_upper_bounds_check);
is_runtime_suspended = (stompWBCompleteActions & SWB_EE_RESTART) || is_runtime_suspended;
if (stompWBCompleteActions & SWB_ICACHE_FLUSH)
{
// flushing/invalidating the write barrier's body for the current process
// NOTE: the underlying API may flush more than needed or nothing at all if Icache is coherent.
::FlushWriteBarrierInstructionCache();
}
// IMPORTANT: managed heap segments may surround unmanaged/stack segments. In such cases adding another managed
// heap segment may put a stack/unmanaged write inside the new heap range. However the old card table would
// not cover it. Therefore we must ensure that the write barriers see the new table before seeing the new bounds.
//
// On architectures with strong ordering, we only need to prevent compiler reordering.
// Otherwise we put a process-wide fence here (so that we could use an ordinary read in the barrier)
#if defined(HOST_ARM64) || defined(HOST_ARM) || defined(HOST_LOONGARCH64) || defined(HOST_RISCV64)
if (!is_runtime_suspended)
{
// If runtime is not suspended, force all threads to see the changed table before seeing updated heap boundaries.
// See: http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/346765
FlushProcessWriteBuffers();
}
#endif
g_lowest_address = args->lowest_address;
g_highest_address = args->highest_address;
#if defined(HOST_ARM64) || defined(HOST_ARM) || defined(HOST_LOONGARCH64) || defined(HOST_RISCV64)
// Need to reupdate for changes to g_highest_address g_lowest_address
stompWBCompleteActions |= ::StompWriteBarrierResize(is_runtime_suspended, args->requires_upper_bounds_check);
#ifdef HOST_ARM
if (stompWBCompleteActions & SWB_ICACHE_FLUSH)
{
// flushing/invalidating the write barrier's body for the current process
// NOTE: the underlying API may flush more than needed or nothing at all if Icache is coherent.
::FlushWriteBarrierInstructionCache();
}
#endif
#endif
// At this point either the old or the new set of globals (card_table, bounds etc) can be used. Card tables and card bundles allow such use.
// When card tables are de-published (at EE suspension) all the info will be merged, so the information will not be lost.
// Another point - we should not yet have any managed objects/addresses outside of the former bounds, so either old or new bounds are fine.
// That is - because bounds can only become wider and we are not yet done with widening.
//
// However!!
// Once we are done, a new object can (and likely will) be allocated outside of the former bounds.
// So, before such object can be used in a write barier, we must ensure that the barrier also uses the new bounds.
//
// This is easy to arrange for architectures with strong memory ordering. We only need to ensure that
// - object is allocated/published _after_ we publish bounds here
// - write barrier reads bounds after reading the new object locations
//
// for architectures with strong memory ordering (x86/x64) both conditions above are naturally guaranteed.
// Systems with weak ordering are more interesting. We could either:
// a) issue a write fence here and pair it with a read fence in the write barrier, or
// b) issue a process-wide full fence here and do ordinary reads in the barrier.
//
// We will do "b" because executing write barrier is by far more common than updating card table.
//
// I.E. - for weak architectures we have to do a process-wide fence.
//
// NOTE: suspending/resuming EE works the same as process-wide fence for our purposes here.
// (we care only about managed threads and suspend/resume will do full fences - good enough for us).
//
#if defined(HOST_ARM64) || defined(HOST_ARM) || defined(HOST_LOONGARCH64) || defined(HOST_RISCV64)
is_runtime_suspended = (stompWBCompleteActions & SWB_EE_RESTART) || is_runtime_suspended;
if (!is_runtime_suspended)
{
// If runtime is not suspended, force all threads to see the changed state before observing future allocations.
FlushProcessWriteBuffers();
}
#endif
if (stompWBCompleteActions & SWB_EE_RESTART)
{
assert(!args->is_runtime_suspended &&
"if runtime was suspended in patching routines then it was in running state at beginning");
ThreadSuspend::RestartEE(FALSE, TRUE);
}
return; // unlike other branches we have already done cleanup so bailing out here
case WriteBarrierOp::StompEphemeral:
assert(args->is_runtime_suspended && "the runtime must be suspended here!");
// StompEphemeral requires a new ephemeral low and a new ephemeral high