-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCCorProfilerCallback.cpp
More file actions
1434 lines (1099 loc) · 42.5 KB
/
Copy pathCCorProfilerCallback.cpp
File metadata and controls
1434 lines (1099 loc) · 42.5 KB
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
#include "pch.h"
#include "CCorProfilerCallback.h"
#include "CExceptionInfo.h"
#include "CSigReader.h"
#include "Hooks\Hooks.h"
#include <bcrypt.h>
#include <strsafe.h>
//Thread local buffers (to avoid reallocating with each RecordFunction invocation that is made)
thread_local WCHAR g_szMethodName[NAME_BUFFER_SIZE];
thread_local WCHAR g_szTypeName[NAME_BUFFER_SIZE];
thread_local WCHAR g_szModuleName[NAME_BUFFER_SIZE];
thread_local WCHAR g_szAssemblyName[NAME_BUFFER_SIZE];
thread_local WCHAR g_szFieldName[NAME_BUFFER_SIZE];
ULONG g_NextUniqueModuleID = 0;
ULONG g_ThreadSequence = 0;
#pragma region IUnknown
/// <summary>
/// Increments the reference count of this object.
/// </summary>
/// <returns>The incremented reference count.</returns>
ULONG CCorProfilerCallback::AddRef()
{
return InterlockedIncrement(&m_RefCount);
}
/// <summary>
/// Decrements the reference count of this object. When the reference count reaches 0 this object will be deleted.
/// </summary>
/// <returns>The new reference count of this object.</returns>
ULONG CCorProfilerCallback::Release()
{
ULONG refCount = InterlockedDecrement(&m_RefCount);
if (refCount == 0)
delete this;
return refCount;
}
/// <summary>
/// Queries the class factory for a pointer to a specific interface it may implement.
/// </summary>
/// <param name="riid">The identifier of the interface that is being queried for.</param>
/// <param name="ppvObject">A pointer to store a pointer to the interface to, if it is supported.</param>
/// <returns>E_POINTER if ppvObject was null, S_OK if the interface is supported or E_NOINTERFACE if the interface is not supported.</returns>
HRESULT CCorProfilerCallback::QueryInterface(REFIID riid, void** ppvObject)
{
if (ppvObject == nullptr)
return E_POINTER;
if (riid == IID_IUnknown)
*ppvObject = static_cast<IUnknown*>(this);
else if (riid == __uuidof(ICorProfilerCallback))
*ppvObject = static_cast<ICorProfilerCallback*>(this);
else if (riid == __uuidof(ICorProfilerCallback2))
*ppvObject = static_cast<ICorProfilerCallback2*>(this);
else if (riid == __uuidof(ICorProfilerCallback3))
*ppvObject = static_cast<ICorProfilerCallback3*>(this);
else
{
*ppvObject = nullptr;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(*ppvObject)->AddRef();
return S_OK;
}
#pragma endregion
#pragma region ICorProfilerCallback
//We don't utilize AssemblyLoadFinished() or ModuleLoadFinished(); if the module was successfully loaded, we'll process it and its assembly in ModuleAttachedToAssembly()
#pragma region Transition
HRESULT CCorProfilerCallback::UnmanagedToManagedTransition(FunctionID functionId, COR_PRF_TRANSITION_REASON reason)
{
HRESULT hr = S_OK;
EnsureTransitionMethodRecorded(functionId);
if (!g_ExceptionQueue.empty())
{
ULONG oldSequence = g_Sequence;
m_ExceptionManager.UnmanagedToManagedTransition(functionId, reason);
//If LEAVE_FUNCTION was called, an ExceptionFrameUnwindEvent was executed, and both the profiler and the controller know
//that the frame has been left. As such, there's nothing more we need to do here
if (oldSequence != g_Sequence)
goto ErrExit;
}
if (reason == COR_PRF_TRANSITION_CALL)
{
ENTER_FUNCTION(functionId, FrameKind::U2M);
LogCall(L"U2M Call", functionId);
}
else
{
LEAVE_FUNCTION(functionId);
LogCall(L"U2M Return", functionId);
}
if (!g_TracingEnabled)
return hr;
ValidateETW(EventWriteUnmanagedToManagedEvent(functionId, g_Sequence, reason));
ErrExit:
return hr;
}
HRESULT CCorProfilerCallback::ManagedToUnmanagedTransition(FunctionID functionId, COR_PRF_TRANSITION_REASON reason)
{
HRESULT hr = S_OK;
EnsureTransitionMethodRecorded(functionId);
if (!g_ExceptionQueue.empty())
{
ULONG oldSequence = g_Sequence;
m_ExceptionManager.ManagedToUnmanagedTransition(functionId, reason);
//If LEAVE_FUNCTION was called, an ExceptionFrameUnwindEvent was executed, and both the profiler and the controller know
//that the frame has been left. As such, there's nothing more we need to do here
if (oldSequence != g_Sequence)
goto ErrExit;
}
if (reason == COR_PRF_TRANSITION_CALL)
{
ENTER_FUNCTION(functionId, FrameKind::M2U);
LogCall(L"M2U Call", functionId);
}
else
{
LEAVE_FUNCTION(functionId);
LogCall(L"M2U Return", functionId);
}
if (!g_TracingEnabled)
return hr;
ValidateETW(EventWriteManagedToUnmanagedEvent(functionId, g_Sequence, reason));
ErrExit:
return hr;
}
#pragma endregion
#pragma region Load Events
HRESULT CCorProfilerCallback::AssemblyUnloadFinished(AssemblyID assemblyId, HRESULT hrStatus)
{
//This method only executes in detailed profiling mode
if (hrStatus != S_OK)
return S_OK;
CLock assemblyLock(&m_AssemblyMutex, true);
auto match = m_AssemblyInfoMap.find(assemblyId);
if (match != m_AssemblyInfoMap.end())
{
CAssemblyInfo* info = match->second;
m_AssemblyInfoMap.erase(assemblyId);
m_AssemblyNameMap.erase(info->m_pAssemblyName->m_szName);
info->Release();
}
return S_OK;
}
HRESULT CCorProfilerCallback::ModuleUnloadFinished(ModuleID moduleId, HRESULT hrStatus)
{
//This method only executes in detailed profiling mode
if (hrStatus != S_OK)
return S_OK;
CLock moduleLock(&m_ModuleMutex, true);
CLock assemblyLock(&m_AssemblyMutex, true);
auto moduleMatch = m_ModuleInfoMap.find(moduleId);
if (moduleMatch != m_ModuleInfoMap.end())
{
CModuleInfo* info = moduleMatch->second;
auto asmMatch = m_AssemblyInfoMap.find(info->m_AssemblyID);
if (asmMatch != m_AssemblyInfoMap.end())
asmMatch->second->RemoveModule(info);
m_ModuleInfoMap.erase(moduleId);
info->Release();
}
return S_OK;
}
HRESULT CCorProfilerCallback::ModuleAttachedToAssembly(ModuleID moduleId, AssemblyID assemblyId)
{
//This method only executes in detailed profiling mode and the hrStatus passed to ModuleLoadFinished SUCCEEDED()
HRESULT hr = S_OK;
CAssemblyInfo* pAssemblyInfo = nullptr;
CAssemblyName* pAssemblyName = nullptr;
IMetaDataImport2* pMDI = nullptr;
IMetaDataAssemblyImport* pMDAI = nullptr;
mdAssembly mdAssembly;
const void* pbPublicKey = nullptr;
ULONG cbPublicKey;
ULONG chName;
ASSEMBLYMETADATA asmMetaData;
ZeroMemory(&asmMetaData, sizeof(ASSEMBLYMETADATA));
ULONG cbPublicKeyToken = 0;
LPWSTR assemblyName = nullptr;
/* CTypeRefResolver::Resolve will take a (shared) lock on m_ModuleMutex as long as it is executing. During
* its execution, it may also take a lock on m_AssemblyMutex. If we were to lock m_ModuleMutex in the SUCCEEDED() block below,
* the following sequence of events could transpire:
*
* 1. CTypeRefResolver::Resolve locks m_ModuleMutex in shared mode
* 2. ModuleAttachedToAssembly locks m_AssemblyMutex in exclusive mode
* 3. CTypeRefResolver::ResolveAssemblyRef attempts to lock m_AssemblyMutex in shared mode, is blocked by exclusive lock in ModuleAttachedToAssembly
* 4. ModuleAttachedToAssembly attempts to lock m_ModuleMutex, is blocked by shared lock in CTypeRefResolver::Resolve!
*
* We workaround this by acquiring m_ModuleMutex BEFORE m_AssemblyMutex here in ModuleAttachedToAssembly, thus blocking us until CTypeRefResolver::Resolve
* finishes executing
*/
CLock moduleLock(&m_ModuleMutex, true);
CLock assemblyLock(&m_AssemblyMutex, true);
auto asmMatch = m_AssemblyInfoMap.find(assemblyId);
IfFailGo(m_pInfo->GetModuleMetaData(moduleId, ofRead, IID_IMetaDataImport2, (IUnknown**)&pMDI));
if (asmMatch == m_AssemblyInfoMap.end())
{
pAssemblyInfo = nullptr;
IfFailGo(pMDI->QueryInterface(IID_IMetaDataAssemblyImport, (void**)&pMDAI));
IfFailGo(pMDAI->GetAssemblyFromScope(&mdAssembly));
IfFailGo(pMDAI->GetAssemblyProps(
mdAssembly,
&pbPublicKey,
&cbPublicKey,
NULL,
g_szAssemblyName,
NAME_BUFFER_SIZE,
&chName,
&asmMetaData,
NULL
));
IfFailGo(GetAssemblyName(
chName,
asmMetaData,
(const BYTE*)pbPublicKey,
cbPublicKey,
cbPublicKey,
&pAssemblyName
));
}
else
pAssemblyInfo = asmMatch->second;
ErrExit:
if (SUCCEEDED(hr))
{
CModuleInfo* pModuleInfo = new CModuleInfo(assemblyId, moduleId, pMDI);
m_ModuleInfoMap[moduleId] = pModuleInfo;
if (!pAssemblyInfo)
{
pAssemblyInfo = new CAssemblyInfo(
pAssemblyName,
(const BYTE*)pbPublicKey,
cbPublicKey,
pMDAI
);
m_AssemblyInfoMap[assemblyId] = pAssemblyInfo;
m_AssemblyNameMap[pAssemblyInfo->m_pAssemblyName->m_szName] = pAssemblyInfo;
}
pAssemblyInfo->AddModule(pModuleInfo);
IfFailGo(m_pInfo->GetModuleInfo(moduleId, NULL, NAME_BUFFER_SIZE, NULL, g_szModuleName, NULL));
ValidateETW(EventWriteModuleLoadedEvent(pModuleInfo->m_UniqueModuleID, g_szModuleName));
}
else
{
if (assemblyName)
free(assemblyName);
if (pAssemblyName)
delete pAssemblyName;
dprintf(L"ModuleAttachedToAssembly failed with %d\n", hr);
}
if (pMDI)
pMDI->Release();
if (pMDAI)
pMDAI->Release();
return hr;
}
HRESULT CCorProfilerCallback::ClassLoadFinished(ClassID classId, HRESULT hrStatus)
{
//This method only executes in detailed profiling mode
if (hrStatus != S_OK)
return S_OK;
HRESULT hr = S_OK;
//We may have force loaded this type prior to ClassLoadFinished being called; in this case, there's nothing to do
//Lock scope
{
CLock classLock(&m_ClassMutex);
if (m_ClassInfoMap.find(classId) != m_ClassInfoMap.end())
goto ErrExit;
}
IClassInfo* pClassInfo;
IfFailGo(CreateClassInfo(classId, &pClassInfo));
//Lock scope. We need this scope because IfFailGo above will skip initialization of the classLock which we want to
//declare after we've got the class info
{
CLock classLock(&m_ClassMutex, true);
if (pClassInfo->m_InfoType == ClassInfoType::Class)
{
CClassInfo* info = (CClassInfo*)pClassInfo;
if (wcscmp(L"System.__Canon", info->m_szName) == 0)
m_CanonTypes.insert(classId);
if (info->m_NumGenericTypeArgs > 0)
{
BOOL all = TRUE;
for (ULONG i = 0; i < info->m_NumGenericTypeArgs; i++)
{
if (m_CanonTypes.find(info->m_GenericTypeArgs[i]) == m_CanonTypes.end())
{
all = FALSE;
break;
}
}
if (all)
{
info->AddRef();
info->m_IsCanonical = true;
m_CanonicalGenericTypes.insert(info);
}
}
}
AddClassNoLock(pClassInfo);
}
ErrExit:
return hr;
}
HRESULT CCorProfilerCallback::ClassUnloadFinished(ClassID classId, HRESULT hrStatus)
{
//This method only executes in detailed profiling mode
if (hrStatus != S_OK)
return S_OK;
CLock classLock(&m_ClassMutex, true);
auto match = m_ClassInfoMap.find(classId);
if (match != m_ClassInfoMap.end())
{
m_ClassInfoMap.erase(classId);
match->second->Release();
if (match->second->m_InfoType == ClassInfoType::StandardType)
{
CStandardTypeInfo* std = (CStandardTypeInfo*)match->second;
m_StandardTypeMap.erase(std->m_ElementType);
std->Release();
}
if (m_CanonTypes.find(classId) != m_CanonTypes.end())
m_CanonTypes.erase(classId);
if (m_CanonicalGenericTypes.find((CClassInfo*) match->second) != m_CanonicalGenericTypes.end())
{
match->second->Release();
m_CanonicalGenericTypes.erase((CClassInfo*)match->second);
}
}
return S_OK;
}
#pragma endregion
#pragma region Exception Events
HRESULT CCorProfilerCallback::ExceptionThrown(ObjectID thrownObjectId) { return m_ExceptionManager.ExceptionThrown(thrownObjectId); }
//SearchFilter
HRESULT CCorProfilerCallback::ExceptionSearchFilterEnter(FunctionID functionId) { return m_ExceptionManager.SearchFilterEnter(functionId); }
HRESULT CCorProfilerCallback::ExceptionSearchFilterLeave() { return m_ExceptionManager.SearchFilterLeave(); }
//UnwindFunction
HRESULT CCorProfilerCallback::ExceptionUnwindFunctionEnter(FunctionID functionId) { return m_ExceptionManager.UnwindFunctionEnter(functionId); }
HRESULT CCorProfilerCallback::ExceptionUnwindFunctionLeave() { return m_ExceptionManager.UnwindFunctionLeave(); }
//CatcherEnter
HRESULT CCorProfilerCallback::ExceptionCatcherEnter(FunctionID functionId, ObjectID objectId) { return m_ExceptionManager.CatcherEnter(functionId, objectId); }
HRESULT CCorProfilerCallback::ExceptionCatcherLeave() { return m_ExceptionManager.CatcherLeave(); }
//UnwindFinally
HRESULT CCorProfilerCallback::ExceptionUnwindFinallyEnter(FunctionID functionId) { return m_ExceptionManager.UnwindFinallyEnter(functionId); }
HRESULT CCorProfilerCallback::ExceptionUnwindFinallyLeave() { return m_ExceptionManager.UnwindFinallyLeave(); }
#pragma endregion
/// <summary>
/// Initializes the profiler, performing initial setup such as registering our event masks, function mappers and function hooks.
/// </summary>
/// <param name="pICorProfilerInfoUnk">A clr!ProfToEEInterfaceImpl object that should be queried to retrieve an ICorProfilerInfo* interface.</param>
/// <returns>A HRESULT that indicates success or failure. In the event of failure the profiler and its DLL will be unloaded.</returns>
HRESULT CCorProfilerCallback::Initialize(IUnknown* pICorProfilerInfoUnk)
{
if (GetBoolEnv("DEBUGTOOLS_WAITFORDEBUG"))
{
OutputDebugStringW(L"Waiting for debugger to attach...\n");
while (!::IsDebuggerPresent())
::Sleep(100);
}
m_Detailed = GetBoolEnv("DEBUGTOOLS_DETAILED");
g_TracingEnabled = GetBoolEnv("DEBUGTOOLS_TRACESTART");
g_IsETW = !GetBoolEnv("DEBUGTOOLS_SYNCHRONOUS_TRANSFERS");
GetMatchItems(L"DEBUGTOOLS_MODULEBLACKLIST", m_ModuleBlacklist);
GetMatchItems(L"DEBUGTOOLS_MODULEWHITELIST", m_ModuleWhitelist);
GetDefaultBlacklistItems(m_ModuleBlacklist);
HRESULT hr = S_OK;
g_pProfiler = this;
BindLifetimeToParentProcess();
IfFailGo(m_Communication.Initialize());
IfFailGo(pICorProfilerInfoUnk->QueryInterface(&m_pInfo));
IfFailGo(m_pInfo->SetFunctionIDMapper2(RecordFunction, nullptr));
IfFailGo(SetEventMask());
if (m_Detailed)
{
IfFailGo(CValueTracer::Initialize(m_pInfo));
IfFailGo(HRESULT_FROM_NT(BCryptCreateHash(BCRYPT_SHA1_ALG_HANDLE, &m_hHash, NULL, 0, NULL, 0, NULL)));
IfFailGo(InstallHooksWithInfo());
}
else
IfFailGo(InstallHooks());
IfFailWin32Go(EventRegisterDebugToolsProfiler());
ErrExit:
return hr;
}
/// <summary>
/// Notifies the profiler that the application is shutting down.
/// </summary>
/// <returns>A HRESULT that indicates success or failure.</returns>
/// <remarks>This method is not guaranteed to be called. In particular, it may not be called if the application is not purely managed (such as PowerShell, which starts unmanaged
/// and then loads the runtime). When a process such as dnSpy exits, ceemain.cpp!EEShutDown creates a new thread -> clr!EEShutDownProcForSTAThread -> EEShutDownHelper -> EEToProfInterfaceImpl::Shutdown -> ICorProfilerCallback::Shutdown.
/// PowerShell does not call Shutdown when closing out of the program normally, however when the "exit" command is executed, _wmainCRTStartup will call msvcrt!doexit, leading to clr!HandleExitProcessHelper calling EEShutDown, etc.</remarks>
HRESULT CCorProfilerCallback::Shutdown()
{
HRESULT hr = S_OK;
ValidateETW(EventWriteShutdownEvent());
ValidateETW(EventUnregisterDebugToolsProfiler());
return hr;
}
/// <summary>
/// Notifies the profiler that a thread has been created.
/// </summary>
/// <param name="threadId">The managed ID of the thread that was created.</param>
/// <returns>A HRESULT that indicates whether the profiler encountered an error processing the event.</returns>
HRESULT CCorProfilerCallback::ThreadCreated(ThreadID threadId)
{
HRESULT hr = S_OK;
LogThread(L"ThreadCreated " FORMAT_PTR "\n", threadId);
ULONG threadSequence = GetThreadSequence(threadId);
DWORD win32ThreadId;
IfFailGo(m_pInfo->GetThreadInfo(threadId, &win32ThreadId));
ValidateETW(EventWriteThreadCreateEvent(threadSequence, win32ThreadId));
ErrExit:
return hr;
}
/// <summary>
/// Notifies the profiler that a thread has been destroyed.
/// </summary>
/// <param name="threadId">The managed ID of the thread that was destroyed.</param>
/// <returns>A HRESULT that indicates whether the profiler encountered an error processing the event.</returns>
HRESULT CCorProfilerCallback::ThreadDestroyed(ThreadID threadId)
{
HRESULT hr = S_OK;
LogThread(L"ThreadDestroyed " FORMAT_PTR "\n", threadId);
ULONG threadSequence = GetThreadSequence(threadId);
DWORD win32ThreadId;
IfFailGo(m_pInfo->GetThreadInfo(threadId, &win32ThreadId));
ValidateETW(EventWriteThreadDestroyEvent(threadSequence, win32ThreadId));
ErrExit:
return hr;
}
#pragma endregion
#pragma region ICorProfilerCallback2
HRESULT CCorProfilerCallback::ThreadNameChanged(ThreadID threadId, ULONG cchName, WCHAR* name)
{
HRESULT hr = S_OK;
ULONG threadSequence = GetThreadSequence(threadId);
DWORD win32ThreadId;
IfFailGo(m_pInfo->GetThreadInfo(threadId, &win32ThreadId));
WCHAR copy[100];
//MSDN states the name is not guaranteed to be null terminated, so we make a copy just in case
StringCchCopyN(copy, 100, name, cchName);
copy[cchName + 1] = '\0';
LogThread(L"ThreadNameChanged " FORMAT_PTR " -> %s\n", threadId, copy);
ValidateETW(EventWriteThreadNameEvent(threadSequence, copy));
ErrExit:
return hr;
}
#pragma endregion
#pragma region CCorProfilerCallback
CCorProfilerCallback* g_pProfiler;
HANDLE CCorProfilerCallback::g_hExitProcess;
CCorProfilerCallback::~CCorProfilerCallback()
{
for (auto const& kv : m_MethodInfoMap)
kv.second->Release();
for (auto const& kv : m_ClassInfoMap)
kv.second->Release();
for (auto const& kv : m_ModuleInfoMap)
kv.second->Release();
for (auto const& kv : m_AssemblyInfoMap)
kv.second->Release();
for (auto const& kv : m_StandardTypeMap)
kv.second->Release();
for (auto const& item : m_CanonicalGenericTypes)
item->Release();
for (auto const& kv : m_ArrayTypeMap)
delete kv.second;
if (m_pInfo)
m_pInfo->Release();
if (m_hHash)
BCryptDestroyHash(m_hHash);
#if _DEBUG
_ASSERTE(g_ExceptionQueue.empty());
#endif
for (auto const& kv : g_ExceptionQueue)
delete kv;
#if _DEBUG && DEBUG_UNKNOWN
_ASSERTE(g_UnknownMap->size() == 1); //+1 for CSigType Sentinel which is a static member
#endif
}
void CCorProfilerCallback::GetMatchItems(
_In_ LPCWSTR envVar,
_In_ std::vector<CMatchItem>& items)
{
#define MATCH_BUFFER_SIZE 4000
#define READBUFFER do { ptr++; \
if ((ptr - szBuffer) > length) \
return; } while(0)
WCHAR szBuffer[MATCH_BUFFER_SIZE];
int length = GetEnvironmentVariable(envVar, szBuffer, MATCH_BUFFER_SIZE);
if (length == 0 || length >= MATCH_BUFFER_SIZE)
return;
WCHAR* ptr = szBuffer;
while (true)
{
MatchKind matchKind = (MatchKind)*(WCHAR*)ptr;
READBUFFER;
WCHAR* strStart = ptr;
while (*ptr != '\t')
READBUFFER;
*ptr = '\0';
LPWSTR str = _wcsdup(strStart);
items.emplace_back(CMatchItem());
CMatchItem& item = items[items.size() - 1];
item.m_MatchKind = matchKind;
item.m_szValue = str;
READBUFFER;
//Two \t's in a row. It's the last one!
if (*ptr == '\t')
break;
}
}
LPCWSTR blacklistModules[] = {
//.NET Framework
L"mscorlib.dll",
L"System.dll",
L"System.Core.dll",
L"System.Configuration.dll",
L"System.Xml.dll",
L"Microsoft.VisualStudio.Telemetry.dll",
L"Newtonsoft.Json.dll",
L"PresentationFramework.dll",
L"PresentationCore.dll",
L"WindowsBase.dll",
//.NET Core
L"System.Private.CoreLib.dll"
};
LPCWSTR blacklistPaths[] = {
L"dotnet\\shared\\Microsoft.NETCore.App",
L"dotnet\\sdk\\",
#ifdef _DEBUG
L"coreclr\\windows.x64.Debug"
#endif
};
void CCorProfilerCallback::GetDefaultBlacklistItems(
_In_ std::vector<CMatchItem>& items)
{
BOOL value = GetBoolEnv("DEBUGTOOLS_IGNORE_DEFAULT_BLACKLIST");
if (value)
return;
for (LPCWSTR& str : blacklistPaths)
{
items.emplace_back(CMatchItem());
CMatchItem& item = items[items.size() - 1];
item.m_MatchKind = MatchKind::Contains;
item.m_szValue = _wcsdup(str);
}
for (LPCWSTR& str : blacklistModules)
{
items.emplace_back(CMatchItem());
CMatchItem& item = items[items.size() - 1];
item.m_MatchKind = MatchKind::ModuleName;
item.m_szValue = _wcsdup(str);
}
}
/// <summary>
/// A function that is called exactly once for each function that is JITted. Allows the profiler to report on the function,
/// and decide whether the function should be hooked or not.
/// </summary>
/// <param name="funcId">The ID of the function that is being JITted.</param>
/// <param name="clientData">The client data that was passed to ICorProfilerInfo3::SetFunctionIDMapper2()</param>
/// <param name="pbHookFunction">A value that must be set by this function indicating whether the function identified by funcId should be hooked or not.</param>
/// <returns>The original funcId that was passed into this function.</returns>
UINT_PTR __stdcall CCorProfilerCallback::RecordFunction(FunctionID funcId, void* clientData, BOOL* pbHookFunction)
{
HRESULT hr = S_OK;
ICorProfilerInfo4* pInfo = g_pProfiler->m_pInfo;
IMetaDataImport2* pMDI = nullptr;
mdMethodDef methodDef;
mdTypeDef typeDef;
ModuleID moduleId;
ClassID* typeArgs = 0;
PCCOR_SIGNATURE pSigBlob = nullptr;
ULONG cbSigBlob = 0;
CSigMethodDef* method = nullptr;
BOOL methodSaved = FALSE;
*pbHookFunction = FALSE;
//Get the IMetaDataImport and mdMethodDef
IfFailGo(pInfo->GetTokenAndMetaDataFromFunction(funcId, IID_IMetaDataImport, reinterpret_cast<IUnknown**>(&pMDI), &methodDef));
/* Get the ModuleID and any type arguments. Due to the fact reference types will tend to share a single generic type definition,
* in order to get proper typeArg information, we need to have a COR_PRF_FRAME_INFO, which we'll only have during EnterWithInfo().
* While we don't query for generic info here, we'll know if a method is generic thanks to m_NumGenericTypeArgNames. For more info on generics,
* see https://github.com/dotnet/runtime/blob/57bfe474518ab5b7cfe6bf7424a79ce3af9d6657/docs/design/coreclr/profiling/davbr-blog-archive/Generics%20and%20Your%20Profiler.md */
IfFailGo(pInfo->GetFunctionInfo2(
funcId, //[in] funcId
NULL, //[in] frameInfo
NULL, //[out] pClassId
&moduleId, //[out] pModuleId
NULL, //[out] pToken
0, //[in] cTypeArgs
NULL, //[out] pcTypeArgs
NULL //[out] typeArgs
));
//Get the module name
IfFailGo(pInfo->GetModuleInfo(moduleId, NULL, NAME_BUFFER_SIZE, NULL, g_szModuleName, NULL));
if (!ShouldHook())
{
LogShouldHook(L"Not tracing " FORMAT_PTR "\n", funcId);
*pbHookFunction = FALSE;
goto ErrExit;
}
if (g_pProfiler->m_Detailed)
{
//Get the method name, mdTypeDef and sigblob
IfFailGo(pMDI->GetMethodProps(
methodDef,
&typeDef,
g_szMethodName,
NAME_BUFFER_SIZE,
NULL,
NULL,
&pSigBlob,
&cbSigBlob,
NULL,
NULL
));
CSigReader reader(methodDef, pMDI, pSigBlob);
IfFailGo(reader.ParseMethod(g_szMethodName, TRUE, (CSigMethod**)&method));
method->m_ModuleID = moduleId;
//Lock scope
{
CLock methodMutex(&g_pProfiler->m_MethodMutex, true);
g_pProfiler->m_MethodInfoMap[funcId] = method;
g_pProfiler->m_HookedMethodMap.insert(funcId);
methodSaved = TRUE;
}
}
else
{
//Get the method name and mdTypeDef
IfFailGo(pMDI->GetMethodProps(
methodDef,
&typeDef,
g_szMethodName,
NAME_BUFFER_SIZE,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
));
CLock methodMutex(&g_pProfiler->m_MethodMutex, true);
g_pProfiler->m_HookedMethodMap.insert(funcId);
}
//Get the type name
IfFailGo(pMDI->GetTypeDefProps(typeDef, g_szTypeName, NAME_BUFFER_SIZE, NULL, NULL, NULL));
//Write the event
LogShouldHook(L"Tracing %s " FORMAT_PTR "\n", g_szMethodName, funcId);
*pbHookFunction = true;
if (g_pProfiler->m_Detailed)
ValidateETW(EventWriteMethodInfoDetailedEvent(funcId, g_szMethodName, g_szTypeName, g_szModuleName, methodDef));
else
ValidateETW(EventWriteMethodInfoEvent(funcId, g_szMethodName, g_szTypeName, g_szModuleName));
ErrExit:
if (FAILED(hr) && !*pbHookFunction)
{
LogShouldHook(L"Not tracing " FORMAT_PTR " due to HRESULT 0x%X\n", funcId, hr);
}
if (typeArgs && !methodSaved)
free(typeArgs);
if (pMDI)
pMDI->Release();
return funcId;
}
BOOL CCorProfilerCallback::ShouldHook()
{
WCHAR* ptr = wcsrchr(g_szModuleName, '\\');
//Path doesn't contain a slash; assume we should hook it
if (!ptr)
return TRUE;
ptr++;
for(size_t i = 0; i < g_pProfiler->m_ModuleBlacklist.size(); i++)
{
CMatchItem& item = g_pProfiler->m_ModuleBlacklist[i];
if (item.IsMatch(item.m_MatchKind == MatchKind::ModuleName ? ptr : g_szModuleName))
{
if (IsWhitelistedModule(ptr))
return TRUE;
return FALSE;
}
}
return TRUE;
}
BOOL CCorProfilerCallback::IsWhitelistedModule(LPWSTR moduleName)
{
for (size_t i = 0; i < g_pProfiler->m_ModuleWhitelist.size(); i++)
{
CMatchItem& item = g_pProfiler->m_ModuleWhitelist[i];
if (item.IsMatch(item.m_MatchKind == MatchKind::ModuleName ? moduleName : g_szModuleName))
return TRUE;
}
return FALSE;
}
HRESULT CCorProfilerCallback::SetEventMask()
{
DWORD flags =
COR_PRF_MONITOR_ENTERLEAVE | //Inject Enter/Leave/Tailcall hooks during JIT
COR_PRF_MONITOR_EXCEPTIONS | //Leave won't be called when an exception occurs, so we must unwind ourselves
COR_PRF_MONITOR_THREADS | //Record basic thread information
COR_PRF_MONITOR_CODE_TRANSITIONS | //Track code transitions (but only when an exception is active) to detect when an exception is caught in unmanaged code
COR_PRF_DISABLE_ALL_NGEN_IMAGES; //Don't use NGEN images (we need a fresh JIT to be able to inject our Enter/Leave/Tailcall hooks)
//WithInfo hooks won't be called unless advanced event flags are set
if (m_Detailed)
{
flags |= COR_PRF_ENABLE_FUNCTION_ARGS | COR_PRF_ENABLE_FUNCTION_RETVAL | COR_PRF_ENABLE_FRAME_INFO; //Detailed frame info
flags |= COR_PRF_MONITOR_ASSEMBLY_LOADS; //Record assemblies for resolving mdTypeRef -> mdAssemblyRef -> CAssemblyInfo -> CModuleInfo -> ModuleID + mdtypeDef
flags |= COR_PRF_MONITOR_MODULE_LOADS; //Record modules for resolving mdTypeRefs
flags |= COR_PRF_MONITOR_CLASS_LOADS; //Record known classes for looking up their structure when getting their fields values
}
return m_pInfo->SetEventMask(flags);
}
HRESULT CCorProfilerCallback::InstallHooks()
{
return m_pInfo->SetEnterLeaveFunctionHooks3(
(FunctionEnter3*)EnterNaked,
(FunctionLeave3*)LeaveNaked,
(FunctionTailcall3*)TailcallNaked
);
}
HRESULT CCorProfilerCallback::InstallHooksWithInfo()
{
return m_pInfo->SetEnterLeaveFunctionHooks3WithInfo(
(FunctionEnter3WithInfo*)EnterNakedWithInfo,
(FunctionLeave3WithInfo*)LeaveNakedWithInfo,
(FunctionTailcall3WithInfo*)TailcallNakedWithInfo
);
}
HRESULT CCorProfilerCallback::BindLifetimeToParentProcess()
{
#define BUFFER_SIZE 100
HANDLE hParentProcess;
CHAR envBuffer[BUFFER_SIZE];
DWORD parentProcessId;
DWORD actualSize = GetEnvironmentVariableA("DEBUGTOOLS_PARENT_PID", envBuffer, BUFFER_SIZE);
if (actualSize == 0 || actualSize >= BUFFER_SIZE)
goto Exit;
parentProcessId = strtol(envBuffer, NULL, 10);
//The only access right that is mandatory is SYNCHRONIZE; without this
//RegisterWaitForSingleObject will throw an exception
hParentProcess = OpenProcess(SYNCHRONIZE, FALSE, parentProcessId);
if(!RegisterWaitForSingleObject(
&g_hExitProcess,
hParentProcess,
ExitProcessCallback,
NULL,
INFINITE,
WT_EXECUTEONLYONCE
))
{
return HRESULT_FROM_WIN32(GetLastError());
}
Exit:
return S_OK;
}
void CCorProfilerCallback::AddClassNoLock(IClassInfo* pClassInfo)
{
m_ClassInfoMap[pClassInfo->m_ClassID] = pClassInfo;
if (pClassInfo->m_InfoType == ClassInfoType::Class)
{
CClassInfo* info = (CClassInfo*)pClassInfo;
if (m_StandardTypeMap.find(ELEMENT_TYPE_OBJECT) == m_StandardTypeMap.end() && _wcsnicmp(info->m_szName, L"System.Object", sizeof(L"System.Object") / sizeof(WCHAR)) == 0)
{
m_StandardTypeMap[ELEMENT_TYPE_OBJECT] = new CStandardTypeInfo(info->m_ClassID, ELEMENT_TYPE_OBJECT);
}