forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheetoprofinterfaceimpl.cpp
6126 lines (4991 loc) · 192 KB
/
eetoprofinterfaceimpl.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.
//
// EEToProfInterfaceImpl.cpp
//
//
// This module implements wrappers around calling the profiler's
// ICorProfilerCallaback* interfaces. When code in the EE needs to call the
// profiler, it goes through EEToProfInterfaceImpl to do so.
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE!
//
// PLEASE READ!
//
// There are strict rules for how to implement ICorProfilerCallback* wrappers. Please read
// https://github.com/dotnet/runtime/blob/main/docs/design/coreclr/botr/profilability.md
// to understand the rules and why they exist.
//
// As a reminder, here is a short summary of your responsibilities. Every PUBLIC
// ENTRYPOINT (from EE to profiler) must have:
//
// - An entrypoint macro at the top. Your choices are:
// CLR_TO_PROFILER_ENTRYPOINT (typical choice)
// This is used for calling ICorProfilerCallback* methods that either have no
// ThreadID parameters, or if they do have a ThreadID parameter, the parameter's
// value is always the *current* ThreadID (i.e., param == GetThreadNULLOk()). This will
// also force a mode switch to preemptive before calling the profiler.
// CLR_TO_PROFILER_ENTRYPOINT_FOR_THREAD
// Similar to above, except these are used for ICorProfilerCallback* methods that
// specify a ThreadID parameter whose value may not always be the *current*
// ThreadID. You must specify the ThreadID as the first parameter to these
// macros. The macro will then use your ThreadID rather than that of the current
// GetThreadNULLOk(), to assert that the callback is currently allowed for that
// ThreadID (i.e., that we have not yet issued a ThreadDestroyed() for that
// ThreadID).
//
// - A complete contract block with comments over every contract choice. Wherever
// possible, use the preferred contracts (if not possible, you must comment why):
// NOTHROW
// All callbacks are really NOTHROW, but that's enforced partially by
// the profiler, whose try/catch blocks aren't visible to the
// contract system. So you'll need to put a scoped
// PERMANENT_CONTRACT_VIOLATION(ThrowsViolation, ReasonProfilerCallout)
// around the call to the profiler
// GC_TRIGGERS
// MODE_PREEMPTIVE (MODE_COOPERATIVE if passing an ObjectID)
// If you use MODE_ANY, you must comment why you don't want an exact mode.
// CAN_TAKE_LOCK
// ASSERT_NO_EE_LOCKS_HELD()
// Note that the preferred contracts in this file are DIFFERENT than the preferred
// contracts for proftoeeinterfaceimpl.cpp.
//
// Private helper functions in this file do not have the same preferred contracts as
// public entrypoints, and they should be contracted following the same guidelines
// as per the rest of the EE.
//
// NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// ======================================================================================
#include "common.h"
#ifdef PROFILING_SUPPORTED
#include "eetoprofinterfaceimpl.h"
#include "eetoprofinterfaceimpl.inl"
#include "contract.h"
#include "proftoeeinterfaceimpl.h"
#include "proftoeeinterfaceimpl.inl"
#include "profilinghelper.inl"
#include "profdetach.h"
#include "simplerwlock.hpp"
#include "eeconfig.h"
#ifdef FEATURE_PERFTRACING
#include "eventpipeadapter.h"
#endif // FEATURE_PERFTRACING
//---------------------------------------------------------------------------------------
// Helpers
// Bitmask of flags that may be passed to the CLR_TO_PROFILER_ENTRYPOINT* macros
// to constrain when the callback may be issued
enum ClrToProfEntrypointFlags
{
// Default
kEE2PNone = 0x00000000,
// Callback is allowable even for detaching profilers
kEE2PAllowableWhileDetaching = 0x00000001,
// Callback is allowable even for initializing profilers
kEE2PAllowableWhileInitializing = 0x00000002,
// Callback is made while in a GC_NOTRIGGER contract. Whereas contracts are
// debug-only, this flag is used in retail builds as well.
kEE2PNoTrigger = 0x00000004,
};
EvacuationCounterHolder::EvacuationCounterHolder(ProfilerInfo *pProfilerInfo) :
m_pProfilerInfo(pProfilerInfo),
m_pThread(GetThreadNULLOk())
{
_ASSERTE(m_pProfilerInfo != NULL);
if (m_pThread == NULL)
{
return;
}
m_pThread->IncProfilerEvacuationCounter(m_pProfilerInfo->slot);
}
EvacuationCounterHolder::~EvacuationCounterHolder()
{
if (m_pThread == NULL)
{
return;
}
m_pThread->DecProfilerEvacuationCounter(m_pProfilerInfo->slot);
}
#define ASSERT_EVAC_COUNTER_NONZERO() \
_ASSERTE((GetThreadNULLOk() == NULL) || \
(GetThread()->GetProfilerEvacuationCounter(m_pProfilerInfo->slot) > 0))
#define CHECK_PROFILER_STATUS(ee2pFlags) \
/* If one of these asserts fires, perhaps you forgot to use */ \
/* BEGIN/END_PROFILER_CALLBACK */ \
ASSERT_EVAC_COUNTER_NONZERO(); \
/* Either we are initializing, or we have the ProfToEEInterfaceImpl */ \
_ASSERTE((((ee2pFlags) & kEE2PAllowableWhileInitializing) != 0) || (m_pProfilerInfo->pProfInterface.Load() != NULL)); \
/* If we are initializing, null is fine. Otherwise we want to make sure we haven't messed up the association between */ \
/* EEToProfInterfaceImpl/ProfToEEInterfaceImpl somehow. */ \
_ASSERTE((((ee2pFlags) & kEE2PAllowableWhileInitializing) != 0) || (m_pProfilerInfo->pProfInterface == this)); \
/* Early abort if... */ \
if ( \
/* Profiler isn't active, */ \
!CORProfilerPresent() && \
\
/* and it's not the case that both a) this callback is allowed */ \
/* on a detaching profiler, and b) the profiler is detaching */ \
!( \
(((ee2pFlags) & kEE2PAllowableWhileDetaching) != 0) && \
(m_pProfilerInfo->curProfStatus.Get() == kProfStatusDetaching) \
) && \
\
/* and it's not the case that both a) this callback is allowed */ \
/* on an initializing profiler, and b) the profiler is initializing */ \
!( \
(((ee2pFlags) & kEE2PAllowableWhileInitializing) != 0) && \
( \
(m_pProfilerInfo->curProfStatus.Get() \
== kProfStatusInitializingForStartupLoad) || \
(m_pProfilerInfo->curProfStatus.Get() \
== kProfStatusInitializingForAttachLoad) \
) \
) \
) \
{ \
return S_OK; \
}
// Least common denominator for the callback wrappers. Logs, records in EE Thread object
// that we're in a callback, and asserts that we're allowed to issue callbacks for the
// specified ThreadID (i.e., no ThreadDestroyed callback has been issued for the
// ThreadID).
//
#define CLR_TO_PROFILER_ENTRYPOINT_FOR_THREAD_EX(ee2pFlags, threadId, logParams) \
INCONTRACT(AssertTriggersContract(!((ee2pFlags) & kEE2PNoTrigger))); \
CHECK_PROFILER_STATUS(ee2pFlags); \
LOG(logParams); \
_ASSERTE(m_pCallback2 != NULL); \
/* Normally, set COR_PRF_CALLBACKSTATE_INCALLBACK | */ \
/* COR_PRF_CALLBACKSTATE_IN_TRIGGERS_SCOPE in the callback state, but omit */ \
/* COR_PRF_CALLBACKSTATE_IN_TRIGGERS_SCOPE if we're in a GC_NOTRIGGERS callback */ \
SetCallbackStateFlagsHolder __csf( \
(((ee2pFlags) & kEE2PNoTrigger) != 0) ? \
COR_PRF_CALLBACKSTATE_INCALLBACK : \
COR_PRF_CALLBACKSTATE_INCALLBACK | COR_PRF_CALLBACKSTATE_IN_TRIGGERS_SCOPE \
); \
_ASSERTE(ProfilerCallbacksAllowedForThread((Thread *) (threadId)))
#define CLR_TO_PROFILER_ENTRYPOINT_EX(ee2pFlags, logParams) \
CLR_TO_PROFILER_ENTRYPOINT_FOR_THREAD_EX(ee2pFlags, GetThreadNULLOk(), logParams)
// Typical entrypoint macro you'll use. Checks that we're allowed to issue
// callbacks for the current thread (i.e., no ThreadDestroyed callback has been
// issued for the current thread).
#define CLR_TO_PROFILER_ENTRYPOINT(logParams) \
CLR_TO_PROFILER_ENTRYPOINT_EX(kEE2PNone, logParams)
#define CLR_TO_PROFILER_ENTRYPOINT_FOR_THREAD(threadId, logParams) \
CLR_TO_PROFILER_ENTRYPOINT_FOR_THREAD_EX(kEE2PNone, threadId, logParams)
//---------------------------------------------------------------------------------------
//
// Wrapper around Thread::ProfilerCallbacksAllowed
//
// Arguments:
// pThread - Thread on which we need to determine whether callbacks are allowed
//
// Return Value:
// TRUE if the profiler portion has marked this thread as allowable, else FALSE.
//
inline BOOL ProfilerCallbacksAllowedForThread(Thread * pThread)
{
WRAPPER_NO_CONTRACT;
return ((pThread == NULL) || (pThread->ProfilerCallbacksAllowed()));
}
//---------------------------------------------------------------------------------------
//
// Wrapper around Thread::SetProfilerCallbacksAllowed
//
// Arguments:
// pThread - Thread on which we're setting whether callbacks shall be allowed
// fValue - The value to store.
//
inline void SetProfilerCallbacksAllowedForThread(Thread * pThread, BOOL fValue)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(pThread != NULL);
pThread->SetProfilerCallbacksAllowed(fValue);
}
//---------------------------------------------------------------------------------------
//
// Low-level function to find and CoCreateInstance the profiler's DLL. Called when
// initializing via EEToProfInterfaceImpl::Init()
//
// Arguments:
// * pClsid - [in] Profiler's CLSID
// * szClsid - [in] String form of CLSID or progid of profiler to load.
// * wszProfileDLL - [in] Path to profiler DLL
// * ppCallback - [out] Pointer to profiler's ICorProfilerCallback2 interface
// * phmodProfilerDLL - [out] HMODULE of profiler's DLL.
//
// Return Value:
// HRESULT indicating success or failure.
//
// Notes:
// * This function (or one of its callees) will log an error to the event log if
// there is a failure
static HRESULT CoCreateProfiler(
const CLSID * pClsid,
_In_z_ LPCSTR szClsid,
_In_z_ LPCWSTR wszProfileDLL,
ICorProfilerCallback2 ** ppCallback,
HMODULE * phmodProfilerDLL)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
} CONTRACTL_END;
_ASSERTE(pClsid != NULL);
_ASSERTE(szClsid != NULL);
_ASSERTE(ppCallback != NULL);
_ASSERTE(phmodProfilerDLL != NULL);
LOG((LF_CORPROF, LL_INFO10, "**PROF: Entered CoCreateProfiler.\n"));
HRESULT hr;
*phmodProfilerDLL = NULL;
// This is the ICorProfilerCallback2 ptr we get back from the profiler's class
// factory's CreateInstance()
ReleaseHolder<ICorProfilerCallback2> pCallback2FromCreateInstance;
// This is the ICorProfilerCallback2 ptr we get back from the profiler's QI (see its
// first use below for an explanation on why this is necessary).
ReleaseHolder<ICorProfilerCallback2> pCallback2FromQI;
// Create an instance of the profiler
hr = FakeCoCreateInstanceEx(*pClsid,
wszProfileDLL,
IID_ICorProfilerCallback2,
(LPVOID *) &pCallback2FromCreateInstance,
phmodProfilerDLL);
// (pCallback2FromCreateInstance == NULL) should be considered an error!
if ((pCallback2FromCreateInstance == NULL) && SUCCEEDED(hr))
{
hr = E_NOINTERFACE;
}
if (hr == E_NOINTERFACE)
{
// Helpful message for a potentially common problem
ProfilingAPIUtility::LogNoInterfaceError(IID_ICorProfilerCallback2, szClsid);
}
else if (hr == CORPROF_E_PROFILER_CANCEL_ACTIVATION)
{
// Profiler didn't encounter a bad error, but is voluntarily choosing not to
// profile this runtime. Profilers that need to set system environment
// variables to be able to profile services may use this HRESULT to avoid
// profiling all the other managed apps on the box.
ProfilingAPIUtility::LogProfInfo(IDS_PROF_CANCEL_ACTIVATION, szClsid);
}
else if (FAILED(hr))
{
// Catch-all error for other CoCreateInstance failures
ProfilingAPIUtility::LogProfError(IDS_E_PROF_CCI_FAILED, szClsid, hr);
}
// Now that hr is normalized (set to error if pCallback2FromCreateInstance == NULL),
// LOG and abort if there was a problem.
if (FAILED(hr))
{
LOG((
LF_CORPROF,
LL_INFO10,
"**PROF: Unable to CoCreateInstance profiler class %s. hr=0x%x.\n",
szClsid,
hr));
return hr;
}
// Redundantly QI for ICorProfilerCallback2. This keeps CLR behavior consistent
// with Whidbey, and works around the following bug in some profilers' class factory
// CreateInstance:
// * CreateInstance() ignores the IID it's given
// * CreateInstance() returns a pointer to the object it created, even though
// that object might not support the IID passed to CreateInstance().
// Whidbey CLR worked around this problem by redundantly QI'ing for the same IID
// again after CreateInstance() returned. In this redudant QI, the profiler code would
// finally realize it didn't support that IID, and return an error there. Without
// the redundant QI, the CLR would accept what it got from CreateInstance(), and
// start calling into it using the unsupported interface's vtable, which would
// cause an AV.
//
// There were many MSDN samples (for example
// http://msdn.microsoft.com/msdnmag/issues/03/01/NETProfilerAPI/) which
// unfortunately had this CreateInstance() bug, so many profilers might have been
// generated based on this code. Since it's easy & cheap to work around the
// problem, we do so here with the redundant QI.
hr = pCallback2FromCreateInstance->QueryInterface(
IID_ICorProfilerCallback2,
(LPVOID *) &pCallback2FromQI);
// (pCallback2FromQI == NULL) should be considered an error!
if ((pCallback2FromQI == NULL) && SUCCEEDED(hr))
{
hr = E_NOINTERFACE;
}
// Any error at this stage implies IID_ICorProfilerCallback2 is not supported
if (FAILED(hr))
{
// Helpful message for a potentially common problem
ProfilingAPIUtility::LogNoInterfaceError(IID_ICorProfilerCallback2, szClsid);
return hr;
}
// Ok, safe to transfer ownership to caller's [out] param
*ppCallback = pCallback2FromQI.Extract();
pCallback2FromQI = NULL;
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Implementation of CHashTableImpl functions. This class a simple implementation of
// CHashTable to provide a very simple implementation of the Cmp pure virtual function
//
EEToProfInterfaceImpl::CHashTableImpl::CHashTableImpl(ULONG iBuckets)
: CHashTable(iBuckets)
{
WRAPPER_NO_CONTRACT;
}
EEToProfInterfaceImpl::CHashTableImpl::~CHashTableImpl()
{
WRAPPER_NO_CONTRACT;
}
//---------------------------------------------------------------------------------------
//
// Comparison function for hash table of ClassIDs
//
// Arguments:
// pc1 - hash key to compare
// pc2 - hash value to compare
//
// Return Value:
// TRUE if the key & value refer to the same ClassID; otherwise FALSE
//
BOOL EEToProfInterfaceImpl::CHashTableImpl::Cmp(SIZE_T k1, const HASHENTRY * pc2)
{
LIMITED_METHOD_CONTRACT;
ClassID key = (ClassID) k1;
ClassID val = ((CLASSHASHENTRY *)pc2)->m_clsId;
return (key != val);
}
//---------------------------------------------------------------------------------------
// Private maintenance functions for initialization, cleanup, etc.
EEToProfInterfaceImpl::AllocByClassData *EEToProfInterfaceImpl::m_pSavedAllocDataBlock = NULL;
//---------------------------------------------------------------------------------------
//
// EEToProfInterfaceImpl ctor just sets initial values
//
EEToProfInterfaceImpl::EEToProfInterfaceImpl() :
m_pCallback2(NULL),
m_pCallback3(NULL),
m_pCallback4(NULL),
m_pCallback5(NULL),
m_pCallback6(NULL),
m_pCallback7(NULL),
m_pCallback8(NULL),
m_pCallback9(NULL),
m_pCallback10(NULL),
m_pCallback11(NULL),
m_hmodProfilerDLL(NULL),
m_fLoadedViaAttach(FALSE),
m_pProfToEE(NULL),
m_pProfilersFuncIDMapper(NULL),
m_pProfilersFuncIDMapper2(NULL),
m_pProfilersFuncIDMapper2ClientData(NULL),
m_pGCRefDataFreeList(NULL),
m_csGCRefDataFreeList(NULL),
m_pEnter(NULL),
m_pLeave(NULL),
m_pTailcall(NULL),
m_pEnter2(NULL),
m_pLeave2(NULL),
m_pTailcall2(NULL),
m_fIsClientIDToFunctionIDMappingEnabled(TRUE),
m_pEnter3(NULL),
m_pLeave3(NULL),
m_pTailcall3(NULL),
m_pEnter3WithInfo(NULL),
m_pLeave3WithInfo(NULL),
m_pTailcall3WithInfo(NULL),
m_fUnrevertiblyModifiedIL(FALSE),
m_fModifiedRejitState(FALSE),
m_pProfilerInfo(NULL),
m_pFunctionIDHashTable(NULL),
m_pFunctionIDHashTableRWLock(NULL),
m_dwConcurrentGCWaitTimeoutInMs(INFINITE),
m_bHasTimedOutWaitingForConcurrentGC(FALSE)
{
// Also NULL out this static. (Note: consider making this a member variable.)
m_pSavedAllocDataBlock = NULL;
LIMITED_METHOD_CONTRACT;
}
//
//---------------------------------------------------------------------------------------
//
// Post-constructor initialization of EEToProfInterfaceImpl. Sets everything up,
// including creating the profiler.
//
// Parameters:
// * pProfToEE - A newly-created ProfToEEInterfaceImpl instance that will be passed
// to the profiler as the ICorProfilerInfo3 interface implementation.
// * pClsid - Profiler's CLSID
// * szClsid - String form of CLSID or progid of profiler to load
// * wszProfileDLL - Path to profiler DLL
// * fLoadedViaAttach - TRUE iff the profiler is being attach-loaded (else
// profiler is being startup-loaded)
//
// Return Value:
// HRESULT indicating success or failure.
//
// Notes:
// This function (or one of its callees) will log an error to the event log if there
// is a failure
//
HRESULT EEToProfInterfaceImpl::Init(
ProfToEEInterfaceImpl * pProfToEE,
const CLSID * pClsid,
_In_z_ LPCSTR szClsid,
_In_z_ LPCWSTR wszProfileDLL,
BOOL fLoadedViaAttach,
DWORD dwConcurrentGCWaitTimeoutInMs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
HRESULT hr = E_UNEXPECTED;
_ASSERTE(pProfToEE != NULL);
m_fLoadedViaAttach = fLoadedViaAttach;
m_dwConcurrentGCWaitTimeoutInMs = dwConcurrentGCWaitTimeoutInMs;
// The rule sez your Crst should switch to preemptive when it's taken. We intentionally
// break this rule with CRST_UNSAFE_ANYMODE, because this Crst is taken DURING A GC
// (see AllocateMovedReferencesData(), called by MovedReference(), called by the GC),
// and we don't want to be switching modes in the middle of a GC! Indeed, on server there
// may not even be a mode in the first place.
CRITSEC_AllocationHolder csGCRefDataFreeList(ClrCreateCriticalSection(CrstProfilerGCRefDataFreeList, CRST_UNSAFE_ANYMODE));
if (csGCRefDataFreeList == NULL)
{
LOG((LF_CORPROF,
LL_ERROR,
"**PROF: Failed to create Crst during initialization.\n"));
// A specialized event log entry for this failure would be confusing and
// unhelpful. So just log a generic internal failure event
ProfilingAPIUtility::LogProfError(IDS_E_PROF_INTERNAL_INIT, szClsid, E_FAIL);
return E_FAIL;
}
// CEEInfo::GetProfilingHandle will be PREEMPTIVE mode when trying to update
// m_pFunctionIDHashTable while ProfileEnter, ProfileLeave and ProfileTailcall
// and LookupClientIDFromCache all will be in COOPERATIVE mode when trying
// to read m_pFunctionIDHashTable, so pFunctionIDHashTableRWLock must be created
// with COOPERATIVE_OR_PREEMPTIVE. It is safe to so do because FunctionIDHashTable,
// synchronized by m_pFunctionIDHashTableRWLock runs only native code and uses
// only native heap.
NewHolder<SimpleRWLock> pFunctionIDHashTableRWLock(new (nothrow) SimpleRWLock(COOPERATIVE_OR_PREEMPTIVE, LOCK_TYPE_DEFAULT));
NewHolder<FunctionIDHashTable> pFunctionIDHashTable(new (nothrow) FunctionIDHashTable());
if ((pFunctionIDHashTable == NULL) || (pFunctionIDHashTableRWLock == NULL))
{
LOG((LF_CORPROF,
LL_ERROR,
"**PROF: Failed to create FunctionIDHashTable or FunctionIDHashTableRWLock during initialization.\n"));
// A specialized event log entry for this failure would be confusing and
// unhelpful. So just log a generic internal failure event
ProfilingAPIUtility::LogProfError(IDS_E_PROF_INTERNAL_INIT, szClsid, E_OUTOFMEMORY);
return E_OUTOFMEMORY;
}
// This wraps the following profiler calls in a try / catch:
// * ClassFactory::CreateInstance
// * AddRef/Release/QueryInterface
// Although most profiler calls are not protected, these creation calls are
// protected here since it's cheap to do so (this is only done once per load of a
// profiler), and it would be nice to avoid tearing down the entire process when
// attaching a profiler that may pass back bogus vtables.
EX_TRY
{
// CoCreate the profiler (but don't call its Initialize() method yet)
hr = CreateProfiler(pClsid, szClsid, wszProfileDLL);
}
EX_CATCH
{
hr = E_UNEXPECTED;
ProfilingAPIUtility::LogProfError(IDS_E_PROF_UNHANDLED_EXCEPTION_ON_LOAD, szClsid);
}
// Intentionally swallowing all exceptions, as we don't want a poorly-written
// profiler that throws or AVs on attach to cause the entire process to go away.
EX_END_CATCH(SwallowAllExceptions);
if (FAILED(hr))
{
// CreateProfiler (or catch clause above) has already logged an event to the
// event log on failure
return hr;
}
m_pProfToEE = pProfToEE;
m_csGCRefDataFreeList = csGCRefDataFreeList.Extract();
csGCRefDataFreeList = NULL;
m_pFunctionIDHashTable = pFunctionIDHashTable.Extract();
pFunctionIDHashTable = NULL;
m_pFunctionIDHashTableRWLock = pFunctionIDHashTableRWLock.Extract();
pFunctionIDHashTableRWLock = NULL;
return S_OK;
}
void EEToProfInterfaceImpl::SetProfilerInfo(ProfilerInfo *pProfilerInfo)
{
LIMITED_METHOD_CONTRACT;
m_pProfilerInfo = pProfilerInfo;
m_pProfToEE->SetProfilerInfo(pProfilerInfo);
}
//---------------------------------------------------------------------------------------
//
// This is used by Init() to load the user-specified profiler (but not to call
// its Initialize() method).
//
// Arguments:
// pClsid - Profiler's CLSID
// szClsid - String form of CLSID or progid of profiler to load
// wszProfileDLL - Path to profiler DLL
//
// Return Value:
// HRESULT indicating success / failure. If this is successful, m_pCallback2 will be
// set to the profiler's ICorProfilerCallback2 interface on return. m_pCallback3,4
// will be set to the profiler's ICorProfilerCallback3 interface on return if
// ICorProfilerCallback3,4 is supported.
//
// Assumptions:
// Although the profiler has not yet been instantiated, it is assumed that the internal
// profiling API structures have already been created
//
// Notes:
// This function (or one of its callees) will log an error to the event log
// if there is a failure
HRESULT EEToProfInterfaceImpl::CreateProfiler(
const CLSID * pClsid,
_In_z_ LPCSTR szClsid,
_In_z_ LPCWSTR wszProfileDLL)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
// This causes events to be logged, which loads resource strings,
// which takes locks.
CAN_TAKE_LOCK;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
// Try and CoCreate the registered profiler
ReleaseHolder<ICorProfilerCallback2> pCallback2;
HModuleHolder hmodProfilerDLL;
HRESULT hr = CoCreateProfiler(
pClsid,
szClsid,
wszProfileDLL,
&pCallback2,
&hmodProfilerDLL);
if (FAILED(hr))
{
// CoCreateProfiler logs events to the event log on failures
return hr;
}
// CoCreateProfiler ensures that if it succeeds, we get some valid pointers
_ASSERTE(pCallback2 != NULL);
_ASSERTE(hmodProfilerDLL != NULL);
// Save profiler pointers into this. The reference ownership now
// belongs to this class, so NULL out locals without allowing them to release
m_pCallback2 = pCallback2.Extract();
pCallback2 = NULL;
m_hmodProfilerDLL = hmodProfilerDLL.Extract();
hmodProfilerDLL = NULL;
// ATTENTION: Please update EEToProfInterfaceImpl::~EEToProfInterfaceImpl() after adding the next ICorProfilerCallback interface here !!!
// The profiler may optionally support ICorProfilerCallback3,4,5,6,7,8,9,10,11. Let's check.
ReleaseHolder<ICorProfilerCallback11> pCallback11;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback11,
(LPVOID *)&pCallback11);
if (SUCCEEDED(hr) && (pCallback11 != NULL))
{
_ASSERTE(m_pCallback11 == NULL);
m_pCallback11 = pCallback11.Extract();
pCallback11 = NULL;
}
if (m_pCallback11 == NULL)
{
ReleaseHolder<ICorProfilerCallback10> pCallback10;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback10,
(LPVOID *)&pCallback10);
if (SUCCEEDED(hr) && (pCallback10 != NULL))
{
_ASSERTE(m_pCallback10 == NULL);
m_pCallback10 = pCallback10.Extract();
pCallback10 = NULL;
}
}
else
{
_ASSERTE(m_pCallback10 == NULL);
m_pCallback10 = static_cast<ICorProfilerCallback10 *>(m_pCallback11);
m_pCallback10->AddRef();
}
// Due to inheritance, if we have an interface we must also have
// all the previous versions
if (m_pCallback10 == NULL)
{
ReleaseHolder<ICorProfilerCallback9> pCallback9;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback9,
(LPVOID *)&pCallback9);
if (SUCCEEDED(hr) && (pCallback9 != NULL))
{
_ASSERTE(m_pCallback9 == NULL);
m_pCallback9 = pCallback9.Extract();
pCallback9 = NULL;
}
}
else
{
_ASSERTE(m_pCallback9 == NULL);
m_pCallback9 = static_cast<ICorProfilerCallback9 *>(m_pCallback10);
m_pCallback9->AddRef();
}
if (m_pCallback9 == NULL)
{
ReleaseHolder<ICorProfilerCallback8> pCallback8;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback8,
(LPVOID *)&pCallback8);
if (SUCCEEDED(hr) && (pCallback8 != NULL))
{
_ASSERTE(m_pCallback8 == NULL);
m_pCallback8 = pCallback8.Extract();
pCallback8 = NULL;
}
}
else
{
_ASSERTE(m_pCallback8 == NULL);
m_pCallback8 = static_cast<ICorProfilerCallback8 *>(m_pCallback9);
m_pCallback8->AddRef();
}
if (m_pCallback8 == NULL)
{
ReleaseHolder<ICorProfilerCallback7> pCallback7;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback7,
(LPVOID *)&pCallback7);
if (SUCCEEDED(hr) && (pCallback7 != NULL))
{
_ASSERTE(m_pCallback7 == NULL);
m_pCallback7 = pCallback7.Extract();
pCallback7 = NULL;
}
}
else
{
_ASSERTE(m_pCallback7 == NULL);
m_pCallback7 = static_cast<ICorProfilerCallback7 *>(m_pCallback8);
m_pCallback7->AddRef();
}
if (m_pCallback7 == NULL)
{
ReleaseHolder<ICorProfilerCallback6> pCallback6;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback6,
(LPVOID *)&pCallback6);
if (SUCCEEDED(hr) && (pCallback6 != NULL))
{
_ASSERTE(m_pCallback6 == NULL);
m_pCallback6 = pCallback6.Extract();
pCallback6 = NULL;
}
}
else
{
_ASSERTE(m_pCallback6 == NULL);
m_pCallback6 = static_cast<ICorProfilerCallback6 *>(m_pCallback7);
m_pCallback6->AddRef();
}
if (m_pCallback6 == NULL)
{
ReleaseHolder<ICorProfilerCallback5> pCallback5;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback5,
(LPVOID *)&pCallback5);
if (SUCCEEDED(hr) && (pCallback5 != NULL))
{
_ASSERTE(m_pCallback5 == NULL);
m_pCallback5 = pCallback5.Extract();
pCallback5 = NULL;
}
}
else
{
_ASSERTE(m_pCallback5 == NULL);
m_pCallback5 = static_cast<ICorProfilerCallback5 *>(m_pCallback6);
m_pCallback5->AddRef();
}
if (m_pCallback5 == NULL)
{
ReleaseHolder<ICorProfilerCallback4> pCallback4;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback4,
(LPVOID *)&pCallback4);
if (SUCCEEDED(hr) && (pCallback4 != NULL))
{
_ASSERTE(m_pCallback4 == NULL);
m_pCallback4 = pCallback4.Extract();
pCallback4 = NULL;
}
}
else
{
_ASSERTE(m_pCallback4 == NULL);
m_pCallback4 = static_cast<ICorProfilerCallback4 *>(m_pCallback5);
m_pCallback4->AddRef();
}
if (m_pCallback4 == NULL)
{
ReleaseHolder<ICorProfilerCallback3> pCallback3;
hr = m_pCallback2->QueryInterface(
IID_ICorProfilerCallback3,
(LPVOID *)&pCallback3);
if (SUCCEEDED(hr) && (pCallback3 != NULL))
{
_ASSERTE(m_pCallback3 == NULL);
m_pCallback3 = pCallback3.Extract();
pCallback3 = NULL;
}
}
else
{
_ASSERTE(m_pCallback3 == NULL);
m_pCallback3 = static_cast<ICorProfilerCallback3 *>(m_pCallback4);
m_pCallback3->AddRef();
}
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Performs cleanup for EEToProfInterfaceImpl, including releasing the profiler's
// callback interface. Called on termination of a profiler connection.
//
EEToProfInterfaceImpl::~EEToProfInterfaceImpl()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
// When we release the profiler's callback interface
// below, it may well perform cleanup that takes locks.
// Example: profiler may release a metadata interface, which
// causes it to take a reader lock
CAN_TAKE_LOCK;
}
CONTRACTL_END;
// Make sure there's no pointer about to dangle once we disappear.
// FUTURE: For reattach-with-neutered-profilers feature crew, change this assert to
// scan through list of detaching profilers to make sure none of them give a
// GetEEToProfPtr() equal to this
#ifdef FEATURE_PROFAPI_ATTACH_DETACH
_ASSERTE(!ProfilingAPIDetach::IsEEToProfPtrRegisteredForDetach(this));
#endif // FEATURE_PROFAPI_ATTACH_DETACH
// Release user-specified profiler DLL
// NOTE: If we're tearing down the process, then do nothing related
// to cleaning up the profiler DLL, as the DLL may no longer
// be present.
if (!IsAtProcessExit())
{
if (m_pCallback2 != NULL)
{
m_pCallback2->Release();
m_pCallback2 = NULL;
}
BOOL fIsV4Profiler = (m_pCallback3 != NULL);
if (fIsV4Profiler)
{
m_pCallback3->Release();
m_pCallback3 = NULL;
}
if (m_pCallback4 != NULL)
{
m_pCallback4->Release();
m_pCallback4 = NULL;
}
if (m_pCallback5 != NULL)
{
m_pCallback5->Release();
m_pCallback5 = NULL;
}
if (m_pCallback6 != NULL)
{
m_pCallback6->Release();
m_pCallback6 = NULL;
}
if (m_pCallback7 != NULL)
{
m_pCallback7->Release();
m_pCallback7 = NULL;
}
if (m_pCallback8 != NULL)
{
m_pCallback8->Release();
m_pCallback8 = NULL;
}
if (m_pCallback9 != NULL)
{
m_pCallback9->Release();
m_pCallback9 = NULL;
}
if (m_pCallback10 != NULL)
{
m_pCallback10->Release();
m_pCallback10 = NULL;
}
if (m_pCallback11 != NULL)
{
m_pCallback11->Release();
m_pCallback11 = NULL;
}
// Only unload the V4 profiler if this is not part of shutdown. This protects
// Whidbey profilers that aren't used to being FreeLibrary'd.
if (fIsV4Profiler && !g_fEEShutDown)
{
if (m_hmodProfilerDLL != NULL)
{
FreeLibrary(m_hmodProfilerDLL);
m_hmodProfilerDLL = NULL;
}
// Now that the profiler is destroyed, it is no longer referencing our
// ProfToEEInterfaceImpl, so it's safe to destroy that, too.
if (m_pProfToEE != NULL)
{
delete m_pProfToEE;
m_pProfToEE = NULL;
}
}
}
// Delete the structs associated with GC moved references
while (m_pGCRefDataFreeList)
{
GCReferencesData * pDel = m_pGCRefDataFreeList;
m_pGCRefDataFreeList = m_pGCRefDataFreeList->pNext;
delete pDel;
}
if (m_pSavedAllocDataBlock)
{