forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofilinghelper.cpp
1635 lines (1423 loc) · 61.3 KB
/
profilinghelper.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.
//
// ProfilingHelper.cpp
//
//
// Implementation of helper classes used for miscellaneous purposes within the profiling
// API
//
// ======================================================================================
//
// #LoadUnloadCallbackSynchronization
//
// There is synchronization around loading profilers, unloading profilers, and issuing
// callbacks to profilers, to ensure that we know when it's safe to detach profilers or
// to call into profilers. The synchronization scheme is intentionally lockless on the
// mainline path (issuing callbacks into the profiler), with heavy locking on the
// non-mainline path (loading / unloading profilers).
//
// PROTECTED DATA
//
// The synchronization protects the following data:
//
// * ProfilingAPIDetach::s_profilerDetachInfo
// * (volatile) g_profControlBlock.curProfStatus.m_profStatus
// * (volatile) g_profControlBlock.pProfInterface
// * latter implies the profiler DLL's load status is protected as well, as
// pProfInterface changes between non-NULL and NULL as a profiler DLL is
// loaded and unloaded, respectively.
//
// SYNCHRONIZATION COMPONENTS
//
// * Simple Crst: code:ProfilingAPIUtility::s_csStatus
// * Lockless, volatile per-thread counters: code:EvacuationCounterHolder
// * Profiler status transition invariants and CPU buffer flushing:
// code:CurrentProfilerStatus::Set
//
// WRITERS
//
// The above data is considered to be "written to" when a profiler is loaded or unloaded,
// or the status changes (see code:ProfilerStatus), or a request to detach the profiler
// is received (see code:ProfilingAPIDetach::RequestProfilerDetach), or the DetachThread
// consumes or modifies the contents of code:ProfilingAPIDetach::s_profilerDetachInfo.
// All these cases are serialized with each other by the simple Crst:
// code:ProfilingAPIUtility::s_csStatus
//
// READERS
//
// Readers are the mainline case and are lockless. A "reader" is anyone who wants to
// issue a profiler callback. Readers are scattered throughout the runtime, and have the
// following format:
// {
// BEGIN_PROFILER_CALLBACK(CORProfilerTrackAppDomainLoads());
// // call the ProfControlBlock callback wrapper
// (&g_profControlBlock)->AppDomainCreationStarted(MyAppDomainID);
// END_PROFILER_CALLBACK();
// }
// The BEGIN / END macros evaluates the expression argument (CORProfiler*). This is a
// "dirty read" as the profiler could be detached at any moment during or after that
// evaluation.
//
// The ProfControlBlock callback wrappers call DoOneProfilerIteration, doing the following:
// * Pushes a code:EvacuationCounterHolder on the stack for the ProfilerInfo, which
// increments the per-thread evacuation counter (not interlocked).
// * Checks the profiler status (code:ProfilerStatus) to see if the profiler is active.
// * Evaluates the ProfControlBlock condition func (e.g. IsProfilerTrackingAppDomainLoads).
// * If true, invokes the callback func (e.g. AppDomainCreationStartedHelper) which in turn
// calls the EEToProfInterfaceImpl implementation where the profiler is guaranteed to
// remain loaded, because the evacuation counter remains nonzero (again, see below).
// * Once the DoOneProfilerIteration block is exited, the evacuation counter is decremented
// and the profiler is unpinned and allowed to detach.
//
// READER / WRITER COORDINATION
//
// The above ensures that a reader never touches EEToProfInterfaceImpl and
// all it embodies (including the profiler DLL code and callback implementations) unless
// the reader was able to increment its thread's evacuation counter AND re-verify that
// the profiler's status is still active (the status check is included in the macro's
// expression argument, such as CORProfilerTrackAppDomainLoads()).
//
// At the same time, a profiler DLL is never unloaded (nor
// g_profControlBlock.pProfInterface deleted and NULLed out) UNLESS the writer performs
// these actions:
// * (a) Set the profiler's status to a non-active state like kProfStatusDetaching or
// kProfStatusNone
// * (b) Call FlushProcessWriteBuffers()
// * (c) Grab thread store lock, iterate through all threads, and verify each per-thread
// evacuation counter is zero.
//
// The above steps are why it's considered a "clean read" if a reader first increments
// its evacuation counter and then checks the profiler status. Once the writer flushes
// the CPU buffers (b), the reader will see the updated status (from a) and know not to
// use g_profControlBlock.pProfInterface. And if the reader clean-reads the status before
// the buffers were flushed, then the reader will have incremented its evacuation counter
// first, which the writer will be sure to see in (c). For more details about how the
// evacuation counters work, see code:ProfilingAPIUtility::IsProfilerEvacuated.
//
#include "common.h"
#ifdef PROFILING_SUPPORTED
#include "eeprofinterfaces.h"
#include "eetoprofinterfaceimpl.h"
#include "eetoprofinterfaceimpl.inl"
#include "corprof.h"
#include "proftoeeinterfaceimpl.h"
#include "proftoeeinterfaceimpl.inl"
#include "profilinghelper.h"
#include "profilinghelper.inl"
#ifdef FEATURE_PROFAPI_ATTACH_DETACH
#include "profdetach.h"
#endif // FEATURE_PROFAPI_ATTACH_DETACH
#include "utilcode.h"
// ----------------------------------------------------------------------------
// CurrentProfilerStatus methods
//---------------------------------------------------------------------------------------
//
// Updates the value indicating the profiler's current status
//
// Arguments:
// profStatus - New value (from enum ProfilerStatus) to set.
//
// Notes:
// Sets the status under a lock, and performs a debug-only check to verify that the
// status transition is a legal one. Also performs a FlushStoreBuffers() after
// changing the status when necessary.
//
void CurrentProfilerStatus::Set(ProfilerStatus newProfStatus)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
_ASSERTE(ProfilingAPIUtility::GetStatusCrst() != NULL);
{
// Need to serialize attempts to transition the profiler status. For example, a
// profiler in one thread could request a detach, while the CLR in another
// thread is transitioning the profiler from kProfStatusInitializing* to
// kProfStatusActive
CRITSEC_Holder csh(ProfilingAPIUtility::GetStatusCrst());
// Based on what the old status is, verify the new status is a legal transition.
switch(m_profStatus)
{
default:
_ASSERTE(!"Unknown ProfilerStatus");
break;
case kProfStatusNone:
_ASSERTE((newProfStatus == kProfStatusPreInitialize) ||
(newProfStatus == kProfStatusInitializingForStartupLoad) ||
(newProfStatus == kProfStatusInitializingForAttachLoad));
break;
case kProfStatusDetaching:
_ASSERTE(newProfStatus == kProfStatusNone);
break;
case kProfStatusInitializingForStartupLoad:
case kProfStatusInitializingForAttachLoad:
_ASSERTE((newProfStatus == kProfStatusActive) ||
(newProfStatus == kProfStatusNone));
break;
case kProfStatusActive:
_ASSERTE((newProfStatus == kProfStatusNone) ||
(newProfStatus == kProfStatusDetaching));
break;
case kProfStatusPreInitialize:
_ASSERTE((newProfStatus == kProfStatusNone) ||
(newProfStatus == kProfStatusInitializingForStartupLoad) ||
(newProfStatus == kProfStatusInitializingForAttachLoad));
break;
}
m_profStatus = newProfStatus;
}
#if !defined(DACCESS_COMPILE)
if (((newProfStatus == kProfStatusNone) ||
(newProfStatus == kProfStatusDetaching) ||
(newProfStatus == kProfStatusActive)))
{
// Flush the store buffers on all CPUs, to ensure other threads see that
// g_profControlBlock.curProfStatus has changed. The important status changes to
// flush are:
// * to kProfStatusNone or kProfStatusDetaching so other threads know to stop
// making calls into the profiler
// * to kProfStatusActive, to ensure callbacks can be issued by the time an
// attaching profiler receives ProfilerAttachComplete(), so the profiler
// can safely perform catchup at that time (see
// code:#ProfCatchUpSynchronization).
//
::FlushProcessWriteBuffers();
}
#endif // !defined(DACCESS_COMPILE)
}
//---------------------------------------------------------------------------------------
// ProfilingAPIUtility members
// See code:#LoadUnloadCallbackSynchronization.
CRITSEC_COOKIE ProfilingAPIUtility::s_csStatus = NULL;
// ----------------------------------------------------------------------------
// ProfilingAPIUtility::AppendSupplementaryInformation
//
// Description:
// Helper to the event logging functions to append the process ID and string
// resource ID to the end of the message.
//
// Arguments:
// * iStringResource - [in] String resource ID to append to message.
// * pString - [in/out] On input, the string to log so far. On output, the original
// string with the process ID info appended.
//
// static
void ProfilingAPIUtility::AppendSupplementaryInformation(int iStringResource, SString * pString)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This loads resource strings, which takes locks.
CAN_TAKE_LOCK;
}
CONTRACTL_END;
StackSString supplementaryInformation;
if (!supplementaryInformation.LoadResource(
CCompRC::Debugging,
IDS_PROF_SUPPLEMENTARY_INFO
))
{
// Resource not found; should never happen.
return;
}
StackSString supplementaryInformationUtf8;
supplementaryInformation.ConvertToUTF8(supplementaryInformationUtf8);
pString->AppendUTF8(" ");
pString->AppendPrintf(
supplementaryInformationUtf8.GetUTF8(),
GetCurrentProcessId(),
iStringResource);
}
//---------------------------------------------------------------------------------------
//
// Helper function to log publicly-viewable errors about profiler loading and
// initialization.
//
//
// Arguments:
// * iStringResourceID - resource ID of string containing message to log
// * wEventType - same constant used in win32 to specify the type of event:
// usually EVENTLOG_ERROR_TYPE, EVENTLOG_WARNING_TYPE, or
// EVENTLOG_INFORMATION_TYPE
// * insertionArgs - 0 or more values to be inserted into the string to be logged
// (>0 only if iStringResourceID contains format arguments (%)).
//
// static
void ProfilingAPIUtility::LogProfEventVA(
int iStringResourceID,
WORD wEventType,
va_list insertionArgs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This loads resource strings, which takes locks.
CAN_TAKE_LOCK;
}
CONTRACTL_END;
StackSString messageFromResource;
if (!messageFromResource.LoadResource(
CCompRC::Debugging,
iStringResourceID
))
{
// Resource not found; should never happen.
return;
}
StackSString messageFromResourceUtf8;
messageFromResource.ConvertToUTF8(messageFromResourceUtf8);
StackSString messageToLog;
messageToLog.VPrintf(messageFromResourceUtf8.GetUTF8(), insertionArgs);
AppendSupplementaryInformation(iStringResourceID, &messageToLog);
#ifdef FEATURE_EVENT_TRACE
if (EventEnabledProfilerMessage())
{
StackSString messageToLogUtf16;
messageToLog.ConvertToUnicode(messageToLogUtf16);
// Write to ETW and EventPipe with the message
FireEtwProfilerMessage(GetClrInstanceId(), messageToLogUtf16.GetUnicode());
}
#endif //FEATURE_EVENT_TRACE
// Output debug strings for diagnostic messages.
OutputDebugStringUtf8(messageToLog.GetUTF8());
}
// See code:ProfilingAPIUtility.LogProfEventVA for description of arguments.
// static
void ProfilingAPIUtility::LogProfError(int iStringResourceID, ...)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This loads resource strings, which takes locks.
CAN_TAKE_LOCK;
}
CONTRACTL_END;
va_list insertionArgs;
va_start(insertionArgs, iStringResourceID);
LogProfEventVA(
iStringResourceID,
EVENTLOG_ERROR_TYPE,
insertionArgs);
va_end(insertionArgs);
}
// See code:ProfilingAPIUtility.LogProfEventVA for description of arguments.
// static
void ProfilingAPIUtility::LogProfInfo(int iStringResourceID, ...)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This loads resource strings, which takes locks.
CAN_TAKE_LOCK;
}
CONTRACTL_END;
va_list insertionArgs;
va_start(insertionArgs, iStringResourceID);
LogProfEventVA(
iStringResourceID,
EVENTLOG_INFORMATION_TYPE,
insertionArgs);
va_end(insertionArgs);
}
#ifdef PROF_TEST_ONLY_FORCE_ELT
// Special forward-declarations of the profiling API's slow-path enter/leave/tailcall
// hooks. These need to be forward-declared here so that they may be referenced in
// InitializeProfiling() below solely for the debug-only, test-only code to allow
// enter/leave/tailcall to be turned on at startup without a profiler. See
// code:ProfControlBlock#TestOnlyELT
EXTERN_C void STDMETHODCALLTYPE ProfileEnterNaked(UINT_PTR clientData);
EXTERN_C void STDMETHODCALLTYPE ProfileLeaveNaked(UINT_PTR clientData);
EXTERN_C void STDMETHODCALLTYPE ProfileTailcallNaked(UINT_PTR clientData);
#endif //PROF_TEST_ONLY_FORCE_ELT
// ----------------------------------------------------------------------------
// ProfilingAPIUtility::InitializeProfiling
//
// This is the top-most level of profiling API initialization, and is called directly by
// EEStartupHelper() (in ceemain.cpp). This initializes internal structures relating to the
// Profiling API. This also orchestrates loading the profiler and initializing it (if
// its GUID is specified in the environment).
//
// Return Value:
// HRESULT indicating success or failure. This is generally very lenient about internal
// failures, as we don't want them to prevent the startup of the app:
// S_OK = Environment didn't request a profiler, or
// Environment did request a profiler, and it was loaded successfully
// S_FALSE = There was a problem loading the profiler, but that shouldn't prevent the app
// from starting up
// else (failure) = There was a serious problem that should be dealt with by the caller
//
// Notes:
// This function (or one of its callees) will log an error to the event log
// if there is a failure
//
// Assumptions:
// InitializeProfiling is called during startup, AFTER the host has initialized its
// settings and the config variables have been read, but BEFORE the finalizer thread
// has entered its first wait state. ASSERTs are placed in
// code:ProfilingAPIAttachDetach::Initialize (which is called by this function, and
// which depends on these assumptions) to verify.
// static
HRESULT ProfilingAPIUtility::InitializeProfiling()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
InitializeLogging();
// NULL out / initialize members of the global profapi structure
g_profControlBlock.Init();
if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableDiagnostics) == 0)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling disabled via EnableDiagnostics config.\n"));
return S_OK;
}
if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableDiagnostics_Profiler) == 0)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling disabled via EnableDiagnostics_Profiler config.\n"));
return S_OK;
}
AttemptLoadProfilerForStartup();
AttemptLoadDelayedStartupProfilers();
AttemptLoadProfilerList();
// For now, the return value from AttemptLoadProfilerForStartup is of no use to us.
// Any event has been logged already by AttemptLoadProfilerForStartup, and
// regardless of whether a profiler got loaded, we still need to continue.
#ifdef PROF_TEST_ONLY_FORCE_ELT
// Test-only, debug-only code to enable ELT on startup regardless of whether a
// startup profiler is loaded. See code:ProfControlBlock#TestOnlyELT.
DWORD dwEnableSlowELTHooks = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_TestOnlyEnableSlowELTHooks);
if (dwEnableSlowELTHooks != 0)
{
(&g_profControlBlock)->fTestOnlyForceEnterLeave = TRUE;
SetJitHelperFunction(CORINFO_HELP_PROF_FCN_ENTER, (void *) ProfileEnterNaked);
SetJitHelperFunction(CORINFO_HELP_PROF_FCN_LEAVE, (void *) ProfileLeaveNaked);
SetJitHelperFunction(CORINFO_HELP_PROF_FCN_TAILCALL, (void *) ProfileTailcallNaked);
LOG((LF_CORPROF, LL_INFO10, "**PROF: Enabled test-only slow ELT hooks.\n"));
}
#endif //PROF_TEST_ONLY_FORCE_ELT
#ifdef PROF_TEST_ONLY_FORCE_OBJECT_ALLOCATED
// Test-only, debug-only code to enable ObjectAllocated callbacks on startup regardless of whether a
// startup profiler is loaded. See code:ProfControlBlock#TestOnlyObjectAllocated.
DWORD dwEnableObjectAllocated = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_TestOnlyEnableObjectAllocatedHook);
if (dwEnableObjectAllocated != 0)
{
(&g_profControlBlock)->fTestOnlyForceObjectAllocated = TRUE;
LOG((LF_CORPROF, LL_INFO10, "**PROF: Enabled test-only object ObjectAllocated hooks.\n"));
}
#endif //PROF_TEST_ONLY_FORCE_ELT
#ifdef _DEBUG
// Test-only, debug-only code to allow attaching profilers to call ICorProfilerInfo interface,
// which would otherwise be disallowed for attaching profilers
DWORD dwTestOnlyEnableICorProfilerInfo = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_TestOnlyEnableICorProfilerInfo);
if (dwTestOnlyEnableICorProfilerInfo != 0)
{
(&g_profControlBlock)->fTestOnlyEnableICorProfilerInfo = TRUE;
}
#endif // _DEBUG
return S_OK;
}
// ----------------------------------------------------------------------------
// ProfilingAPIUtility::ProfilerCLSIDFromString
//
// Description:
// Takes a string form of a CLSID (or progid, believe it or not), and returns the
// corresponding CLSID structure.
//
// Arguments:
// * wszClsid - [in] CLSID string to convert. This may also be a progid. This
// ensures our behavior is backward-compatible with previous CLR versions. I don't
// know why previous versions allowed the user to set a progid in the environment,
// but well whatever. For back-compatibility, we also strip all double-quotes from the passed in ProgId.
// * pClsid - [out] CLSID structure corresponding to wszClsid
//
// Return Value:
// HRESULT indicating success or failure.
//
// Notes:
// * An event is logged if there is a failure.
//
// static
HRESULT ProfilingAPIUtility::ProfilerCLSIDFromString(
__in_z LPCWSTR wszClsid,
CLSID * pClsid)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
_ASSERTE(wszClsid != NULL);
_ASSERTE(pClsid != NULL);
HRESULT hr;
// Translate the string into a CLSID
if (*wszClsid == W('{'))
{
hr = LPCWSTRToGuid(wszClsid, pClsid) ? S_OK : E_FAIL;
}
else
{
#ifndef TARGET_UNIX
SString progId{wszClsid};
for (auto it = progId.Begin(); it != progId.End(); ++it)
{
while (it != progId.End() && *it == W('"'))
{
progId.Delete(it, 1);
}
}
hr = CLSIDFromProgID(progId.GetUnicode(), pClsid);
#else // !TARGET_UNIX
// ProgID not supported on TARGET_UNIX
hr = E_INVALIDARG;
#endif // !TARGET_UNIX
}
if (FAILED(hr))
{
MAKE_UTF8PTR_FROMWIDE(badClsid, wszClsid);
LOG((
LF_CORPROF,
LL_INFO10,
"**PROF: Invalid CLSID or ProgID (%s). hr=0x%x.\n",
badClsid,
hr));
ProfilingAPIUtility::LogProfError(IDS_E_PROF_BAD_CLSID, badClsid, hr);
return hr;
}
return S_OK;
}
// ----------------------------------------------------------------------------
// ProfilingAPIUtility::AttemptLoadProfilerForStartup
//
// Description:
// Checks environment or registry to see if the app is configured to run with a
// profiler loaded on startup. If so, this calls LoadProfiler() to load it up.
//
// Arguments:
//
// Return Value:
// * S_OK: Startup-profiler has been loaded
// * S_FALSE: No profiler is configured for startup load
// * else, HRESULT indicating failure that occurred
//
// Assumptions:
// * This should be called on startup, after g_profControlBlock is initialized, but
// before any attach infrastructure is initialized. This ensures we don't receive
// an attach request while startup-loading a profiler.
//
// Notes:
// * This or its callees will ensure an event is logged on failure (though will be
// silent if no profiler is configured for startup load (which causes S_FALSE to
// be returned)
//
// static
HRESULT ProfilingAPIUtility::AttemptLoadProfilerForStartup()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
HRESULT hr;
// Find out if profiling is enabled
DWORD fProfEnabled = 0;
fProfEnabled = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_ENABLE_PROFILING);
NewArrayHolder<WCHAR> wszClsid(NULL);
NewArrayHolder<WCHAR> wszProfilerDLL(NULL);
CLSID clsid;
if (fProfEnabled == 0)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling not enabled.\n"));
return S_FALSE;
}
LOG((LF_CORPROF, LL_INFO10, "**PROF: Initializing Profiling Services.\n"));
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER, &wszClsid));
#if defined(TARGET_ARM64)
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER_PATH_ARM64, &wszProfilerDLL));
#elif defined(TARGET_ARM)
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER_PATH_ARM32, &wszProfilerDLL));
#endif
if(wszProfilerDLL == NULL)
{
#ifdef TARGET_64BIT
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER_PATH_64, &wszProfilerDLL));
#else
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER_PATH_32, &wszProfilerDLL));
#endif
if(wszProfilerDLL == NULL)
{
IfFailRet(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_PROFILER_PATH, &wszProfilerDLL));
}
}
// If the environment variable doesn't exist, profiling is not enabled.
if (wszClsid == NULL)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling flag set, but required "
"environment variable does not exist.\n"));
LogProfError(IDS_E_PROF_NO_CLSID);
return S_FALSE;
}
if ((wszProfilerDLL != NULL) && (u16_strlen(wszProfilerDLL) >= MAX_LONGPATH))
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling flag set, but CORECLR_PROFILER_PATH was not set properly.\n"));
LogProfError(IDS_E_PROF_BAD_PATH);
return S_FALSE;
}
#ifdef TARGET_UNIX
// If the environment variable doesn't exist, profiling is not enabled.
if (wszProfilerDLL == NULL)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling flag set, but required "
"environment variable does not exist.\n"));
LogProfError(IDS_E_PROF_BAD_PATH);
return S_FALSE;
}
#endif // TARGET_UNIX
hr = ProfilingAPIUtility::ProfilerCLSIDFromString(wszClsid, &clsid);
if (FAILED(hr))
{
// ProfilerCLSIDFromString already logged an event if there was a failure
return hr;
}
char clsidUtf8[GUID_STR_BUFFER_LEN];
GuidToLPSTR(clsid, clsidUtf8);
hr = LoadProfiler(
kStartupLoad,
&clsid,
(LPCSTR)clsidUtf8,
wszProfilerDLL,
NULL, // No client data for startup load
0); // No client data for startup load
if (FAILED(hr))
{
// A failure in either the CLR or the profiler prevented it from
// loading. Event has been logged. Propagate hr
return hr;
}
return S_OK;
}
//static
HRESULT ProfilingAPIUtility::AttemptLoadDelayedStartupProfilers()
{
if (g_profControlBlock.storedProfilers.IsEmpty())
{
return S_OK;
}
HRESULT storedHr = S_OK;
STOREDPROFILERLIST *profilers = &g_profControlBlock.storedProfilers;
for (StoredProfilerNode* item = profilers->GetHead(); item != NULL; item = STOREDPROFILERLIST::GetNext(item))
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiler loading from GUID/Path stored from the IPC channel."));
CLSID *pClsid = &(item->guid);
char clsidUtf8[GUID_STR_BUFFER_LEN];
GuidToLPSTR(*pClsid, clsidUtf8);
HRESULT hr = LoadProfiler(
kStartupLoad,
pClsid,
(LPCSTR)clsidUtf8,
item->path.GetUnicode(),
NULL, // No client data for startup load
0); // No client data for startup load
if (FAILED(hr))
{
// LoadProfiler logs if there is an error
storedHr = hr;
}
}
return storedHr;
}
// static
HRESULT ProfilingAPIUtility::AttemptLoadProfilerList()
{
HRESULT hr = S_OK;
CLRConfigStringHolder wszProfilerList(NULL);
#if defined(TARGET_ARM64)
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_NOTIFICATION_PROFILERS_ARM64, &wszProfilerList);
#elif defined(TARGET_ARM)
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_NOTIFICATION_PROFILERS_ARM32, &wszProfilerList);
#endif
if (wszProfilerList == NULL)
{
#ifdef TARGET_64BIT
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_NOTIFICATION_PROFILERS_64, &wszProfilerList);
#else
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_NOTIFICATION_PROFILERS_32, &wszProfilerList);
#endif
if (wszProfilerList == NULL)
{
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_NOTIFICATION_PROFILERS, &wszProfilerList);
if (wszProfilerList == NULL)
{
// No profiler list specified, bail
return S_OK;
}
}
}
DWORD dwEnabled = CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_CORECLR_ENABLE_NOTIFICATION_PROFILERS);
if (dwEnabled == 0)
{
// Profiler list explicitly disabled, bail
LogProfInfo(IDS_E_PROF_NOTIFICATION_DISABLED);
return S_OK;
}
SString profilerList{wszProfilerList};
HRESULT storedHr = S_OK;
for (SString::Iterator sectionStart = profilerList.Begin(), sectionEnd = profilerList.Begin();
profilerList.Find(sectionEnd, W(';'));
sectionStart = ++sectionEnd)
{
SString::Iterator pathEnd = sectionStart;
if (!profilerList.Find(pathEnd, W('=')) || pathEnd > sectionEnd)
{
ProfilingAPIUtility::LogProfError(IDS_E_PROF_BAD_PATH);
storedHr = E_FAIL;
continue;
}
SString::Iterator clsidStart = pathEnd + 1;
PathString path{profilerList, sectionStart, pathEnd};
StackSString clsidString{profilerList, clsidStart, sectionEnd};
CLSID clsid;
hr = ProfilingAPIUtility::ProfilerCLSIDFromString(clsidString.GetUnicode(), &clsid);
if (FAILED(hr))
{
// ProfilerCLSIDFromString already logged an event if there was a failure
storedHr = hr;
continue;
}
char clsidUtf8[GUID_STR_BUFFER_LEN];
GuidToLPSTR(clsid, clsidUtf8);
hr = LoadProfiler(
kStartupLoad,
&clsid,
(LPCSTR)clsidUtf8,
path.GetUnicode(),
NULL, // No client data for startup load
0); // No client data for startup load
if (FAILED(hr))
{
// LoadProfiler already logged if there was an error
storedHr = hr;
continue;
}
}
return storedHr;
}
//---------------------------------------------------------------------------------------
//
// Performs lazy initialization that need not occur on startup, but does need to occur
// before trying to load a profiler.
//
// Return Value:
// HRESULT indicating success or failure.
//
HRESULT ProfilingAPIUtility::PerformDeferredInit()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
CAN_TAKE_LOCK;
MODE_ANY;
}
CONTRACTL_END;
#ifdef FEATURE_PROFAPI_ATTACH_DETACH
// Initialize internal resources for detaching
HRESULT hr = ProfilingAPIDetach::Initialize();
if (FAILED(hr))
{
LOG((
LF_CORPROF,
LL_ERROR,
"**PROF: Unable to initialize resources for detaching. hr=0x%x.\n",
hr));
return hr;
}
#endif // FEATURE_PROFAPI_ATTACH_DETACH
if (s_csStatus == NULL)
{
s_csStatus = ClrCreateCriticalSection(
CrstProfilingAPIStatus,
(CrstFlags) (CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));
if (s_csStatus == NULL)
{
return E_OUTOFMEMORY;
}
}
return S_OK;
}
// static
HRESULT ProfilingAPIUtility::DoPreInitialization(
EEToProfInterfaceImpl *pEEProf,
const CLSID *pClsid,
LPCSTR szClsid,
LPCWSTR wszProfilerDLL,
LoadType loadType,
DWORD dwConcurrentGCWaitTimeoutInMs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_ANY;
PRECONDITION(pEEProf != NULL);
PRECONDITION(pClsid != NULL);
PRECONDITION(szClsid != NULL);
}
CONTRACTL_END;
_ASSERTE(s_csStatus != NULL);
ProfilerCompatibilityFlag profilerCompatibilityFlag = kDisableV2Profiler;
NewArrayHolder<WCHAR> wszProfilerCompatibilitySetting(NULL);
if (loadType == kStartupLoad)
{
CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_ProfAPI_ProfilerCompatibilitySetting, &wszProfilerCompatibilitySetting);
if (wszProfilerCompatibilitySetting != NULL)
{
if (SString::_wcsicmp(wszProfilerCompatibilitySetting, W("EnableV2Profiler")) == 0)
{
profilerCompatibilityFlag = kEnableV2Profiler;
}
else if (SString::_wcsicmp(wszProfilerCompatibilitySetting, W("PreventLoad")) == 0)
{
profilerCompatibilityFlag = kPreventLoad;
}
}
if (profilerCompatibilityFlag == kPreventLoad)
{
LOG((LF_CORPROF, LL_INFO10, "**PROF: DOTNET_ProfAPI_ProfilerCompatibilitySetting is set to PreventLoad. "
"Profiler will not be loaded.\n"));
MAKE_UTF8PTR_FROMWIDE(szEnvVarName, CLRConfig::EXTERNAL_ProfAPI_ProfilerCompatibilitySetting.name);
MAKE_UTF8PTR_FROMWIDE(szEnvVarValue, wszProfilerCompatibilitySetting.GetValue());
LogProfInfo(IDS_PROF_PROFILER_DISABLED,
szEnvVarName,
szEnvVarValue,
szClsid);
return S_OK;
}
}
HRESULT hr = S_OK;
NewHolder<ProfToEEInterfaceImpl> pProfEE(new (nothrow) ProfToEEInterfaceImpl());
if (pProfEE == NULL)
{
LOG((LF_CORPROF, LL_ERROR, "**PROF: Unable to allocate ProfToEEInterfaceImpl.\n"));
LogProfError(IDS_E_PROF_INTERNAL_INIT, szClsid, E_OUTOFMEMORY);
return E_OUTOFMEMORY;
}
// Initialize the interface
hr = pProfEE->Init();
if (FAILED(hr))
{
LOG((LF_CORPROF, LL_ERROR, "**PROF: ProfToEEInterface::Init failed.\n"));
LogProfError(IDS_E_PROF_INTERNAL_INIT, szClsid, hr);
return hr;
}
// Provide the newly created and inited interface
LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling code being provided with EE interface.\n"));
#ifdef FEATURE_PROFAPI_ATTACH_DETACH
// We're about to load the profiler, so first make sure we successfully create the
// DetachThread and abort the load of the profiler if we can't. This ensures we don't
// load a profiler unless we're prepared to detach it later.
hr = ProfilingAPIDetach::CreateDetachThread();
if (FAILED(hr))
{
LOG((
LF_CORPROF,
LL_ERROR,
"**PROF: Unable to create DetachThread. hr=0x%x.\n",
hr));
ProfilingAPIUtility::LogProfError(IDS_E_PROF_INTERNAL_INIT, szClsid, hr);
return hr;
}
#endif // FEATURE_PROFAPI_ATTACH_DETACH
// Initialize internal state of our EEToProfInterfaceImpl. This also loads the
// profiler itself, but does not yet call its Initialize() callback
hr = pEEProf->Init(pProfEE, pClsid, szClsid, wszProfilerDLL, (loadType == kAttachLoad), dwConcurrentGCWaitTimeoutInMs);
if (FAILED(hr))
{
LOG((LF_CORPROF, LL_ERROR, "**PROF: EEToProfInterfaceImpl::Init failed.\n"));