This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathproftoeeinterfaceimpl.cpp
10504 lines (8660 loc) · 313 KB
/
proftoeeinterfaceimpl.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.
// See the LICENSE file in the project root for more information.
//
// FILE: ProfToEEInterfaceImpl.cpp
//
// This module implements the ICorProfilerInfo* interfaces, which allow the
// Profiler to communicate with the EE. This allows the Profiler DLL to get
// access to private EE data structures and other things that should never be
// exported outside of the EE.
//
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE! NOTE!
//
// PLEASE READ!
//
// There are strict rules for how to implement ICorProfilerInfo* methods. Please read
// https://github.com/dotnet/coreclr/blob/master/Documentation/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 profiler to EE) must have:
//
// - An entrypoint macro at the top (see code:#P2CLRRestrictionsOverview). Your choices are:
// PROFILER_TO_CLR_ENTRYPOINT_SYNC (typical choice):
// Indicates the method may only be called by the profiler from within
// a callback (from EE to profiler).
// PROFILER_TO_CLR_ENTRYPOINT_CALLABLE_ON_INIT_ONLY
// Even more restrictive, this indicates the method may only be called
// from within the Initialize() callback
// PROFILER_TO_CLR_ENTRYPOINT_ASYNC
// Indicates this method may be called anytime.
// THIS IS DANGEROUS. PLEASE READ ABOVE DOC FOR GUIDANCE ON HOW TO SAFELY
// CODE AN ASYNCHRONOUS METHOD.
// You may use variants of these macros ending in _EX that accept bit flags (see
// code:ProfToClrEntrypointFlags) if you need to specify additional parameters to how
// the entrypoint should behave, though typically you can omit the flags and the
// default (kP2EENone) will be used.
//
// - A complete contract block with comments over every contract choice. Wherever
// possible, use the preferred contracts (if not possible, you must comment why):
// NOTHROW
// GC_NOTRIGGER
// MODE_ANY
// CANNOT_TAKE_LOCK
// SO_NOT_MAINLINE
// (EE_THREAD_(NOT)_REQUIRED are unenforced and are thus optional. If you wish
// to specify these, EE_THREAD_NOT_REQUIRED is preferred.)
// Note that the preferred contracts in this file are DIFFERENT than the preferred
// contracts for eetoprofinterfaceimpl.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!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
//
// #P2CLRRestrictionsOverview
//
// The public ICorProfilerInfo(N) functions below have different restrictions on when
// they're allowed to be called. Listed roughly in order from most to least restrictive:
// * PROFILER_TO_CLR_ENTRYPOINT_CALLABLE_ON_INIT_ONLY: Functions that are only
// allowed to be called while the profiler is initializing on startup, from
// inside the profiler's ICorProfilerCallback::Initialize method
// * PROFILER_TO_CLR_ENTRYPOINT_SYNC: Functions that may be called from within any of
// the profiler's callbacks, or anytime from a thread created by the profiler.
// These functions may only be called by profilers loaded on startup
// * PROFILER_TO_CLR_ENTRYPOINT_SYNC_EX(kP2EEAllowableAfterAttach): Same as above,
// except these may be called by startup AND attaching profilers.
// * PROFILER_TO_CLR_ENTRYPOINT_ASYNC: Functions that may be called at any time and
// from any thread by a profiler loaded on startup
// * PROFILER_TO_CLR_ENTRYPOINT_ASYNC_EX(kP2EEAllowableAfterAttach): Same as above,
// except these may be called by startup AND attaching profilers.
//
// The above restrictions are lifted for certain tests that run with these environment
// variables set. (These are only available on DEBUG builds--including chk--not retail
// builds.)
// * COMPlus_TestOnlyEnableSlowELTHooks:
// * If nonzero, then on startup the runtime will act as if a profiler was loaded
// on startup and requested ELT slow-path (even if no profiler is loaded on
// startup). This will also allow the SetEnterLeaveFunctionHooks(2) info
// functions to be called outside of Initialize(). If a profiler later
// attaches and calls these functions, then the slow-path wrapper will call
// into the profiler's ELT hooks.
// * COMPlus_TestOnlyEnableObjectAllocatedHook:
// * If nonzero, then on startup the runtime will act as if a profiler was loaded
// on startup and requested ObjectAllocated callback (even if no profiler is loaded
// on startup). If a profiler later attaches and calls these functions, then the
// ObjectAllocated notifications will call into the profiler's ObjectAllocated callback.
// * COMPlus_TestOnlyEnableICorProfilerInfo:
// * If nonzero, then attaching profilers allows to call ICorProfilerInfo inteface,
// which would otherwise be disallowed for attaching profilers
// * COMPlus_TestOnlyAllowedEventMask
// * If a profiler needs to work around the restrictions of either
// COR_PRF_ALLOWABLE_AFTER_ATTACH or COR_PRF_MONITOR_IMMUTABLE it may set
// this environment variable. Its value should be a bitmask containing all
// the flags that are:
// * normally immutable or disallowed after attach, AND
// * that the test plans to set after startup and / or by an attaching
// profiler.
//
//
//
// ======================================================================================
#include "common.h"
#include <posterror.h>
#include "proftoeeinterfaceimpl.h"
#include "proftoeeinterfaceimpl.inl"
#include "dllimport.h"
#include "threads.h"
#include "method.hpp"
#include "vars.hpp"
#include "dbginterface.h"
#include "corprof.h"
#include "class.h"
#include "object.h"
#include "ceegen.h"
#include "eeconfig.h"
#include "generics.h"
#include "gcinfo.h"
#include "safemath.h"
#include "threadsuspend.h"
#include "inlinetracking.h"
#ifdef PROFILING_SUPPORTED
#include "profilinghelper.h"
#include "profilinghelper.inl"
#include "eetoprofinterfaceimpl.inl"
#include "profilingenumerators.h"
#endif
#include "profdetach.h"
#include "metadataexports.h"
//---------------------------------------------------------------------------------------
// Helpers
// An OR'd combination of these flags may be specified in the _EX entrypoint macros to
// customize the behavior.
enum ProfToClrEntrypointFlags
{
// Just use the default behavior (this one is used if the non-_EX entrypoint macro is
// specified without any flags).
kP2EENone = 0x00000000,
// By default, Info functions are not allowed to be used by an attaching profiler.
// Specify this flag to override the default.
kP2EEAllowableAfterAttach = 0x00000001,
// This info method has a GC_TRIGGERS contract. Whereas contracts are debug-only,
// this flag is used in retail builds as well.
kP2EETriggers = 0x00000002,
};
// Default versions of the entrypoint macros use kP2EENone if no
// ProfToClrEntrypointFlags are specified
#define PROFILER_TO_CLR_ENTRYPOINT_ASYNC(logParams) \
PROFILER_TO_CLR_ENTRYPOINT_ASYNC_EX(kP2EENone, logParams)
#define PROFILER_TO_CLR_ENTRYPOINT_SYNC(logParams) \
PROFILER_TO_CLR_ENTRYPOINT_SYNC_EX(kP2EENone, logParams)
// ASYNC entrypoints log and ensure an attaching profiler isn't making a call that's
// only supported by startup profilers.
#define CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED_HELPER(p2eeFlags) \
do \
{ \
if ((((p2eeFlags) & kP2EEAllowableAfterAttach) == 0) && \
(g_profControlBlock.pProfInterface->IsLoadedViaAttach())) \
{ \
LOG((LF_CORPROF, \
LL_ERROR, \
"**PROF: ERROR: Returning CORPROF_E_UNSUPPORTED_FOR_ATTACHING_PROFILER " \
"due to a call illegally made by an attaching profiler \n")); \
return CORPROF_E_UNSUPPORTED_FOR_ATTACHING_PROFILER; \
} \
} while(0)
#ifdef _DEBUG
#define CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED(p2eeFlags) \
do \
{ \
if (!((&g_profControlBlock)->fTestOnlyEnableICorProfilerInfo)) \
{ \
CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED_HELPER(p2eeFlags); \
} \
} while(0)
#else //_DEBUG
#define CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED(p2eeFlags) \
do \
{ \
CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED_HELPER(p2eeFlags); \
} while(0)
#endif //_DEBUG
#define PROFILER_TO_CLR_ENTRYPOINT_ASYNC_EX(p2eeFlags, logParams) \
do \
{ \
INCONTRACT(AssertTriggersContract(((p2eeFlags) & kP2EETriggers))); \
_ASSERTE(g_profControlBlock.curProfStatus.Get() != kProfStatusNone); \
LOG(logParams); \
/* If profiler was neutered, disallow call */ \
if (g_profControlBlock.curProfStatus.Get() == kProfStatusDetaching) \
{ \
LOG((LF_CORPROF, \
LL_ERROR, \
"**PROF: ERROR: Returning CORPROF_E_PROFILER_DETACHING " \
"due to a post-neutered profiler call\n")); \
return CORPROF_E_PROFILER_DETACHING; \
} \
CHECK_IF_ATTACHING_PROFILER_IS_ALLOWED(p2eeFlags); \
} while(0)
// SYNC entrypoints must ensure the current EE Thread shows evidence that we're
// inside a callback. If there's no EE Thread, then we automatically "pass"
// the check, and the SYNC call is allowed.
#define PROFILER_TO_CLR_ENTRYPOINT_SYNC_EX(p2eeFlags, logParams) \
do \
{ \
PROFILER_TO_CLR_ENTRYPOINT_ASYNC_EX(p2eeFlags, logParams); \
DWORD __dwExpectedCallbackState = COR_PRF_CALLBACKSTATE_INCALLBACK; \
if (((p2eeFlags) & kP2EETriggers) != 0) \
{ \
__dwExpectedCallbackState |= COR_PRF_CALLBACKSTATE_IN_TRIGGERS_SCOPE; \
} \
if (!AreCallbackStateFlagsSet(__dwExpectedCallbackState)) \
{ \
LOG((LF_CORPROF, \
LL_ERROR, \
"**PROF: ERROR: Returning CORPROF_E_UNSUPPORTED_CALL_SEQUENCE " \
"due to illegal asynchronous profiler call\n")); \
return CORPROF_E_UNSUPPORTED_CALL_SEQUENCE; \
} \
} while(0)
// INIT_ONLY entrypoints must ensure we're executing inside the profiler's
// Initialize() implementation on startup (attach init doesn't count!).
#define PROFILER_TO_CLR_ENTRYPOINT_CALLABLE_ON_INIT_ONLY(logParams) \
do \
{ \
PROFILER_TO_CLR_ENTRYPOINT_ASYNC(logParams); \
if (g_profControlBlock.curProfStatus.Get() != kProfStatusInitializingForStartupLoad && \
g_profControlBlock.curProfStatus.Get() != kProfStatusInitializingForAttachLoad) \
{ \
return CORPROF_E_CALL_ONLY_FROM_INIT; \
} \
} while(0)
// This macro is used to ensure that the current thread is not in a forbid
// suspend region. Some methods are allowed to be called asynchronously,
// but some of them call JIT functions that take a reader lock. So we need to ensure
// the current thread hasn't been hijacked by a profiler while it was holding the writer lock.
// Checking the ForbidSuspendThread region is a sufficient test for this
#define FAIL_IF_IN_FORBID_SUSPEND_REGION() \
do \
{ \
Thread * __pThread = GetThreadNULLOk(); \
if ((__pThread != NULL) && (__pThread->IsInForbidSuspendRegion())) \
{ \
return CORPROF_E_ASYNCHRONOUS_UNSAFE; \
} \
} while(0)
//
// This type is an overlay onto the exported type COR_PRF_FRAME_INFO.
// The first four fields *must* line up with the same fields in the
// exported type. After that, we can add to the end as we wish.
//
typedef struct _COR_PRF_FRAME_INFO_INTERNAL {
USHORT size;
USHORT version;
FunctionID funcID;
UINT_PTR IP;
void *extraArg;
LPVOID thisArg;
} COR_PRF_FRAME_INFO_INTERNAL, *PCOR_PRF_FRAME_INFO_INTERNAL;
//
// After we ship a product with a certain struct type for COR_PRF_FRAME_INFO_INTERNAL
// we have that as a version. If we change that in a later product, we can increment
// the counter below and then we can properly do versioning.
//
#define COR_PRF_FRAME_INFO_INTERNAL_CURRENT_VERSION 1
//---------------------------------------------------------------------------------------
//
// Converts TypeHandle to a ClassID
//
// Arguments:
// th - TypeHandle to convert
//
// Return Value:
// Requested ClassID.
//
ClassID TypeHandleToClassID(TypeHandle th)
{
WRAPPER_NO_CONTRACT;
return reinterpret_cast<ClassID> (th.AsPtr());
}
//---------------------------------------------------------------------------------------
//
// Converts TypeHandle for a non-generic type to a ClassID
//
// Arguments:
// th - TypeHandle to convert
//
// Return Value:
// Requested ClassID. NULL if th represents a generic type
//
#ifdef PROFILING_SUPPORTED
static ClassID NonGenericTypeHandleToClassID(TypeHandle th)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
if ((!th.IsNull()) && (th.HasInstantiation()))
{
return NULL;
}
return TypeHandleToClassID(th);
}
//---------------------------------------------------------------------------------------
//
// Converts MethodDesc * to FunctionID
//
// Arguments:
// pMD - MethodDesc * to convert
//
// Return Value:
// Requested FunctionID
//
static FunctionID MethodDescToFunctionID(MethodDesc * pMD)
{
LIMITED_METHOD_CONTRACT;
return reinterpret_cast< FunctionID > (pMD);
}
#endif
//---------------------------------------------------------------------------------------
//
// Converts FunctionID to MethodDesc *
//
// Arguments:
// functionID - FunctionID to convert
//
// Return Value:
// MethodDesc * requested
//
MethodDesc *FunctionIdToMethodDesc(FunctionID functionID)
{
LIMITED_METHOD_CONTRACT;
MethodDesc *pMethodDesc;
pMethodDesc = reinterpret_cast< MethodDesc* >(functionID);
_ASSERTE(pMethodDesc != NULL);
return pMethodDesc;
}
// (See comments for ArrayKindFromTypeHandle below.)
typedef enum
{
ARRAY_KIND_TYPEDESC, // Normal, garden-variety typedesc array
ARRAY_KIND_METHODTABLE, // Weirdo array with its own unshared methodtable (e.g., System.Object[])
ARRAY_KIND_NOTARRAY, // Not an array
} ARRAY_KIND;
//---------------------------------------------------------------------------------------
//
// A couple Info calls need to understand what constitutes an "array", and what
// kinds of arrays there are. ArrayKindFromTypeHandle tries to put some of this
// knowledge in a single place
//
// Arguments:
// th - TypeHandle to inspect
//
// Return Value:
// ARRAY_KIND describing th
//
inline ARRAY_KIND ArrayKindFromTypeHandle(TypeHandle th)
{
LIMITED_METHOD_CONTRACT;
if (th.IsArray())
{
return ARRAY_KIND_TYPEDESC;
}
if (!th.IsTypeDesc() && th.GetMethodTable()->IsArray())
{
return ARRAY_KIND_METHODTABLE;
}
return ARRAY_KIND_NOTARRAY;
}
#ifdef PROFILING_SUPPORTED
//---------------------------------------------------------------------------------------
// ModuleILHeap IUnknown implementation
//
// Function headers unnecessary, as MSDN adequately documents IUnknown
//
ULONG ModuleILHeap::AddRef()
{
// Lifetime of this object is controlled entirely by the CLR. This
// is created on first request, and is automatically destroyed when
// the profiler is detached.
return 1;
}
ULONG ModuleILHeap::Release()
{
// Lifetime of this object is controlled entirely by the CLR. This
// is created on first request, and is automatically destroyed when
// the profiler is detached.
return 1;
}
HRESULT ModuleILHeap::QueryInterface(REFIID riid, void ** pp)
{
HRESULT hr = S_OK;
if (pp == NULL)
{
return E_POINTER;
}
*pp = 0;
if (riid == IID_IUnknown)
{
*pp = static_cast<IUnknown *>(this);
}
else if (riid == IID_IMethodMalloc)
{
*pp = static_cast<IMethodMalloc *>(this);
}
else
{
hr = E_NOINTERFACE;
}
if (hr == S_OK)
{
// CLR manages lifetime of this object, but in case that changes (or
// this code gets copied/pasted elsewhere), we'll still AddRef here so
// QI remains a good citizen either way.
AddRef();
}
return hr;
}
//---------------------------------------------------------------------------------------
// Profiler entrypoint to allocate space from this module's heap.
//
// Arguments
// cb - size in bytes of allocation request
//
// Return value
// pointer to allocated memory, or NULL if there was an error
void * STDMETHODCALLTYPE ModuleILHeap::Alloc(ULONG cb)
{
CONTRACTL
{
// Yay!
NOTHROW;
// (see GC_TRIGGERS comment below)
CAN_TAKE_LOCK;
// Allocations using loader heaps below enter a critsec, which switches
// to preemptive, which is effectively a GC trigger
GC_TRIGGERS;
// Yay!
MODE_ANY;
SO_NOT_MAINLINE;
}
CONTRACTL_END;
LOG((LF_CORPROF, LL_INFO1000, "**PROF: ModuleILHeap::Alloc 0x%08xp.\n", cb));
if (cb == 0)
{
return NULL;
}
return new (nothrow) BYTE[cb];
}
//---------------------------------------------------------------------------------------
// The one and only instance of the IL heap
ModuleILHeap ModuleILHeap::s_Heap;
//---------------------------------------------------------------------------------------
// Implementation of ProfToEEInterfaceImpl's IUnknown
//
// The VM controls the lifetime of ProfToEEInterfaceImpl, not the
// profiler. We'll automatically take care of cleanup when profilers
// unload and detach.
//
ULONG STDMETHODCALLTYPE ProfToEEInterfaceImpl::AddRef()
{
LIMITED_METHOD_CONTRACT;
return 1;
}
ULONG STDMETHODCALLTYPE ProfToEEInterfaceImpl::Release()
{
LIMITED_METHOD_CONTRACT;
return 1;
}
COM_METHOD ProfToEEInterfaceImpl::QueryInterface(REFIID id, void ** pInterface)
{
if (pInterface == NULL)
{
return E_POINTER;
}
if (id == IID_ICorProfilerInfo)
{
*pInterface = static_cast<ICorProfilerInfo *>(this);
}
else if (id == IID_ICorProfilerInfo2)
{
*pInterface = static_cast<ICorProfilerInfo2 *>(this);
}
else if (id == IID_ICorProfilerInfo3)
{
*pInterface = static_cast<ICorProfilerInfo3 *>(this);
}
else if (id == IID_ICorProfilerInfo4)
{
*pInterface = static_cast<ICorProfilerInfo4 *>(this);
}
else if (id == IID_ICorProfilerInfo5)
{
*pInterface = static_cast<ICorProfilerInfo5 *>(this);
}
else if (id == IID_ICorProfilerInfo6)
{
*pInterface = static_cast<ICorProfilerInfo6 *>(this);
}
else if (id == IID_ICorProfilerInfo7)
{
*pInterface = static_cast<ICorProfilerInfo7 *>(this);
}
else if (id == IID_ICorProfilerInfo8)
{
*pInterface = static_cast<ICorProfilerInfo8 *>(this);
}
else if (id == IID_ICorProfilerInfo9)
{
*pInterface = static_cast<ICorProfilerInfo9 *>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown *>(static_cast<ICorProfilerInfo *>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
// CLR manages lifetime of this object, but in case that changes (or
// this code gets copied/pasted elsewhere), we'll still AddRef here so
// QI remains a good citizen either way.
AddRef();
return S_OK;
}
#endif // PROFILING_SUPPORTED
//---------------------------------------------------------------------------------------
//
// GC-related helpers. These are called from elsewhere in the EE to determine profiler
// state, and to update the profiling API with info from the GC.
//
//---------------------------------------------------------------------------------------
//
// ProfilerObjectAllocatedCallback is called if a profiler is attached, requesting
// ObjectAllocated callbacks.
//
// Arguments:
// objref - Reference to newly-allocated object
// classId - ClassID of newly-allocated object
//
void __stdcall ProfilerObjectAllocatedCallback(OBJECTREF objref, ClassID classId)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
TypeHandle th = OBJECTREFToObject(objref)->GetTypeHandle();
// WARNING: objref can move as a result of the ObjectAllocated() call below if
// the profiler causes a GC, so any operations on the objref should occur above
// this comment (unless you're prepared to add a GCPROTECT around the objref).
#ifdef PROFILING_SUPPORTED
// Notify the profiler of the allocation
{
BEGIN_PIN_PROFILER(CORProfilerTrackAllocations());
// Note that for generic code we always return uninstantiated ClassIDs and FunctionIDs.
// Thus we strip any instantiations of the ClassID (which is really a type handle) here.
g_profControlBlock.pProfInterface->ObjectAllocated(
(ObjectID) OBJECTREFToObject(objref),
classId);
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
}
//---------------------------------------------------------------------------------------
//
// Wrapper around the GC Started callback
//
// Arguments:
// generation - Generation being collected
// induced - Was this GC induced by GC.Collect?
//
void __stdcall GarbageCollectionStartedCallback(int generation, BOOL induced)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY; // can be called even on GC threads
}
CONTRACTL_END;
#ifdef PROFILING_SUPPORTED
//
// Mark that we are starting a GC. This will allow profilers to do limited object inspection
// during callbacks that occur while a GC is happening.
//
g_profControlBlock.fGCInProgress = TRUE;
// Notify the profiler of start of the collection
{
BEGIN_PIN_PROFILER(CORProfilerTrackGC());
BOOL generationCollected[COR_PRF_GC_LARGE_OBJECT_HEAP+1];
if (generation == COR_PRF_GC_GEN_2)
generation = COR_PRF_GC_LARGE_OBJECT_HEAP;
for (int gen = 0; gen <= COR_PRF_GC_LARGE_OBJECT_HEAP; gen++)
generationCollected[gen] = gen <= generation;
g_profControlBlock.pProfInterface->GarbageCollectionStarted(
COR_PRF_GC_LARGE_OBJECT_HEAP+1,
generationCollected,
induced ? COR_PRF_GC_INDUCED : COR_PRF_GC_OTHER);
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
}
//---------------------------------------------------------------------------------------
//
// Wrapper around the GC Finished callback
//
void __stdcall GarbageCollectionFinishedCallback()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY; // can be called even on GC threads
}
CONTRACTL_END;
#ifdef PROFILING_SUPPORTED
// Notify the profiler of end of the collection
{
BEGIN_PIN_PROFILER(CORProfilerTrackGC());
g_profControlBlock.pProfInterface->GarbageCollectionFinished();
END_PIN_PROFILER();
}
// Mark that GC is finished.
g_profControlBlock.fGCInProgress = FALSE;
#endif // PROFILING_SUPPORTED
}
#ifdef PROFILING_SUPPORTED
//---------------------------------------------------------------------------------------
//
// Describes a GC generation by number and address range
//
struct GenerationDesc
{
int generation;
BYTE *rangeStart;
BYTE *rangeEnd;
BYTE *rangeEndReserved;
};
struct GenerationTable
{
ULONG count;
ULONG capacity;
static const ULONG defaultCapacity = 4; // that's the minimum for 3 generation plus the large object heap
GenerationTable *prev;
GenerationDesc *genDescTable;
#ifdef _DEBUG
ULONG magic;
#define GENERATION_TABLE_MAGIC 0x34781256
#define GENERATION_TABLE_BAD_MAGIC 0x55aa55aa
#endif
};
//---------------------------------------------------------------------------------------
//
// This is a callback used by the GC when we call GCHeapUtilities::DiagDescrGenerations
// (from UpdateGenerationBounds() below). The GC gives us generation information through
// this callback, which we use to update the GenerationDesc in the corresponding
// GenerationTable
//
// Arguments:
// context - The containing GenerationTable
// generation - Generation number
// rangeStart - Address where generation starts
// rangeEnd - Address where generation ends
// rangeEndReserved - Address where generation reserved space ends
//
// static
static void GenWalkFunc(void * context,
int generation,
BYTE * rangeStart,
BYTE * rangeEnd,
BYTE * rangeEndReserved)
{
CONTRACT_VOID
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY; // can be called even on GC threads
PRECONDITION(CheckPointer(context));
PRECONDITION(0 <= generation && generation <= 3);
PRECONDITION(CheckPointer(rangeStart));
PRECONDITION(CheckPointer(rangeEnd));
PRECONDITION(CheckPointer(rangeEndReserved));
} CONTRACT_END;
GenerationTable *generationTable = (GenerationTable *)context;
_ASSERTE(generationTable->magic == GENERATION_TABLE_MAGIC);
ULONG count = generationTable->count;
if (count >= generationTable->capacity)
{
ULONG newCapacity = generationTable->capacity == 0 ? GenerationTable::defaultCapacity : generationTable->capacity * 2;
GenerationDesc *newGenDescTable = new (nothrow) GenerationDesc[newCapacity];
if (newGenDescTable == NULL)
{
// if we can't allocate a bigger table, we'll have to ignore this call
RETURN;
}
memcpy(newGenDescTable, generationTable->genDescTable, sizeof(generationTable->genDescTable[0]) * generationTable->count);
delete[] generationTable->genDescTable;
generationTable->genDescTable = newGenDescTable;
generationTable->capacity = newCapacity;
}
_ASSERTE(count < generationTable->capacity);
GenerationDesc *genDescTable = generationTable->genDescTable;
genDescTable[count].generation = generation;
genDescTable[count].rangeStart = rangeStart;
genDescTable[count].rangeEnd = rangeEnd;
genDescTable[count].rangeEndReserved = rangeEndReserved;
generationTable->count = count + 1;
}
// This is the table of generation bounds updated by the gc
// and read by the profiler. So this is a single writer,
// multiple readers scenario.
static GenerationTable *s_currentGenerationTable;
// The generation table is updated atomically by replacing the
// pointer to it. The only tricky part is knowing when
// the old table can be deleted.
static Volatile<LONG> s_generationTableLock;
// This is just so we can assert there's a single writer
#ifdef ENABLE_CONTRACTS
static Volatile<LONG> s_generationTableWriterCount;
#endif
#endif // PROFILING_SUPPORTED
//---------------------------------------------------------------------------------------
//
// This is called from the gc to push a new set of generation bounds
//
void __stdcall UpdateGenerationBounds()
{
CONTRACT_VOID
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY; // can be called even on GC threads
#ifdef PROFILING_SUPPORTED
PRECONDITION(FastInterlockIncrement(&s_generationTableWriterCount) == 1);
POSTCONDITION(FastInterlockDecrement(&s_generationTableWriterCount) == 0);
#endif // PROFILING_SUPPORTED
} CONTRACT_END;
#ifdef PROFILING_SUPPORTED
// Notify the profiler of start of the collection
if (CORProfilerTrackGC())
{
// generate a new generation table
GenerationTable *newGenerationTable = new (nothrow) GenerationTable();
if (newGenerationTable == NULL)
RETURN;
newGenerationTable->count = 0;
newGenerationTable->capacity = GenerationTable::defaultCapacity;
// if there is already a current table, use its count as a guess for the capacity
if (s_currentGenerationTable != NULL)
newGenerationTable->capacity = s_currentGenerationTable->count;
newGenerationTable->prev = NULL;
newGenerationTable->genDescTable = new (nothrow) GenerationDesc[newGenerationTable->capacity];
if (newGenerationTable->genDescTable == NULL)
newGenerationTable->capacity = 0;
#ifdef _DEBUG
newGenerationTable->magic = GENERATION_TABLE_MAGIC;
#endif
// fill in the values by calling back into the gc, which will report
// the ranges by calling GenWalkFunc for each one
IGCHeap *hp = GCHeapUtilities::GetGCHeap();
hp->DiagDescrGenerations(GenWalkFunc, newGenerationTable);
// remember the old table and plug in the new one
GenerationTable *oldGenerationTable = s_currentGenerationTable;
s_currentGenerationTable = newGenerationTable;
// WARNING: tricky code!
//
// We sample the generation table lock *after* plugging in the new table
// We do so using an interlocked operation so the cpu can't reorder
// the write to the s_currentGenerationTable with the increment.
// If the interlocked increment returns 1, we know nobody can be using
// the old table (readers increment the lock before using the table,
// and decrement it afterwards). Any new readers coming in
// will use the new table. So it's safe to delete the old
// table.
// On the other hand, if the interlocked increment returns
// something other than one, we put the old table on a list
// dangling off of the new one. Next time around, we'll try again
// deleting any old tables.
if (FastInterlockIncrement(&s_generationTableLock) == 1)
{
// We know nobody can be using any of the old tables
while (oldGenerationTable != NULL)
{
_ASSERTE(oldGenerationTable->magic == GENERATION_TABLE_MAGIC);
#ifdef _DEBUG
oldGenerationTable->magic = GENERATION_TABLE_BAD_MAGIC;
#endif
GenerationTable *temp = oldGenerationTable;
oldGenerationTable = oldGenerationTable->prev;
delete[] temp->genDescTable;
delete temp;
}
}
else
{
// put the old table on a list
newGenerationTable->prev = oldGenerationTable;
}
FastInterlockDecrement(&s_generationTableLock);
}
#endif // PROFILING_SUPPORTED
RETURN;
}
#ifdef PROFILING_SUPPORTED
//---------------------------------------------------------------------------------------
//
// Determines whether we are in a window to allow object inspection.
//
// Return Value:
// Returns S_OK if we can determine that we are in a window to allow object
// inspection. Otherwise a failure HRESULT is returned
//
HRESULT AllowObjectInspection()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY; // tests for preemptive mode dynamically as its main function so contract enforcement is not appropriate
}
CONTRACTL_END;
//
// Check first to see if we are in the process of doing a GC and presume that the profiler
// is making this object inspection from the same thread that notified of a valid ObjectID.
//
if (g_profControlBlock.fGCInProgress)
{
return S_OK;