-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
eventtrace.cpp
5861 lines (5080 loc) · 226 KB
/
eventtrace.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.
//
// File: eventtrace.cpp
// Abstract: This module implements Event Tracing support
//
//
//
// ============================================================================
#include "common.h"
#ifdef FEATURE_NATIVEAOT
#include "commontypes.h"
#include "daccess.h"
#include "debugmacrosext.h"
#include "gcrhenv.h"
#define Win32EventWrite PalEtwEventWrite
#define InterlockedExchange64 PalInterlockedExchange64
#else // !FEATURE_NATIVEAOT
#include "eventtrace.h"
#include "winbase.h"
#include "contract.h"
#include "ex.h"
#include "dbginterface.h"
#include "finalizerthread.h"
#include "clrversion.h"
#include "typestring.h"
#define Win32EventWrite EventWrite
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#include "runtimecallablewrapper.h"
#endif
#endif // FEATURE_NATIVEAOT
#include "eventtracepriv.h"
#ifndef HOST_UNIX
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context = { &MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_EVENTPIPE_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context = { &MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_Context, MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_EVENTPIPE_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_DOTNET_Context = { &MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_Context, MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_EVENTPIPE_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_DOTNET_Context = { &MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_Context, MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_EVENTPIPE_Context };
#else
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context = { MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_EVENTPIPE_Context, &MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_LTTNG_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context = { MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_EVENTPIPE_Context, &MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_LTTNG_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_DOTNET_Context = { MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_EVENTPIPE_Context, &MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_LTTNG_Context };
DOTNET_TRACE_CONTEXT MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_DOTNET_Context = { MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_EVENTPIPE_Context, &MICROSOFT_WINDOWS_DOTNETRUNTIME_STRESS_PROVIDER_LTTNG_Context };
#endif // HOST_UNIX
#ifdef FEATURE_NATIVEAOT
volatile LONGLONG ETW::GCLog::s_l64LastClientSequenceNumber = 0;
#else // FEATURE_NATIVEAOT
Volatile<LONGLONG> ETW::GCLog::s_l64LastClientSequenceNumber = 0;
#endif // FEATURE_NATIVEAOT
#ifndef FEATURE_NATIVEAOT
//---------------------------------------------------------------------------------------
// Helper macros to determine which version of the Method events to use
//
// The V2 versions of these events include the NativeCodeId, the V1 versions do not.
// Historically, when we version events, we'd just stop sending the old version and only
// send the new one. However, now that we have xperf in heavy use internally and soon to be
// used externally, we need to be a bit careful. In particular, we'd like to allow
// current xperf to continue working without knowledge of NativeCodeIds, and allow future
// xperf to decode symbols in ReJITted functions. Thus,
// * During a first-JIT, only issue the existing V1 MethodLoad, etc. events (NOT v0,
// NOT v2). This event does not include a NativeCodeId, and can thus continue to be
// parsed by older decoders.
// * During a rejit, only issue the new V2 events (NOT v0 or v1), which will include a
// nonzero NativeCodeId. Thus, your unique key for a method extent would be MethodID +
// NativeCodeId + extent (hot/cold). These events will be ignored by older decoders
// (including current xperf) because of the version number, but xperf will be
// updated to decode these in the future.
#define FireEtwMethodLoadVerbose_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodLoadVerbose_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID); } \
else \
{ FireEtwMethodLoadVerbose_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodLoad_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodLoad_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, clrInstanceID); } \
else \
{ FireEtwMethodLoad_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulMethodFlags, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodUnloadVerbose_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodUnloadVerbose_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID); } \
else \
{ FireEtwMethodUnloadVerbose_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodUnload_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodUnload_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID); } \
else \
{ FireEtwMethodUnload_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodDCStartVerbose_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodDCStartVerbose_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID); } \
else \
{ FireEtwMethodDCStartVerbose_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodDCStart_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodDCStart_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID); } \
else \
{ FireEtwMethodDCStart_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodDCEndVerbose_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodDCEndVerbose_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID); } \
else \
{ FireEtwMethodDCEndVerbose_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, szDtraceOutput1, szDtraceOutput2, szDtraceOutput3, clrInstanceID, nativeCodeId); } \
}
#define FireEtwMethodDCEnd_V1_or_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId) \
{ \
if (nativeCodeId == 0) \
{ FireEtwMethodDCEnd_V1(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID); } \
else \
{ FireEtwMethodDCEnd_V2(ullMethodIdentifier, ullModuleID, ullMethodStartAddress, ulMethodSize, ulMethodToken, ulColdMethodFlags, clrInstanceID, nativeCodeId); } \
}
// Module load / unload events:
#define FireEtwModuleLoad_V1_or_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath) \
FireEtwModuleLoad_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath)
#define FireEtwModuleUnload_V1_or_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath) \
FireEtwModuleUnload_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath)
#define FireEtwModuleDCStart_V1_or_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath) \
FireEtwModuleDCStart_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath)
#define FireEtwModuleDCEnd_V1_or_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath) \
FireEtwModuleDCEnd_V2(ullModuleId, ullAssemblyId, ulFlags, ulReservedFlags, szDtraceOutput1, szDtraceOutput2, clrInstanceId, ManagedPdbSignature, ManagedPdbAge, ManagedPdbPath, NativePdbSignature, NativePdbAge, NativePdbPath)
//---------------------------------------------------------------------------------------
//
// Rather than checking the NGEN keyword on the runtime provider directly, use this
// helper that checks that the NGEN runtime provider keyword is enabled AND the
// OverrideAndSuppressNGenEvents keyword on the runtime provider is NOT enabled.
//
// OverrideAndSuppressNGenEvents allows controllers to set the expensive NGEN keyword for
// older runtimes (< 4.0) where NGEN PDB info is NOT available, while suppressing those
// expensive events on newer runtimes (>= 4.5) where NGEN PDB info IS available. Note
// that 4.0 has NGEN PDBS but unfortunately not the OverrideAndSuppressNGenEvents
// keyword, b/c NGEN PDBs were made publicly only after 4.0 shipped. So tools that need
// to consume both <4.0 and 4.0 events would need to enable the expensive NGEN events to
// deal properly with 3.5, even though those events aren't necessary on 4.0.
//
// On CoreCLR, this keyword is a no-op, because coregen PDBs don't exist (and thus we'll
// need the NGEN rundown to still work on Silverligth).
//
// Return Value:
// nonzero iff NGenKeyword is enabled on the runtime provider and
// OverrideAndSuppressNGenEventsKeyword is not enabled on the runtime provider.
//
BOOL IsRuntimeNgenKeywordEnabledAndNotSuppressed()
{
LIMITED_METHOD_CONTRACT;
return
(
ETW_TRACING_CATEGORY_ENABLED(
MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
CLR_NGEN_KEYWORD)
&& ! ( ETW_TRACING_CATEGORY_ENABLED(
MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
CLR_OVERRIDEANDSUPPRESSNGENEVENTS_KEYWORD) )
);
}
// Same as above, but for the rundown provider
BOOL IsRundownNgenKeywordEnabledAndNotSuppressed()
{
LIMITED_METHOD_CONTRACT;
return
#ifdef FEATURE_PERFTRACING
EventPipeHelper::Enabled() ||
#endif // FEATURE_PERFTRACING
(
ETW_TRACING_CATEGORY_ENABLED(
MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
CLR_RUNDOWNNGEN_KEYWORD)
&& ! ( ETW_TRACING_CATEGORY_ENABLED(
MICROSOFT_WINDOWS_DOTNETRUNTIME_RUNDOWN_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
CLR_RUNDOWNOVERRIDEANDSUPPRESSNGENEVENTS_KEYWORD) )
);
}
/*******************************************************/
/* Fast assembly function to get the topmost EBP frame */
/*******************************************************/
#if defined(TARGET_X86)
extern "C"
{
CallStackFrame* GetEbp()
{
CallStackFrame *frame=NULL;
#ifdef TARGET_WINDOWS
__asm
{
mov frame, ebp
}
#else
frame = (CallStackFrame*)__builtin_frame_address(0);
#endif
return frame;
}
}
#endif //TARGET_X86
/*************************************/
/* Function to append a frame to an existing stack */
/*************************************/
#if !defined(HOST_UNIX)
void ETW::SamplingLog::Append(SIZE_T currentFrame)
{
LIMITED_METHOD_CONTRACT;
if(m_FrameCount < (ETW::SamplingLog::s_MaxStackSize-1) &&
currentFrame != 0)
{
m_EBPStack[m_FrameCount] = currentFrame;
m_FrameCount++;
}
};
/********************************************************/
/* Function to get the callstack on the current thread */
/********************************************************/
ETW::SamplingLog::EtwStackWalkStatus ETW::SamplingLog::GetCurrentThreadsCallStack(UINT32 *frameCount, PVOID **Stack)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
m_FrameCount = 0;
ETW::SamplingLog::EtwStackWalkStatus stackwalkStatus = SaveCurrentStack();
_ASSERTE(m_FrameCount < ETW::SamplingLog::s_MaxStackSize);
// this not really needed, but let's do it
// because we use the framecount while dumping the stack event
for(int i=m_FrameCount; i<ETW::SamplingLog::s_MaxStackSize; i++)
{
m_EBPStack[i] = 0;
}
// This is for consumers to work correctly because the number of
// frames in the manifest file is specified to be 2
if(m_FrameCount < 2)
m_FrameCount = 2;
*frameCount = m_FrameCount;
*Stack = (PVOID *)m_EBPStack;
return stackwalkStatus;
};
/*************************************/
/* Function to save the stack on the current thread */
/*************************************/
ETW::SamplingLog::EtwStackWalkStatus ETW::SamplingLog::SaveCurrentStack(int skipTopNFrames)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!IsGarbageCollectorFullyInitialized())
{
// If the GC isn't ready yet, then there won't be any interesting
// managed code on the stack to walk. Plus, the stack walk itself may
// hit problems (e.g., when calling into the code manager) if it's run
// too early during startup.
return ETW::SamplingLog::UnInitialized;
}
#ifndef DACCESS_COMPILE
#ifdef TARGET_AMD64
if (RtlVirtualUnwind_Unsafe == NULL)
{
// We haven't even set up the RtlVirtualUnwind function pointer yet,
// so it's too early to try stack walking.
return ETW::SamplingLog::UnInitialized;
}
#endif // TARGET_AMD64
Thread *pThread = GetThreadNULLOk();
if (pThread == NULL)
{
return ETW::SamplingLog::UnInitialized;
}
// The thread should not have a hijack set up or we can't walk the stack.
if (pThread->m_State & Thread::TS_Hijacked) {
return ETW::SamplingLog::UnInitialized;
}
if (pThread->IsEtwStackWalkInProgress())
{
return ETW::SamplingLog::InProgress;
}
pThread->MarkEtwStackWalkInProgress();
EX_TRY
{
#ifdef TARGET_X86
CallStackFrame *currentEBP = GetEbp();
CallStackFrame *lastEBP = NULL;
// The EBP stack walk below is meant to be extremely fast. It does not attempt to protect
// against cases of stack corruption. *BUT* it does need to validate a "sane" EBP chain.
// Ensure the EBP in the starting frame is "reasonable" (i.e. above the address of a local)
if ((SIZE_T) currentEBP > (SIZE_T)¤tEBP)
{
while(currentEBP)
{
lastEBP = currentEBP;
currentEBP = currentEBP->m_Next;
// Check for stack upper limit; we don't check the lower limit on each iteration
// (we did it at the top) and each subsequent value in the loop is larger than
// the previous (see the check "currentEBP < lastEBP" below)
if((SIZE_T)currentEBP > (SIZE_T)Thread::GetStackUpperBound())
{
break;
}
// If we have a too small address, we are probably bad
if((SIZE_T)currentEBP < (SIZE_T)0x10000)
break;
if((SIZE_T)currentEBP < (SIZE_T)lastEBP)
{
break;
}
// Skip the top N frames
if(skipTopNFrames) {
skipTopNFrames--;
continue;
}
// Save the Return Address for symbol decoding
Append(lastEBP->m_ReturnAddress);
}
}
#else
CONTEXT ctx;
ClrCaptureContext(&ctx);
UINT_PTR ControlPc = 0;
UINT_PTR CurrentSP = 0, PrevSP = 0;
while(1)
{
// Unwind to the caller
ControlPc = Thread::VirtualUnwindCallFrame(&ctx);
// This is to take care of recursion
CurrentSP = (UINT_PTR)GetSP(&ctx);
// when to break from this loop
if ( ControlPc == 0 || ( PrevSP == CurrentSP ) )
{
break;
}
// Skip the top N frames
if ( skipTopNFrames ) {
skipTopNFrames--;
continue;
}
// Add the stack frame to the list
Append(ControlPc);
PrevSP = CurrentSP;
}
#endif //TARGET_X86
} EX_CATCH { } EX_END_CATCH(SwallowAllExceptions);
pThread->MarkEtwStackWalkCompleted();
#endif //!DACCESS_COMPILE
return ETW::SamplingLog::Completed;
}
#endif // !defined(HOST_UNIX)
#endif // !FEATURE_NATIVEAOT
/****************************************************************************/
/* Methods that are called from the runtime */
/****************************************************************************/
/****************************************************************************/
/* Methods for rundown events */
/****************************************************************************/
/***************************************************************************/
/* This function should be called from the event tracing callback routine
when the private CLR provider is enabled */
/***************************************************************************/
#ifndef FEATURE_NATIVEAOT
VOID ETW::GCLog::GCSettingsEvent()
{
if (GCHeapUtilities::IsGCHeapInitialized())
{
if (ETW_TRACING_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context,
GCSettings))
{
ETW::GCLog::ETW_GC_INFO Info;
Info.GCSettings.ServerGC = GCHeapUtilities::IsServerHeap ();
Info.GCSettings.SegmentSize = GCHeapUtilities::GetGCHeap()->GetValidSegmentSize (false);
Info.GCSettings.LargeObjectSegmentSize = GCHeapUtilities::GetGCHeap()->GetValidSegmentSize (true);
FireEtwGCSettings_V1(Info.GCSettings.SegmentSize, Info.GCSettings.LargeObjectSegmentSize, Info.GCSettings.ServerGC, GetClrInstanceId());
}
GCHeapUtilities::GetGCHeap()->DiagTraceGCSegments();
}
};
#endif // !FEATURE_NATIVEAOT
//---------------------------------------------------------------------------------------
//
// Helper to fire the GCStart event. Figures out which version of GCStart to fire, and
// includes the client sequence number, if available.
//
// Arguments:
// pGcInfo - ETW_GC_INFO containing details from GC about this collection
//
// static
VOID ETW::GCLog::FireGcStart(ETW_GC_INFO * pGcInfo)
{
LIMITED_METHOD_CONTRACT;
if (ETW_TRACING_CATEGORY_ENABLED(
MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_INFORMATION,
CLR_GC_KEYWORD))
{
// If the controller specified a client sequence number for us to log with this
// GCStart, then retrieve it
LONGLONG l64ClientSequenceNumberToLog = 0;
if ((s_l64LastClientSequenceNumber != 0) &&
(pGcInfo->GCStart.Depth == GCHeapUtilities::GetGCHeap()->GetMaxGeneration()) &&
(pGcInfo->GCStart.Reason == ETW_GC_INFO::GC_INDUCED))
{
l64ClientSequenceNumberToLog = InterlockedExchange64(&s_l64LastClientSequenceNumber, 0);
}
FireEtwGCStart_V2(pGcInfo->GCStart.Count, pGcInfo->GCStart.Depth, pGcInfo->GCStart.Reason, pGcInfo->GCStart.Type, GetClrInstanceId(), l64ClientSequenceNumberToLog);
}
}
//---------------------------------------------------------------------------------------
//
// Helper to send public finalize object & type events, and private finalize object
// event. If Type events are enabled, this will send the Type event for the finalized
// objects. It will not be batched with other types (except type parameters, if any),
// and will not check if the Type has already been logged (may thus result in dupe
// logging of the Type).
//
// Arguments:
// pMT - MT of object getting finalized
// pObj - object getting finalized
//
// static
VOID ETW::GCLog::SendFinalizeObjectEvent(MethodTable * pMT, Object * pObj)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
// LogTypeAndParameters locks, and we take our own lock if typeLogBehavior says to
CAN_TAKE_LOCK;
}
CONTRACTL_END;
// Send public finalize object event, if it's enabled
if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, FinalizeObject))
{
FireEtwFinalizeObject(pMT, pObj, GetClrInstanceId());
// This function checks if type events are enabled; if so, it sends event for
// finalized object's type (and parameter types, if any)
ETW::TypeSystemLog::LogTypeAndParametersIfNecessary(
NULL, // Not batching this type with others
(TADDR) pMT,
// Don't spend the time entering the lock and checking the hash table to see
// if we've already logged the type; just log it (if type events are enabled).
ETW::TypeSystemLog::kTypeLogBehaviorAlwaysLog
);
}
// Send private finalize object event, if it's enabled
if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context, PrvFinalizeObject))
{
EX_TRY
{
DefineFullyQualifiedNameForClassWOnStack();
FireEtwPrvFinalizeObject(pMT, pObj, GetClrInstanceId(), GetFullyQualifiedNameForClassNestedAwareW(pMT));
}
EX_CATCH
{
}
EX_END_CATCH(RethrowTerminalExceptions);
}
}
DWORD ETW::ThreadLog::GetEtwThreadFlags(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
DWORD dwEtwThreadFlags = 0;
if (pThread->IsThreadPoolThread())
{
dwEtwThreadFlags |= kEtwThreadFlagThreadPoolWorker;
}
if (pThread->IsGCSpecial())
{
dwEtwThreadFlags |= kEtwThreadFlagGCSpecial;
}
if (IsGarbageCollectorFullyInitialized() &&
(pThread == FinalizerThread::GetFinalizerThread()))
{
dwEtwThreadFlags |= kEtwThreadFlagFinalizer;
}
return dwEtwThreadFlags;
}
VOID ETW::ThreadLog::FireThreadCreated(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
FireEtwThreadCreated(
(ULONGLONG)pThread,
(ULONGLONG)AppDomain::GetCurrentDomain(),
GetEtwThreadFlags(pThread),
pThread->GetThreadId(),
pThread->GetOSThreadId(),
GetClrInstanceId());
}
VOID ETW::ThreadLog::FireThreadDC(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
FireEtwThreadDC(
(ULONGLONG)pThread,
(ULONGLONG)AppDomain::GetCurrentDomain(),
GetEtwThreadFlags(pThread),
pThread->GetThreadId(),
pThread->GetOSThreadId(),
GetClrInstanceId());
}
#ifndef FEATURE_NATIVEAOT
// TypeSystemLog implementation
//
// We keep track of which TypeHandles have been logged, and stats on instances of these
// TypeHandles that have been allocated, by a hash table of hash tables. The outer hash
// table maps Module*'s to an inner hash table that contains all the TypeLoggingInfos for that
// Module*. Arranging things this way makes it easy to deal with Module unloads, as we
// can simply remove the corresponding inner hash table from the outer hash table.
// The following help define the "inner" hash table: a hash table of TypeLoggingInfos
// from a particular Module (key = TypeHandle, value = TypeLoggingInfo.
class LoggedTypesFromModuleTraits : public NoRemoveSHashTraits< DefaultSHashTraits<ETW::TypeLoggingInfo> >
{
public:
// explicitly declare local typedefs for these traits types, otherwise
// the compiler may get confused
typedef NoRemoveSHashTraits< DefaultSHashTraits<ETW::TypeLoggingInfo> > PARENT;
typedef PARENT::element_t element_t;
typedef PARENT::count_t count_t;
typedef TypeHandle key_t;
static key_t GetKey(const element_t &e)
{
LIMITED_METHOD_CONTRACT;
return e.th;
}
static BOOL Equals(key_t k1, key_t k2)
{
LIMITED_METHOD_CONTRACT;
return (k1 == k2);
}
static count_t Hash(key_t k)
{
LIMITED_METHOD_CONTRACT;
return (count_t) k.AsTAddr();
}
static bool IsNull(const element_t &e)
{
LIMITED_METHOD_CONTRACT;
return (e.th.AsTAddr() == 0);
}
static const element_t Null()
{
LIMITED_METHOD_CONTRACT;
return ETW::TypeLoggingInfo(NULL);
}
};
typedef SHash<LoggedTypesFromModuleTraits> LoggedTypesFromModuleHash;
// The inner hash table is housed inside this class, which acts as an entry in the outer
// hash table.
class ETW::LoggedTypesFromModule
{
public:
Module * pModule;
LoggedTypesFromModuleHash loggedTypesFromModuleHash;
// These are used by the outer hash table (mapping Module*'s to instances of
// LoggedTypesFromModule).
static COUNT_T Hash(Module * pModule)
{
LIMITED_METHOD_CONTRACT;
return (COUNT_T) (SIZE_T) pModule;
}
Module * GetKey()
{
LIMITED_METHOD_CONTRACT;
return pModule;
}
LoggedTypesFromModule(Module * pModuleParam) : loggedTypesFromModuleHash()
{
LIMITED_METHOD_CONTRACT;
pModule = pModuleParam;
}
~LoggedTypesFromModule()
{
LIMITED_METHOD_CONTRACT;
}
};
// The following define the outer hash table (mapping Module*'s to instances of
// LoggedTypesFromModule).
class AllLoggedTypesTraits : public DefaultSHashTraits<ETW::LoggedTypesFromModule *>
{
public:
// explicitly declare local typedefs for these traits types, otherwise
// the compiler may get confused
typedef DefaultSHashTraits<ETW::LoggedTypesFromModule *> PARENT;
typedef PARENT::element_t element_t;
typedef PARENT::count_t count_t;
typedef Module * key_t;
static key_t GetKey(const element_t &e)
{
LIMITED_METHOD_CONTRACT;
return e->pModule;
}
static BOOL Equals(key_t k1, key_t k2)
{
LIMITED_METHOD_CONTRACT;
return (k1 == k2);
}
static count_t Hash(key_t k)
{
LIMITED_METHOD_CONTRACT;
return (count_t) (size_t) k;
}
static bool IsNull(const element_t &e)
{
LIMITED_METHOD_CONTRACT;
return (e == NULL);
}
static element_t Null()
{
LIMITED_METHOD_CONTRACT;
return NULL;
}
};
typedef SHash<AllLoggedTypesTraits> AllLoggedTypesHash;
// The outer hash table (mapping Module*'s to instances of LoggedTypesFromModule) is
// housed in this struct, which is dynamically allocated the first time we decide we need
// it.
struct AllLoggedTypes
{
public:
// This Crst protects the entire outer & inner hash tables. On a GC heap walk, it
// is entered once for the duration of the walk, so that we can freely access the
// hash tables during the walk. On each object allocation, this Crst must be
// entered individually each time.
static CrstStatic s_cs;
// A thread local copy of the global epoch.
// This value is used by each thread to ensure that the thread local data structures
// are in sync with the global state.
unsigned int nEpoch;
// The outer hash table (mapping Module*'s to instances of LoggedTypesFromModule)
AllLoggedTypesHash allLoggedTypesHash;
};
CrstStatic AllLoggedTypes::s_cs;
AllLoggedTypes * ETW::TypeSystemLog::s_pAllLoggedTypes = NULL;
unsigned int ETW::TypeSystemLog::s_nEpoch = 0;
BOOL ETW::TypeSystemLog::s_fHeapAllocEventEnabledOnStartup = FALSE;
BOOL ETW::TypeSystemLog::s_fHeapAllocHighEventEnabledNow = FALSE;
BOOL ETW::TypeSystemLog::s_fHeapAllocLowEventEnabledNow = FALSE;
int ETW::TypeSystemLog::s_nCustomMsBetweenEvents = 0;
//---------------------------------------------------------------------------------------
//
// Initializes TypeSystemLog (specifically its crst). Called just before ETW providers
// are registered with the OS
//
// Return Value:
// HRESULT indicating success or failure
//
// static
HRESULT ETW::TypeSystemLog::PreRegistrationInit()
{
LIMITED_METHOD_CONTRACT;
if (!AllLoggedTypes::s_cs.InitNoThrow(
CrstEtwTypeLogHash,
CRST_UNSAFE_ANYMODE)) // This lock is taken during a GC while walking the heap
{
return E_FAIL;
}
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Initializes TypeSystemLog (specifically its crst). Called just after ETW providers
// are registered with the OS
//
// Return Value:
// HRESULT indicating success or failure
//
// static
void ETW::TypeSystemLog::PostRegistrationInit()
{
LIMITED_METHOD_CONTRACT;
// Initialize our "current state" BOOLs that remember if low or high allocation
// sampling is turned on
s_fHeapAllocLowEventEnabledNow = ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_GCHEAPALLOCLOW_KEYWORD);
s_fHeapAllocHighEventEnabledNow = ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_GCHEAPALLOCHIGH_KEYWORD);
// Snapshot the current state of the object allocated keyword (on startup), and rely
// on this snapshot for the rest of the process run. Since these events require the
// slow alloc JIT helper to be enabled, and that can only be done on startup, we
// remember in this BOOL that we did so, so that we can prevent the object allocated
// event from being fired if the fast allocation helper were enabled but had to
// degrade down to the slow helper (e.g., thread ran over its allocation limit). This
// keeps things consistent.
s_fHeapAllocEventEnabledOnStartup = (s_fHeapAllocLowEventEnabledNow || s_fHeapAllocHighEventEnabledNow);
if (s_fHeapAllocEventEnabledOnStartup)
{
// Determine if a COMPLUS env var is overriding the frequency for the sampled
// object allocated events
// Config value intentionally typed as string, b/c DWORD interpretation is hard-coded
// to hex, which is not what the user would expect. This way I can force the
// conversion to use decimal.
NewArrayHolder<WCHAR> wszCustomObjectAllocationEventsPerTypePerSec(NULL);
if (FAILED(CLRConfig::GetConfigValue(
CLRConfig::UNSUPPORTED_ETW_ObjectAllocationEventsPerTypePerSec,
&wszCustomObjectAllocationEventsPerTypePerSec)) ||
(wszCustomObjectAllocationEventsPerTypePerSec == NULL))
{
return;
}
LPWSTR endPtr;
DWORD dwCustomObjectAllocationEventsPerTypePerSec = u16_strtoul(
wszCustomObjectAllocationEventsPerTypePerSec,
&endPtr,
10 // Base 10 conversion
);
if (dwCustomObjectAllocationEventsPerTypePerSec == UINT32_MAX)
dwCustomObjectAllocationEventsPerTypePerSec = 0;
if (dwCustomObjectAllocationEventsPerTypePerSec != 0)
{
// MsBetweenEvents = (1000 ms/sec) / (custom desired events/sec)
s_nCustomMsBetweenEvents = 1000 / dwCustomObjectAllocationEventsPerTypePerSec;
}
}
}
//---------------------------------------------------------------------------------------
//
// Update object allocation sampling frequency and / or Type hash table contents based
// on what keywords were changed.
//
// static
void ETW::TypeSystemLog::OnKeywordsChanged()
{
LIMITED_METHOD_CONTRACT;
// If the desired frequency for the GCSampledObjectAllocation events has changed,
// update our state.
s_fHeapAllocLowEventEnabledNow = ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_GCHEAPALLOCLOW_KEYWORD);
s_fHeapAllocHighEventEnabledNow = ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_GCHEAPALLOCHIGH_KEYWORD);
// FUTURE: Would be nice here to log an error event if (s_fHeapAllocLowEventEnabledNow ||
// s_fHeapAllocHighEventEnabledNow), but !s_fHeapAllocEventEnabledOnStartup
// If the type events should be turned off, eliminate the hash tables that tracked
// which types were logged. (If type events are turned back on later, we'll re-log
// them all as we encounter them.) Note that all we can really test for is that the
// Types keyword on the runtime provider is off. Not necessarily that it was on and
// was just turned off with this request. But either way, TypeSystemLog can handle it
// because it is extremely smart.
if (!ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_TYPE_KEYWORD))
OnTypesKeywordTurnedOff();
}
//---------------------------------------------------------------------------------------
//
// Based on keywords alone, determine the what the default sampling rate should be for
// object allocation events. (This function does not consider any COMPLUS overrides for
// the sampling rate.)
//
// static
int ETW::TypeSystemLog::GetDefaultMsBetweenEvents()
{
LIMITED_METHOD_CONTRACT;
// We should only get here if the allocation event is enabled. In spirit, this assert
// is correct, but a race could cause the assert to fire (if someone toggled the
// event off after we decided that the event was on and we started down the path of
// calculating statistics to fire the event). In such a case we'll end up returning
// k_nDefaultMsBetweenEventsLow below, but next time we won't get here as we'll know
// early enough not to fire the event.
//_ASSERTE(IsHeapAllocEventEnabled());
// MsBetweenEvents = (1000 ms/sec) / (desired events/sec)
const int k_nDefaultMsBetweenEventsHigh = 1000 / 100; // 100 events per type per sec
const int k_nDefaultMsBetweenEventsLow = 1000 / 5; // 5 events per type per sec
// If both are set, High takes precedence
if (s_fHeapAllocHighEventEnabledNow)
{
return k_nDefaultMsBetweenEventsHigh;
}
return k_nDefaultMsBetweenEventsLow;
}
//---------------------------------------------------------------------------------------
//
// Use this to decide whether to fire the object allocation event
//
// Return Value:
// nonzero iff we should fire the event.
//
// static
BOOL ETW::TypeSystemLog::IsHeapAllocEventEnabled()
{
LIMITED_METHOD_CONTRACT;
return
// Only fire the event if it was enabled at startup (and thus the slow-JIT new
// helper is used in all cases)
s_fHeapAllocEventEnabledOnStartup &&
// AND a keyword is still enabled. (Thus people can turn off the event
// whenever they want; but they cannot turn it on unless it was also on at startup.)
(s_fHeapAllocHighEventEnabledNow || s_fHeapAllocLowEventEnabledNow);
}
//---------------------------------------------------------------------------------------
//
// Helper that adds (or updates) the TypeLoggingInfo inside the inner hash table passed
// in.
//
// Arguments:
// * pLoggedTypesFromModule - Inner hash table to update
// * pTypeLoggingInfo - TypeLoggingInfo to store
//
// Return Value:
// nonzero iff the add/replace was successful.
//
// static
BOOL ETW::TypeSystemLog::AddOrReplaceTypeLoggingInfo(ETW::LoggedTypesFromModule * pLoggedTypesFromModule, const ETW::TypeLoggingInfo * pTypeLoggingInfo)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pLoggedTypesFromModule != NULL);
BOOL fSucceeded = FALSE;
EX_TRY
{
pLoggedTypesFromModule->loggedTypesFromModuleHash.AddOrReplace(*pTypeLoggingInfo);
fSucceeded = TRUE;
}
EX_CATCH
{
fSucceeded = FALSE;
}
EX_END_CATCH(RethrowTerminalExceptions);
return fSucceeded;
}
//---------------------------------------------------------------------------------------
//
// Records stats about the object's allocation, and determines based on those stats whether
// to fires the high / low frequency GCSampledObjectAllocation ETW event
//
// Arguments:
// * pObject - Allocated object to log
// * th - TypeHandle for the object
//
// static
void ETW::TypeSystemLog::SendObjectAllocatedEvent(Object * pObject)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// No-op if the appropriate keywords were not enabled on startup (or we're not yet