forked from microsoft/CLRInstrumentationEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProfilerManager.cpp
4064 lines (3062 loc) · 123 KB
/
ProfilerManager.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "stdafx.h"
#include "ProfilerManager.h"
#include "ProfilerManagerForInstrumentationMethod.h"
#include "MethodJitInfo.h"
#include "CorProfilerInfoWrapper.h"
#include "AssemblyInfo.h"
#include "CorProfilerFunctionControlWrapper.h"
#include "SignatureBuilder.h"
#include "TypeCreator.h"
#include "MethodInfoCleanup.h"
#include "InstrumentationMethod.h"
#include "ConfigurationLoader.h"
#include "InstrumentationMethodEvents.h"
#include "LoggingWrapper.h"
#include "ConfigurationLocator.h"
#ifndef PLATFORM_UNIX
#include "RawProfilerHookLoader.h"
#include "RawProfilerHookSettingsReader.h"
#include "../Common.Lib/PathUtils.h"
#endif
#include "../InstrumentationEngine.Lib/Encoding.h"
#include <algorithm>
#include <XmlDocWrapper.h>
using namespace ATL;
CProfilerManager::CProfilerManager() :
m_bProfilingDisabled(false),
m_dwEventMask(GetDefaultEventMask()),
m_dwEventMaskHigh(0),
m_attachedClrVersion(ClrVersion_Unknown),
m_runtimeType((COR_PRF_RUNTIME_TYPE)0),
m_bIsInInitialize(false),
m_bIsInitializingInstrumentationMethod(false),
m_dwInstrumentationMethodFlags(0),
m_bValidateCodeSignature(true),
m_bAttach(false)
{
#ifdef PLATFORM_UNIX
PAL_Initialize(0, NULL);
#endif
WCHAR wszEnvVar[MAX_PATH];
#ifndef PLATFORM_UNIX
GetEnvironmentVariable(_T("MicrosoftInstrumentationEngine_MessageboxAtAttach"), wszEnvVar, MAX_PATH);
if (wcscmp(wszEnvVar, _T("1")) == 0)
{
tstringstream mboxStream;
DWORD pid = GetCurrentProcessId();
mboxStream << _T("MicrosoftInstrumentationEngine ProfilerAttach. PID: ") << pid;
MessageBoxW(NULL, mboxStream.str().c_str(), L"", MB_OK);
}
if (GetEnvironmentVariable(_T("MicrosoftInstrumentationEngine_DebugWait"), wszEnvVar, MAX_PATH) > 0)
{
while (!IsDebuggerPresent())
{
Sleep(100);
}
}
#endif
CLogging::Initialize();
#ifndef PLATFORM_UNIX
//
// Set this environment variable for testing purposes only.
// Setting it will allow untrusted instrumentation methods to be loaded
//
// We consider this variable as secure as COR_ENABLE_PROFILER because we read it very early in process lifetime so malicious code
// inside the process cannot modify it. Make sure you do not move this initialization logic and do not make it lazily initialized
//
if (GetEnvironmentVariable(_T("MicrosoftInstrumentationEngine_DisableCodeSignatureValidation"), nullptr, 0) > 0)
{
m_bValidateCodeSignature = false;
}
#else
m_bValidateCodeSignature = false;
#endif
InitializeCriticalSection(&m_csForJIT);
InitializeCriticalSection(&m_cs);
InitializeCriticalSection(&m_csForAppDomains);
// the PAL's implementation of COM does not invoke finalconstruct.
#ifdef PLATFORM_UNIX
FinalConstruct();
#endif
}
CProfilerManager::~CProfilerManager()
{
DeleteCriticalSection(&m_cs);
CLogging::Shutdown();
}
HRESULT CProfilerManager::FinalConstruct()
{
HRESULT hr = S_OK;
#ifndef PLATFORM_UNIX
// This object aggregates the free threaded marshaler which ensures all cross apartment calls to this object
// do not marshal off the calling thead. In all likelihood, this shouldn't be a problem as I don't expect
// any STA or MTA objects to get a hold of this. However, for correctness sake, I am doing this.
ATL::CComPtr<IUnknown> pUnkMarshal;
IfFailRet(CoCreateFreeThreadedMarshaler((IUnknown*)(ATL::CComObjectRootEx<ATL::CComMultiThreadModel>*)(this), (IUnknown**)&m_pFTM));
#endif
m_pAppDomainCollection.Attach(new CAppDomainCollection(this));
if (m_pAppDomainCollection == NULL)
{
return E_OUTOFMEMORY;
}
return hr;
}
void CProfilerManager::FinalRelease()
{
}
HRESULT CProfilerManager::SetupProfilingEnvironment(_In_reads_(numConfigPaths) BSTR rgConfigPaths[], _In_ UINT numConfigPaths)
{
IfNullRetPointer(rgConfigPaths);
HRESULT hr = S_OK;
vector<CComPtr<CConfigurationSource>> configSources;
for (UINT i = 0; i < numConfigPaths; i++)
{
CComPtr<CConfigurationSource> pConfigSource;
pConfigSource.Attach(new (nothrow) CConfigurationSource(rgConfigPaths[i]));
IfFalseRet(nullptr != pConfigSource, E_OUTOFMEMORY);
configSources.push_back(pConfigSource.p);
}
m_configSources = configSources;
return InvokeThreadRoutine(InstrumentationMethodThreadProc);
}
HRESULT CProfilerManager::InvokeThreadRoutine(_In_ LPTHREAD_START_ROUTINE threadRoutine)
{
HRESULT hr = S_OK;
// The CLR doesn't initialize com before calling the profiler, and the profiler manager cannot do so itself
// as that would screw up the com state for the application thread. This thread allows the profiler manager
// to co create a free threaded version of msxml on a thread that it owns to avoid this.
HANDLE hThread = CreateThread(NULL, 0, threadRoutine, this, 0, NULL);
IfFalseRet(hThread != NULL, CORPROF_E_PROFILER_CANCEL_ACTIVATION);
CHandle hConfigThread(hThread);
DWORD waitTime = 60 * 1000; // Wait 1 minute for loading instrumentation methods
#ifndef PLATFORM_UNIX
if (IsDebuggerPresent())
{
waitTime = INFINITE;
}
#endif
DWORD retVal = WaitForSingleObject(hConfigThread, waitTime);
if (retVal == WAIT_TIMEOUT)
{
CLogging::LogError(_T("CProfilerManager::InvokeThreadRoutine - ThreadRoutine timeout exceeded"));
return CORPROF_E_PROFILER_CANCEL_ACTIVATION;
}
if (retVal != WAIT_OBJECT_0)
{
CLogging::LogError(_T("CProfilerManager::InvokeThreadRoutine - ThreadRoutine failed with error 0x%08X"), HRESULT_FROM_WIN32(GetLastError()));
return CORPROF_E_PROFILER_CANCEL_ACTIVATION;
}
return S_OK;
}
HRESULT CProfilerManager::AddRawProfilerHook(
_In_ IUnknown *pUnkProfilerCallback
)
{
HRESULT hr = S_OK;
IfNullRetPointer(pUnkProfilerCallback);
if (m_profilerCallbackHolder != nullptr)
{
CLogging::LogError(_T("CAppDomainInfo::AddRawProfilerHook - Raw profiler hook is already initialized"));
return E_FAIL;
}
if (!GetIsInInitialize())
{
CLogging::LogError(_T("Begin CAppDomainInfo::AddRawProfilerHook - Cannot add a raw profiler hook after initialize"));
return E_FAIL;
}
CCriticalSectionHolder lock(&m_cs);
unique_ptr<CProfilerCallbackHolder> profilerCallbackHolder(new CProfilerCallbackHolder);
// Rather than following COM-rules and QI-ing for each specific ICorProfilerCallback version, we instead follow the implementation set by the CLR
// where to interface inheritance, higher versioned ICorProfilerCallback## can be statically-casted to lower versioned ICorProfilerCallback##,
// and raw profilers QI can just return the highest supported version (they must still provide implementation for all lower versioned callbacks).
//
// See https://github.com/dotnet/runtime/blob/cf6b06b1d36d545e37b00bf1a6311b7fff33ff4e/src/coreclr/src/vm/eetoprofinterfaceimpl.cpp#L613
// ICorProfilerCallback7
CComPtr<ICorProfilerCallback7> pCorProfilerCallback7;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback7), (LPVOID*)&pCorProfilerCallback7);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback7 = pCorProfilerCallback7;
}
// ICorProfilerCallback6
if (profilerCallbackHolder->m_CorProfilerCallback7)
{
profilerCallbackHolder->m_CorProfilerCallback6 = static_cast<ICorProfilerCallback6*>(profilerCallbackHolder->m_CorProfilerCallback7);
}
else
{
CComPtr<ICorProfilerCallback6> pCorProfilerCallback6;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback6), (LPVOID*)&pCorProfilerCallback6);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback6 = pCorProfilerCallback6;
}
}
// ICorProfilerCallback5
if (profilerCallbackHolder->m_CorProfilerCallback6)
{
profilerCallbackHolder->m_CorProfilerCallback5 = static_cast<ICorProfilerCallback5*>(profilerCallbackHolder->m_CorProfilerCallback6);
}
else
{
CComPtr<ICorProfilerCallback5> pCorProfilerCallback5;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback5), (LPVOID*)&pCorProfilerCallback5);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback5 = pCorProfilerCallback5;
}
}
// ICorProfilerCallback4
if (profilerCallbackHolder->m_CorProfilerCallback5)
{
profilerCallbackHolder->m_CorProfilerCallback4 = static_cast<ICorProfilerCallback4*>(profilerCallbackHolder->m_CorProfilerCallback5);
}
else
{
CComPtr<ICorProfilerCallback4> pCorProfilerCallback4;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback4), (LPVOID*)&pCorProfilerCallback4);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback4 = pCorProfilerCallback4;
}
}
// ICorProfilerCallback3
if (profilerCallbackHolder->m_CorProfilerCallback4)
{
profilerCallbackHolder->m_CorProfilerCallback3 = static_cast<ICorProfilerCallback3*>(profilerCallbackHolder->m_CorProfilerCallback4);
}
else
{
CComPtr<ICorProfilerCallback3> pCorProfilerCallback3;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback3), (LPVOID*)&pCorProfilerCallback3);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback3 = pCorProfilerCallback3;
}
}
// ICorProfilerCallback2
if (profilerCallbackHolder->m_CorProfilerCallback3)
{
profilerCallbackHolder->m_CorProfilerCallback2 = static_cast<ICorProfilerCallback2*>(profilerCallbackHolder->m_CorProfilerCallback3);
}
else
{
CComPtr<ICorProfilerCallback2> pCorProfilerCallback2;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback2), (LPVOID*)&pCorProfilerCallback2);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback2 = pCorProfilerCallback2;
}
}
// ICorProfilerCallback
if (profilerCallbackHolder->m_CorProfilerCallback2)
{
profilerCallbackHolder->m_CorProfilerCallback = static_cast<ICorProfilerCallback*>(profilerCallbackHolder->m_CorProfilerCallback2);
}
else
{
CComPtr<ICorProfilerCallback> pCorProfilerCallback;
hr = pUnkProfilerCallback->QueryInterface(__uuidof(ICorProfilerCallback), (LPVOID*)&pCorProfilerCallback);
if (SUCCEEDED(hr))
{
profilerCallbackHolder->m_CorProfilerCallback = pCorProfilerCallback;
}
}
m_profilerCallbackHolder = std::move(profilerCallbackHolder);
return S_OK;
}
HRESULT CProfilerManager::RemoveRawProfilerHook(
)
{
HRESULT hr = S_OK;
CCriticalSectionHolder lock(&m_cs);
m_profilerCallbackHolder = nullptr;
return S_OK;
}
HRESULT CProfilerManager::GetCorProfilerInfo(
_Outptr_ IUnknown **ppCorProfiler
)
{
IfNullRetPointer(ppCorProfiler);
IfNullRet(m_pWrappedProfilerInfo);
*ppCorProfiler = (IUnknown*)(m_pWrappedProfilerInfo.p);
(*ppCorProfiler)->AddRef();
return S_OK;
}
// return the profiler host instance
HRESULT CProfilerManager::GetProfilerHost(_Out_ IProfilerManagerHost** ppProfilerManagerHost)
{
return E_NOTIMPL;
}
// Returns an instance of IProfilerManagerLogging which instrumentation methods can use
// to log to the profiler manager or optionally to the profiler host.
HRESULT CProfilerManager::GetLoggingInstance(_Out_ IProfilerManagerLogging** ppLogging)
{
*ppLogging = (IProfilerManagerLogging*)this;
(*ppLogging)->AddRef();
return S_OK;
}
// By default, logging messages are written to the debug output port. However,
// hosts can optionally signup to receive them through an instance of IProfilerManagerLogging
HRESULT CProfilerManager::SetLoggingHost(_In_opt_ IProfilerManagerLoggingHost* pLoggingHost)
{
HRESULT hr = S_OK;
CLogging::SetLoggingHost(pLoggingHost);
return S_OK;
}
HRESULT CProfilerManager::GetAppDomainCollection(_Out_ IAppDomainCollection** ppAppDomainCollection)
{
HRESULT hr = S_OK;
*ppAppDomainCollection = (IAppDomainCollection*)m_pAppDomainCollection;
(*ppAppDomainCollection)->AddRef();
return hr;
}
// IProfilerManagerLogging Methods
// If trace logging in enabled in the profiler manager, trace messages are sent to the
// profiler manager through this function.
HRESULT CProfilerManager::LogMessage(_In_ const WCHAR* wszMessage)
{
CLogging::LogMessage(wszMessage);
return S_OK;
}
// Errors detected during profiling will be sent to the host through this method
HRESULT CProfilerManager::LogError(_In_ const WCHAR* wszError)
{
CLogging::LogError(wszError);
return S_OK;
}
// If instrumentation result tracing is enabled, the detailed results of each instrumented
// method will be sent to the profiler manager host through this method.
HRESULT CProfilerManager::LogDumpMessage(_In_ const WCHAR* wszMessage)
{
CLogging::LogDumpMessage(wszMessage);
return S_OK;
}
// Called to cause logging to be written to the debug output port (via DebugOutputString) as well
// as to the host.
HRESULT CProfilerManager::EnableDiagnosticLogToDebugPort(_In_ BOOL enable)
{
CLogging::SetLogToDebugPort(enable != 0);
return S_OK;
}
// Allows instrumentation methods and hosts to ask for the current logging flags
HRESULT CProfilerManager::GetLoggingFlags(_Out_ LoggingFlags* pLoggingFlags)
{
HRESULT hr = S_OK;
IfNullRetPointer(pLoggingFlags);
IfFailRet(CLogging::GetLoggingFlags(pLoggingFlags));
return S_OK;
}
// Allows instrumentation methods and hosts to modify the current logging level
HRESULT CProfilerManager::SetLoggingFlags(_In_ LoggingFlags loggingFlags)
{
HRESULT hr = S_OK;
IfFailRet(CLogging::SetLoggingFlags(loggingFlags));
return S_OK;
}
// The CLR doesn't initialize com before calling the profiler, and the profiler manager cannot do so itself
// as that would screw up the com state for the application thread. This thread allows the profiler manager
// to co create a free threaded version of msxml on a thread that it owns to avoid this.
//static
DWORD WINAPI CProfilerManager::InstrumentationMethodThreadProc(
_In_ LPVOID lpParameter
)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CProfilerManager::InstrumentationMethodThreadProc"));
#ifndef PLATFORM_UNIX
hr = CoInitialize(NULL);
if (FAILED(hr))
{
CLogging::LogError(_T("CProfilerManager::InstrumentationMethodThreadProc - CoInitializeEx failed"));
return 1;
}
#endif
CProfilerManager* pProfilerManager = static_cast<CProfilerManager*>(lpParameter);
if (pProfilerManager == NULL)
{
CLogging::LogError(_T("CProfilerManager::InstrumentationMethodThreadProc - Invalid parameter"));
return 1;
}
for (UINT i = 0; i < pProfilerManager->m_configSources.size(); i++)
{
IfFailRet(pProfilerManager->LoadInstrumentationMethods(pProfilerManager->m_configSources[i]));
}
#ifndef PLATFORM_UNIX
CoUninitialize();
#endif
CLogging::LogMessage(_T("End CProfilerManager::InstrumentationMethodThreadProc"));
return 0;
}
//static
DWORD WINAPI CProfilerManager::ParseAttachConfigurationThreadProc(
_In_ LPVOID lpParameter
)
{
HRESULT hr = S_OK;
CLogging::LogMessage(_T("Starting CConfigurationLocator::ParseAttachConfigurationThreadProc"));
#ifndef PLATFORM_UNIX
hr = CoInitialize(NULL);
if (FAILED(hr))
{
CLogging::LogError(_T("CConfigurationLocator::ParseAttachConfigurationThreadProc - CoInitializeEx failed"));
return 1;
}
#endif
CProfilerManager* pProfilerManager = static_cast<CProfilerManager*>(lpParameter);
if (pProfilerManager == NULL)
{
CLogging::LogError(_T("CConfigurationLocator::ParseAttachConfigurationThreadProc - Invalid parameter"));
return 1;
}
CComPtr<CXmlDocWrapper> pDocument;
pDocument.Attach(new CXmlDocWrapper());
IfFailRet(pDocument->LoadContent(pProfilerManager->m_tstrConfigXml.c_str()));
CComPtr<CXmlNode> pDocumentNode;
IfFailRet(pDocument->GetRootNode(&pDocumentNode));
CComPtr<CXmlNode> pCurrChildNode;
IfFailRet(pDocumentNode->GetChildNode(&pCurrChildNode));
CComBSTR bstrCurrChildNodeName;
IfFailRet(pDocumentNode->GetName(&bstrCurrChildNodeName));
if (wcscmp(bstrCurrChildNodeName, _T("InstrumentationEngineConfiguration")) != 0)
{
CLogging::LogError(_T("CConfigurationLocator::ParseAttachConfigurationThreadProc - Invalid configuration. Root element should be InstrumentationEngineConfiguration"));
return E_FAIL;
}
while (pCurrChildNode != nullptr)
{
IfFailRet(pCurrChildNode->GetName(&bstrCurrChildNodeName));
if (wcscmp(bstrCurrChildNodeName, _T("InstrumentationEngine")) == 0)
{
CComPtr<CXmlNode> pSettingsNode;
IfFailRet(pCurrChildNode->GetChildNode(&pSettingsNode));
if (pSettingsNode != nullptr)
{
CComBSTR bstrSettingsNodeName;
IfFailRet(pSettingsNode->GetName(&bstrSettingsNodeName));
if (wcscmp(bstrSettingsNodeName, _T("Settings")) == 0)
{
unordered_map<tstring, tstring> settingsMap;
IfFailRet(ParseSettingsConfigurationNode(pSettingsNode, settingsMap));
for (unordered_map<tstring, tstring>::iterator it = settingsMap.begin();
it != settingsMap.end();
++it)
{
if (wcscmp(it->first.c_str(), _T("LogLevel")) == 0)
{
CLogging::SetLoggingFlags(CLoggerService::ExtractLoggingFlags(it->second.c_str()));
}
else if (wcscmp(it->first.c_str(), _T("LogFileLevel")) == 0)
{
CLogging::SetLogFileLevel(CLoggerService::ExtractLoggingFlags(it->second.c_str()));
}
else if (wcscmp(it->first.c_str(), _T("LogFilePath")) == 0)
{
CLogging::SetLogFilePath(it->second.c_str());
}
}
}
}
}
else if (wcscmp(bstrCurrChildNodeName, _T("InstrumentationMethods")) == 0)
{
CComPtr<CXmlNode> pInstrumentationMethodNode;
IfFailRet(pCurrChildNode->GetChildNode(&pInstrumentationMethodNode));
while (pInstrumentationMethodNode != nullptr)
{
CComBSTR bstrInstrumentationMethodNodeName;
IfFailRet(pInstrumentationMethodNode->GetName(&bstrInstrumentationMethodNodeName));
if (wcscmp(bstrInstrumentationMethodNodeName, _T("AddInstrumentationMethod")) == 0)
{
CComBSTR bstrConfigPath;
IfFailRet(pInstrumentationMethodNode->GetAttribute(_T("ConfigPath"), &bstrConfigPath));
IfFalseRet(bstrConfigPath.Length() != 0, E_FAIL);
CComPtr<CConfigurationSource> pSource;
pSource.Attach(new (nothrow) CConfigurationSource(bstrConfigPath));
IfFalseRet(nullptr != pSource, E_OUTOFMEMORY);
CComPtr<CXmlNode> pInstrumentationMethodChildNode;
IfFailRet(pInstrumentationMethodNode->GetChildNode(&pInstrumentationMethodChildNode));
while (pInstrumentationMethodChildNode != nullptr)
{
CComBSTR bstrInstrumentationMethodChildNodeName;
IfFailRet(pInstrumentationMethodChildNode->GetName(&bstrInstrumentationMethodChildNodeName));
if (wcscmp(bstrInstrumentationMethodChildNodeName, _T("Settings")) == 0)
{
unordered_map<tstring, tstring> settingsMap;
IfFailRet(ParseSettingsConfigurationNode(pInstrumentationMethodChildNode, settingsMap));
for (unordered_map<tstring, tstring>::iterator it = settingsMap.begin();
it != settingsMap.end();
++it)
{
IfFailRet(pSource->AddSetting(it->first.c_str(), it->second.c_str()));
}
}
CXmlNode* nextInstrumentationMethod = pInstrumentationMethodChildNode->Next();
pInstrumentationMethodChildNode.Release();
pInstrumentationMethodChildNode.Attach(nextInstrumentationMethod);
}
pProfilerManager->m_configSources.push_back(pSource.p);
}
CXmlNode* next = pInstrumentationMethodNode->Next();
pInstrumentationMethodNode.Release();
pInstrumentationMethodNode.Attach(next);
}
}
CXmlNode* next = pCurrChildNode->Next();
pCurrChildNode.Release();
pCurrChildNode.Attach(next);
}
#ifndef PLATFORM_UNIX
CoUninitialize();
#endif
CLogging::LogMessage(_T("End CConfigurationLocator::ParseAttachConfigurationThreadProc"));
return 0;
}
//static
HRESULT CProfilerManager::ParseSettingsConfigurationNode(
_In_ const CComPtr<CXmlNode>& parentNode,
_Inout_ unordered_map<tstring, tstring>& settings)
{
HRESULT hr = S_OK;
CComPtr<CXmlNode> pSettingNode;
IfFailRet(parentNode->GetChildNode(&pSettingNode));
while (pSettingNode != nullptr)
{
CComBSTR bstrSettingNodeName;
IfFailRet(pSettingNode->GetName(&bstrSettingNodeName));
IfFalseRet(wcscmp(bstrSettingNodeName, _T("Setting")) == 0, E_FAIL);
CComBSTR bstrSettingName;
IfFailRet(pSettingNode->GetAttribute(_T("Name"), &bstrSettingName));
IfFalseRet(bstrSettingName.Length() != 0, E_FAIL);
CComBSTR bstrSettingValue;
IfFailRet(pSettingNode->GetAttribute(_T("Value"), &bstrSettingValue));
IfFalseRet(bstrSettingValue.Length() != 0, E_FAIL);
if (settings.find(bstrSettingName.m_str) == settings.end())
{
settings.insert(std::pair<tstring, tstring>(bstrSettingName.m_str, bstrSettingValue.m_str));
}
CXmlNode* nextSetting = pSettingNode->Next();
pSettingNode.Release();
pSettingNode.Attach(nextSetting);
}
return S_OK;
}
HRESULT CProfilerManager::LoadInstrumentationMethods(_In_ CConfigurationSource* pConfigurationSource)
{
IfFalseRet(nullptr != pConfigurationSource, E_INVALIDARG);
HRESULT hr = S_OK;
CComBSTR bstrConfigPath;
IfFailRet(pConfigurationSource->GetPath(&bstrConfigPath));
if (SysStringLen(bstrConfigPath) == 0)
{
CLogging::LogError(_T("Configuration xml should be set"));
return E_FAIL;
}
CConfigurationLoader loader;
std::vector<CInstrumentationMethod*> tempMethods;
std::vector<CInstrumentationMethod*> instrumentationMethods;
if (FAILED(loader.LoadConfiguration(bstrConfigPath, tempMethods)))
{
CLogging::LogError(_T("Failed to load configuration file '%s'."), bstrConfigPath.m_str);
}
// Remove methods with duplicate classIds
for (CInstrumentationMethod* method : tempMethods)
{
GUID currentMethodGuid = method->GetClassId();
std::vector<GUID>::iterator it = std::find(m_instrumentationMethodGuids.begin(), m_instrumentationMethodGuids.end(), currentMethodGuid);
if (it != m_instrumentationMethodGuids.end())
{
WCHAR wszCurrentMethodGuid[40] = { 0 };
if (0 != ::StringFromGUID2(currentMethodGuid, wszCurrentMethodGuid, 40))
{
CLogging::LogMessage(_T("CProfilerManager::LoadInstrumentationMethods - Instrumentation Method found with duplicate ClassId '%s' of another previously loaded method. Skipping."), wszCurrentMethodGuid);
}
delete method;
}
else
{
instrumentationMethods.push_back(method);
m_instrumentationMethodGuids.push_back(currentMethodGuid);
}
}
CComPtr<IEnumInstrumentationMethodSettings> pSettingsEnum;
IfFailRet(pConfigurationSource->EnumSettings(&pSettingsEnum));
for (CInstrumentationMethod* method : instrumentationMethods)
{
// Reset the position of the enumerator before initializing the next instrumentation method
IfFailRet(pSettingsEnum->Reset());
IInstrumentationMethod* pInstrumentationMethod = nullptr;
this->AddInstrumentationMethod(method, pSettingsEnum, &pInstrumentationMethod);
}
return S_OK;
}
HRESULT CProfilerManager::RemoveInstrumentationMethod(
_In_ IInstrumentationMethod* pInstrumentationMethod)
{
HRESULT hr = S_OK;
{
DWORD dwFlags = 0;
CCriticalSectionHolder lock(&m_cs);
for (TInstrumentationMethodsCollection::iterator iter = m_instrumentationMethods.begin(); iter != m_instrumentationMethods.end(); ++iter)
{
CComPtr<IInstrumentationMethod> spInstrMethodTmp;
IfFailRet(iter->first->GetRawInstrumentationMethod(&spInstrMethodTmp));
if (spInstrMethodTmp.p == pInstrumentationMethod)
{
dwFlags = iter->second;
m_instrumentationMethods.erase(iter);
break;
}
}
if (dwFlags != 0)
{
CInitializeInstrumentationMethodHolder initHolder(this);
//this operation will remove flags associated with removed Instrumentation method
// We need to trace error, however remove operation will succeed anyway
HRESULT hr2 = SetEventMask(0);
if (FAILED(hr2))
{
#ifndef PLATFORM_UNIX
CLogging::LogError(_T("SetEventMask failed in function ") __FUNCTIONW__ _T(". This may be expected if instrumentation method attempted to set mutable flags. Flags: %X %X"), dwFlags, hr2);
#else
CLogging::LogError(_T("SetEventMask failed in function ") WCHAR_SPEC _T(". This may be expected if instrumentation method attempted to set mutable flags. Flags: %X %X"), __FUNCTION__, dwFlags, hr);
#endif
}
}
}
return hr;
}
HRESULT CProfilerManager::AddInstrumentationMethod(
_In_ CInstrumentationMethod* pInstrumentationMethod,
_In_ IEnumInstrumentationMethodSettings* pSettingsEnum,
_Out_ IInstrumentationMethod** ppInstrumentationMethod)
{
HRESULT hr = S_OK;
{
CCriticalSectionHolder lock(&m_cs);
DWORD dwFlags = 0;
{
//Initialize Instrumentation method.
// Initialize method of InstrumentationMethod can set additional flags that will be associated with this
// InstrumentationMethod. Since we are using global lock - InstrumentationMethod can only set flags associated
// with it in this thread.
CInitializeInstrumentationMethodHolder initHolder(this);
CComPtr<CProfilerManagerForInstrumentationMethod> pProfilerManagerWrapper;
GUID classId = pInstrumentationMethod->GetClassId();
pProfilerManagerWrapper.Attach(new (nothrow) CProfilerManagerForInstrumentationMethod(classId, this));
if (pProfilerManagerWrapper == nullptr)
{
return E_OUTOFMEMORY;
}
LoggingFlags instrumentationMethodLoggingFlag;
if (SUCCEEDED(pProfilerManagerWrapper->GetInstrumentationMethodLoggingFlags(&instrumentationMethodLoggingFlag)))
{
CLogging::UpdateInstrumentationMethodLoggingFlags(classId, instrumentationMethodLoggingFlag);
}
// Do not detach so CComPtr can track refcount.
if (m_bAttach)
{
hr = pInstrumentationMethod->InitializeForAttach(pProfilerManagerWrapper, pSettingsEnum, m_bValidateCodeSignature);
}
else
{
hr = pInstrumentationMethod->Initialize(pProfilerManagerWrapper, m_bValidateCodeSignature);
}
dwFlags = GetInitializingInstrumentationMethodFlags();
}
if (FAILED(hr))
{
return hr;
}
bool bInserted = false;
// Number of instrumentation methods is expected to be very small.
for (TInstrumentationMethodsCollection::iterator iter = m_instrumentationMethods.begin(); iter != m_instrumentationMethods.end(); ++iter)
{
shared_ptr<CInstrumentationMethod> pCurrInstrumentationMethod = iter->first;
if (pCurrInstrumentationMethod->GetPriority() > pInstrumentationMethod->GetPriority())
{
m_instrumentationMethods.insert(iter, TInstrumentationMethodsCollection::value_type(std::shared_ptr<CInstrumentationMethod>(pInstrumentationMethod), dwFlags));
bInserted = true;
break;
}
}
if (!bInserted)
{
m_instrumentationMethods.push_back(TInstrumentationMethodsCollection::value_type(std::shared_ptr<CInstrumentationMethod>(pInstrumentationMethod), dwFlags));
}
}
IfFailRet(pInstrumentationMethod->GetRawInstrumentationMethod(ppInstrumentationMethod));
return hr;
}
HRESULT CProfilerManager::AddInstrumentationMethod(
_In_ BSTR bstrModulePath,
_In_ BSTR bstrName,
_In_ BSTR bstrDescription,
_In_ BSTR bstrModule,
_In_ BSTR bstrClassGuid,
_In_ DWORD dwPriority,
_Out_ IInstrumentationMethod** ppInstrumentationMethod)
{
IfNullRetPointer(ppInstrumentationMethod);
*ppInstrumentationMethod = nullptr;
HRESULT hr = S_OK;
GUID guidClassId;
hr = IIDFromString(bstrClassGuid, (LPCLSID)&guidClassId);
if (FAILED(hr))
{
CLogging::LogError(_T("CInstrumentationMethod::Initialize - Bad classid for instrumentation method"));
return E_INVALIDARG;
}
unique_ptr<CInstrumentationMethod> pInstrumentationMethod(new CInstrumentationMethod(bstrModulePath, bstrName, bstrDescription, bstrModule, guidClassId, dwPriority));
if (pInstrumentationMethod == nullptr)
{
CLogging::LogError(_T("Unable to create a new instance of CInstrumentationMethod. Treating it as an out of memory error."));
return E_OUTOFMEMORY;
}
CComPtr<CConfigurationSource> pSource;
pSource.Attach(new (nothrow) CConfigurationSource(bstrModulePath));
IfFalseRet(nullptr != pSource, E_OUTOFMEMORY);
CComPtr<IEnumInstrumentationMethodSettings> pSettingsEnum;
IfFailRet(pSource->EnumSettings(&pSettingsEnum));
return this->AddInstrumentationMethod(pInstrumentationMethod.release(), pSettingsEnum, ppInstrumentationMethod);
}
HRESULT CProfilerManager::DisableProfiling()
{
m_bProfilingDisabled = true;
return S_OK;
}
HRESULT CProfilerManager::ApplyMetadata(_In_ IModuleInfo* pMethodInfo)
{
HRESULT hr = S_OK;
IfNullRet(pMethodInfo);
CComQIPtr<ICorProfilerInfo7> pCorProfiler7 = m_pRealProfilerInfo.p;
IfNullRet(pCorProfiler7);
ModuleID moduleId;
IfFailRet(static_cast<CModuleInfo*>(pMethodInfo)->GetModuleID(&moduleId));
IfFailRet(pCorProfiler7->ApplyMetaData(moduleId));
return S_OK;
}
HRESULT CProfilerManager::GetApiVersion(_Out_ DWORD* pApiVer)
{
IfNullRet(pApiVer);
*pApiVer = CLR_INSTRUMENTATION_ENGINE_API_VER;
return S_OK;
}
HRESULT CProfilerManager::GetGlobalLoggingInstance(_Out_ IProfilerManagerLogging** ppLogging)
{
if (nullptr == ppLogging)
{
return E_POINTER;
}
CComPtr<CLoggingWrapper> pLogging;
pLogging.Attach(new (nothrow) CLoggingWrapper());
if (nullptr == pLogging)
{
return E_OUTOFMEMORY;
}
HRESULT hr = S_OK;
IfFailRetNoLog(pLogging->Initialize());
*ppLogging = pLogging.Detach();
return S_OK;
}
HRESULT CProfilerManager::IsInstrumentationMethodRegistered(_In_ REFGUID clsid, _Out_ BOOL* pfRegistered)
{
IfNullRet(pfRegistered);
CCriticalSectionHolder lock(&m_cs);
*pfRegistered = FALSE;
std::vector<GUID>::iterator it = std::find(m_instrumentationMethodGuids.begin(), m_instrumentationMethodGuids.end(), clsid);
if (it != m_instrumentationMethodGuids.end())
{
*pfRegistered = TRUE;
}
return S_OK;
}
// ICorProfilerCallback methods
HRESULT CProfilerManager::Initialize(
_In_ IUnknown *pICorProfilerInfoUnk)
{
HRESULT hr = S_OK;
PROF_CALLBACK_BEGIN
// Try to get instrumentation methods from environment variables
IfFailRet(CConfigurationLocator::GetFromEnvironment(m_configSources));
#ifndef PLATFORM_UNIX
if (0 == m_configSources.size())
{
IfFailRet(CConfigurationLocator::GetFromFilesystem(m_configSources));
}
#endif
// Mark that this is during the initialize call. This enables operations that can only be supported during initialize
CInitializeHolder initHolder(this);
IfFailRet(InitializeCore(pICorProfilerInfoUnk));
if (m_bProfilingDisabled)
{
return CORPROF_E_PROFILER_CANCEL_ACTIVATION;
}
// Take the lock that protects the raw profiler callback and the instrumentation methods. This keeps the collection from changing out from under the iterator
CCriticalSectionHolder lock(&m_cs);
if (m_profilerCallbackHolder != nullptr)
{
CComPtr<ICorProfilerCallback2> pCallback = m_profilerCallbackHolder->m_CorProfilerCallback2;
if (pCallback)
{
if (m_attachedClrVersion != ClrVersion_2)
{
IfFailRet(pCallback->Initialize((IUnknown*)(m_pWrappedProfilerInfo.p)));
}
else
{
IfFailRet(pCallback->Initialize((IUnknown*)(m_pRealProfilerInfo.p)));
}
}
}
PROF_CALLBACK_END
return S_OK;
}
HRESULT CProfilerManager::DetermineClrVersion()
{
if (m_pRealProfilerInfo)
{
CComPtr<ICorProfilerInfo3> pRealProfilerInfo3;
if (FAILED(m_pRealProfilerInfo->QueryInterface(__uuidof(ICorProfilerInfo3), (void**)&pRealProfilerInfo3)) ||
pRealProfilerInfo3 == nullptr ||
FAILED(pRealProfilerInfo3->GetRuntimeInformation(
nullptr,
&m_runtimeType,