-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathFrameStore.cpp
More file actions
1657 lines (1428 loc) · 57.5 KB
/
Copy pathFrameStore.cpp
File metadata and controls
1657 lines (1428 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc.
#include "FrameStore.h"
#include "COMHelpers.h"
#include "DebugInfoStore.h"
#include "IConfiguration.h"
#include "Log.h"
#include "ManagedCodeCache.h"
#include "OpSysTools.h"
#include "shared/src/native-src/com_ptr.h"
#include "shared/src/native-src/dd_filesystem.hpp"
// namespace fs is an alias defined in "dd_filesystem.hpp"
#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))
void StrAppend(std::stringstream& builder, const char* str);
void FixGenericSyntax(WCHAR* name);
void FixGenericSyntax(char* name);
PCCOR_SIGNATURE ParseByte(PCCOR_SIGNATURE pbSig, BYTE* pByte);
FrameStore::FrameStore(ICorProfilerInfo4* pCorProfilerInfo,
IConfiguration* pConfiguration,
IDebugInfoStore* debugInfoStore,
ManagedCodeCache* pManagedCodeCache) :
_pCorProfilerInfo{pCorProfilerInfo},
_pDebugInfoStore{debugInfoStore},
_pManagedCodeCache{pManagedCodeCache},
_cachedItemsSize(0)
{
if (_pManagedCodeCache == nullptr)
{
Log::Info("FrameStore will not rely on ManagedCodeCache to resolve function IDs.");
}
else
{
Log::Info("FrameStore will rely on ManagedCodeCache to resolve function IDs.");
}
}
std::optional<std::pair<HRESULT, FunctionID>> FrameStore::GetFunctionFromIP(uintptr_t instructionPointer)
{
HRESULT hr;
FunctionID functionId;
// On Windows, the call to GetFunctionFromIP can crash:
// We may end up in a situation where the module containing that symbol was just unloaded.
// For linux, we do not have solution yet.
#ifdef _WINDOWS
// Cannot return while in __try/__except (compilation error)
// We need a flag to know if an access violation exception was raised.
bool wasAccessViolationRaised = false;
__try
{
#endif
hr = _pCorProfilerInfo->GetFunctionFromIP((LPCBYTE)instructionPointer, &functionId);
#ifdef _WINDOWS
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
wasAccessViolationRaised = true;
}
if (wasAccessViolationRaised)
{
return std::nullopt;
}
#endif
return {{hr, functionId}};
}
std::pair<bool, FrameInfoView> FrameStore::GetFrame(uintptr_t instructionPointer)
{
static const std::string NotResolvedModuleName("NotResolvedModule");
static const std::string NotResolvedFrame("|lm:Unknown-Assembly |ns: |ct:Unknown-Type |cg: |fn:NotResolvedFrame |fg: |sg:(?)");
static const std::string UnloadedModuleName("UnloadedModule");
static const std::string FakeModuleName("FakeModule");
static const std::string FakeContentionFrame("|lm:Unknown-Assembly |ns: |ct:Unknown-Type |cg: |fn:lock-contention |fg: |sg:(?)");
static const std::string FakeAllocationFrame("|lm:Unknown-Assembly |ns: |ct:Unknown-Type |cg: |fn:allocation |fg: |sg:(?)");
static const std::string UnknownFrameType("|lm:Unknown-Assembly |ns: |ct:Unknown-Type |cg: |fn:Unknown-Frame-Type |fg: |sg:(?)");
// check for fake IPs used in tests
if (instructionPointer <= MaxFakeIP)
{
// switch/case does not support compile-time constants
if (instructionPointer == FrameStore::FakeLockContentionIP)
{
return { true, {FakeModuleName, FakeContentionFrame, "", 0} };
}
else if (instructionPointer == FrameStore::FakeAllocationIP)
{
return { true, {FakeModuleName, FakeAllocationFrame, "", 0} };
}
else if (instructionPointer == FrameStore::UnknownFrameTypeIP)
{
// We log it only when it debug to identify truncated callstack
// Example: during tests
const auto recordFrame = Log::IsDebugEnabled();
return { recordFrame, {FakeModuleName, UnknownFrameType, "", 0} };
}
else
{
return { true, {FakeModuleName, UnknownManagedFrame, "", 0} };
}
}
HRESULT hr;
std::optional<FunctionID> functionId;
if (_pManagedCodeCache == nullptr)
{
std::optional<std::pair<HRESULT, FunctionID>> result = GetFunctionFromIP(instructionPointer);
if (!result.has_value())
{
// Windows-only: GetFunctionFromIP was wrapped in __try/__except and caught an
// SEH exception coming out of the CLR. Surface the frame as resolved
// (isResolved=true) so the existing Windows pipeline keeps its placeholder
// frame rather than silently dropping it.
return {true, {NotResolvedModuleName, NotResolvedFrame, "", 0}};
}
std::tie(hr, functionId) = result.value();
if (FAILED(hr))
{
// IP is not in managed ranges (native frame). Return isResolved=false so
// RawSampleTransformer drops it from the final callstack.
return {false, {NotResolvedModuleName, NotResolvedFrame, "", 0}};
}
}
else
{
functionId = _pManagedCodeCache->GetFunctionId(instructionPointer);
if (!functionId.has_value())
{
// Windows-only: the ICorProfilerInfo::GetFunctionFromIP call inside
// ManagedCodeCache was wrapped in __try/__except and caught an SEH
// exception from the CLR. Keep isResolved=true so the Windows pipeline
// preserves the placeholder frame (legacy semantic).
return {true, {NotResolvedModuleName, NotResolvedFrame, "", 0}};
}
if (functionId.value() == ManagedCodeCache::InvalidFunctionId)
{
// IP is not in managed ranges (native frame). Return isResolved=false so
// RawSampleTransformer drops it from the final callstack.
return {false, {NotResolvedModuleName, NotResolvedFrame, "", 0}};
}
}
auto frameInfo = GetManagedFrame(functionId.value());
return {true, frameInfo};
}
FrameInfoView FrameStore::GetManagedFrame(FunctionID functionId)
{
{
std::lock_guard<std::mutex> lock(_methodsLock);
// Look into the cache first
auto element = _methods.find(functionId);
if (element != _methods.end())
{
return element->second;
}
}
// Get the method generic parameters if any + metadata token + class ID + module ID
// Next, get the method name et type token from metadata API
// Finally, get the type/namespace names
mdToken mdTokenFunc;
ClassID classId;
ModuleID moduleId;
std::unique_ptr<ClassID[]> genericParameters;
ULONG32 genericParametersCount;
if (!GetFunctionInfo(functionId, mdTokenFunc, classId, moduleId, genericParametersCount, genericParameters))
{
return {UnknownManagedAssembly, UnknownManagedFrame, {}, 0};
}
// Use metadata API to get method name
ComPtr<IMetaDataImport2> pMetadataImport;
if (!GetMetadataApi(moduleId, functionId, pMetadataImport))
{
return {UnknownManagedAssembly, UnknownManagedFrame, {}, 0};
}
// method name is resolved first because we also get the mdDefToken of its class
auto [rva, methodName, methodGenericParameters, mdTokenType] = GetMethodName(functionId, pMetadataImport.Get(), mdTokenFunc, genericParametersCount, genericParameters.get());
if (methodName.empty())
{
return {UnknownManagedAssembly, UnknownManagedFrame, {}, 0};
}
// get the method signature
std::string signature = GetMethodSignature(_pCorProfilerInfo, pMetadataImport.Get(), mdTokenType, functionId, mdTokenFunc);
// get type related description (assembly, namespace and type name)
// look into the cache first
TypeDesc* pTypeDesc = nullptr; // if already in the cache
TypeDesc typeDesc; // if needed to be built from a given classId
bool typeInCache = GetCachedTypeDesc(classId, pTypeDesc);
// TODO: would it be interesting to have a (moduleId + mdTokenDef) -> TypeDesc cache for the non cached generic types?
if (!typeInCache)
{
// try to get the type description
if (!BuildTypeDesc(pMetadataImport.Get(), classId, moduleId, mdTokenType, typeDesc, false, nullptr))
{
// This should never happen but in case it happens, we cache the module/frame value.
// It's safe to cache, because there is no reason that the next calls to
// BuildTypeDesc will succeed.
std::lock_guard<std::mutex> lock(_methodsLock);
auto& value = _methods[functionId];
std::stringstream builder;
builder << UnknownManagedType << " |fn:" << std::move(methodName) << " |fg:" << std::move(methodGenericParameters) << " |sg:" << std::move(signature);
value = {UnknownManagedAssembly, builder.str(), "", 0};
// Incrementally track item size
size_t itemSize = value.ModuleName.capacity() + value.Frame.capacity();
_cachedItemsSize.fetch_add(itemSize, std::memory_order_relaxed);
return value;
}
pTypeDesc = &typeDesc;
}
// build the frame from assembly, namespace, type and method names
std::stringstream builder;
if (!pTypeDesc->Assembly.empty())
{
builder << "|lm:" << pTypeDesc->Assembly;
}
builder << " |ns:" << pTypeDesc->Namespace;
builder << " |ct:" << pTypeDesc->Type;
builder << " |cg:" << pTypeDesc->Parameters;
builder << " |fn:" << methodName;
builder << " |fg:" << methodGenericParameters;
builder << " |sg:" << signature;
auto debugInfo = _pDebugInfoStore->Get(moduleId, mdTokenFunc);
std::string managedFrame = builder.str();
{
std::lock_guard<std::mutex> lock(_methodsLock);
// store it into the function cache and return an iterator to the stored elements
auto [it, _] = _methods.emplace(functionId, FrameInfo{pTypeDesc->Assembly, managedFrame, debugInfo.File, debugInfo.StartLine});
// Incrementally track item size
size_t itemSize = it->second.ModuleName.capacity() + it->second.Frame.capacity();
_cachedItemsSize.fetch_add(itemSize, std::memory_order_relaxed);
// first is the key, second is the associated value
return it->second;
}
}
bool FrameStore::GetTypeName(ClassID classId, std::string& name)
{
TypeDesc* pTypeDesc = nullptr;
if (!GetTypeDesc(classId, pTypeDesc))
{
return false;
}
if (pTypeDesc->Namespace.empty())
{
name = pTypeDesc->Type;
}
else
{
name = pTypeDesc->Namespace + "." + pTypeDesc->Type;
}
// generic and array if any
if (!pTypeDesc->Parameters.empty())
{
name += pTypeDesc->Parameters;
}
return true;
}
// FOR ALLOCATIONS RECORDER ONLY
//
// This method is supposed to return a string_view over a string in the types cache
// It is used by the allocations recorder to avoid duplicating type name strings
// For example if 4 instances of MyType are allocated, the string_view for these 4 allocations
// will point to the same "MyType" string.
// This is why it is needed to get a pointer to the TypeDesc held by the cache
bool FrameStore::GetTypeName(ClassID classId, std::string_view& name)
{
std::lock_guard<std::mutex> lock(_fullTypeNamesLock);
auto typeEntry = _fullTypeNames.find(classId);
if (typeEntry != _fullTypeNames.end())
{
// ensure that the string_view is pointing to the string in the cache
name = {typeEntry->second.data(), typeEntry->second.size()};
return true;
}
TypeDesc* pTypeDesc = nullptr;
if (!GetTypeDesc(classId, pTypeDesc))
{
return false;
}
// ensure that the string_view is pointing to the string in the cache
auto& entry = _fullTypeNames[classId];
entry = pTypeDesc->Type + pTypeDesc->Parameters;
name = {entry.data(), entry.size()};
// Incrementally track item size
_cachedItemsSize.fetch_add(entry.capacity(), std::memory_order_relaxed);
return true;
}
bool FrameStore::GetCachedTypeDesc(ClassID classId, TypeDesc*& typeDesc)
{
if (classId != 0)
{
std::lock_guard<std::mutex> lock(_typesLock);
auto typeEntry = _types.find(classId);
if (typeEntry != _types.end())
{
typeDesc = &typeEntry->second;
return true;
}
}
return false;
}
void AppendArrayRank(std::string& arrayBuilder, ULONG rank)
{
if (rank == 1)
{
arrayBuilder = "[]" + arrayBuilder;
}
else
{
std::stringstream builder;
builder << "[";
for (size_t i = 0; i < rank - 1; i++)
{
builder << ",";
}
builder << "]";
arrayBuilder = builder.str() + arrayBuilder;
}
}
bool FrameStore::GetTypeDesc(ClassID classId, TypeDesc*& pTypeDesc)
{
// get type related description (assembly, namespace and type name)
// look into the cache first
bool typeInCache = GetCachedTypeDesc(classId, pTypeDesc);
// TODO: would it be interesting to have a (moduleId + mdTokenDef) -> TypeDesc cache for the non cached generic types?
if (!typeInCache)
{
ClassID originalClassId = classId;
// deal with class[]/[,...,]
// read https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/icorprofilerinfo-isarrayclass-method for more details
bool isArray = false;
std::string arrayBuilder;
CorElementType baseElementType;
ClassID itemClassId;
ULONG rank = 0;
if (_pCorProfilerInfo->IsArrayClass(classId, &baseElementType, &itemClassId, &rank) == S_OK)
{
classId = itemClassId;
isArray = true;
AppendArrayRank(arrayBuilder, rank);
// in case of matrices, it is needed to look for the last "good" item class ID
// because all others might be array of array of ...
for (size_t i = 0; i < rank; i++)
{
HRESULT hr = _pCorProfilerInfo->IsArrayClass(classId, &baseElementType, &itemClassId, &rank);
if ((hr == S_FALSE) || FAILED(hr))
{
itemClassId = classId;
break;
}
AppendArrayRank(arrayBuilder, rank);
classId = itemClassId;
}
}
ModuleID moduleId;
mdTypeDef typeDefToken;
INVOKE(_pCorProfilerInfo->GetClassIDInfo(classId, &moduleId, &typeDefToken));
// for some types, it is not possible to find the moduleId ??? --> could be arrays...
if (moduleId == 0)
{
INVOKE(_pCorProfilerInfo->GetClassIDInfo2(classId, &moduleId, &typeDefToken, nullptr, 0, nullptr, nullptr));
}
ComPtr<IMetaDataImport2> metadataImport;
INVOKE_INFO(_pCorProfilerInfo->GetModuleMetaData(moduleId, ofRead, IID_IMetaDataImport2, reinterpret_cast<IUnknown**>(metadataImport.GetAddressOf())));
// try to get the type description
TypeDesc typeDesc;
if (!BuildTypeDesc(metadataImport.Get(), classId, moduleId, typeDefToken, typeDesc, isArray, arrayBuilder.c_str()))
{
return false;
}
if (originalClassId != 0)
{
std::lock_guard<std::mutex> lock(_typesLock);
// it is possible that another thread already added the type description while we were building it
auto typeEntry = _types.find(originalClassId);
if (typeEntry != _types.end())
{
pTypeDesc = &typeEntry->second;
return true;
}
pTypeDesc = &(_types[originalClassId] = typeDesc);
// Incrementally track item size
size_t itemSize = pTypeDesc->Assembly.capacity() + pTypeDesc->Namespace.capacity() +
pTypeDesc->Type.capacity() + pTypeDesc->Parameters.capacity();
_cachedItemsSize.fetch_add(itemSize, std::memory_order_relaxed);
}
else
{
// TODO: check the number of times this happens because a TypeDefs has been constructed but
// it is not possible to return a pointer to it (the object is on the stack)!!!
return false;
}
}
return true;
}
// More explanations in https://chnasarre.medium.com/dealing-with-modules-assemblies-and-types-with-clr-profiling-apis-a7522a5abaa9?source=friends_link&sk=3e010ab991456db0394d4cca29cb8cb2
bool FrameStore::BuildTypeDesc(
IMetaDataImport2* pMetadataImport,
ClassID classId,
ModuleID moduleId,
mdTypeDef mdTokenType,
TypeDesc& typeDesc,
bool isArray,
const char* arraySuffix)
{
// 1. Get the assembly from the module
if (!GetAssemblyName(_pCorProfilerInfo, moduleId, typeDesc.Assembly))
{
return false;
}
// 2. Look for the type name including namespace (need to take into account nested types and generic types)
auto [ns, ct, cg] = GetManagedTypeName(_pCorProfilerInfo, pMetadataImport, moduleId, classId, mdTokenType, isArray, arraySuffix);
typeDesc.Namespace = ns;
typeDesc.Type = ct;
typeDesc.Parameters = cg;
return true;
}
bool FrameStore::GetFunctionInfo(
FunctionID functionId,
mdToken& mdTokenFunc,
ClassID& classId,
ModuleID& moduleId,
ULONG32& genericParametersCount,
std::unique_ptr<ClassID[]>& genericParameters)
{
// Call GetFunctionInfo2 to get the method's class and module, its metadata token, and
// its generic type parameters if any
//
// Note that the class ID may be 0 in the case of a generic type with at least 1 reference type as parameter.
// The solution is to use metadata API to rebuild the un-instanciated definition of the generic type:
// class MyClass<K, V> --> MyClass<K, V>
// Note: it is not possible to get more details about K and V types so the ct: recursive syntax cannot be used
// and the name will be "ct:MyClass<K, V>"
//
// Even when class ID is 0, the generic parameters of the method (not the type) are still available
// and typeArgsCount should not be 0.
//
// Unlike what the GetClassIDInfo2 documentation states, GetFunctionInfo2 must always be called
// with 0 as number of arguments to get the real generic parameters count
// https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/icorprofilerinfo2-getfunctioninfo2-method
//
// GetFunctionInfo2 is called with 0 to get the actual number of the method generic parameters
HRESULT hr = _pCorProfilerInfo->GetFunctionInfo2(
functionId,
(COR_PRF_FRAME_INFO)(nullptr), /* clrFrameInfo */
&classId,
&moduleId,
&mdTokenFunc,
0,
&genericParametersCount,
nullptr);
if (FAILED(hr))
{
classId = 0;
moduleId = 0;
mdTokenFunc = 0;
genericParameters = nullptr;
genericParametersCount = 0;
return false;
}
if (genericParametersCount > 0)
{
// in case of generic function, it's time to allocate the array
// that will receive the ClassID for each generic parameter
genericParameters = std::make_unique<ClassID[]>(genericParametersCount); // move
hr = _pCorProfilerInfo->GetFunctionInfo2(
functionId,
(COR_PRF_FRAME_INFO)(nullptr), /* clrFrameInfo */
nullptr, //
nullptr, // these parameters have already been retrieved in the first call
nullptr, //
genericParametersCount,
&genericParametersCount,
genericParameters.get());
if (FAILED(hr))
{
// This is not supposed to happen but just in case, since generic parameters are not available,
// let's say that this is not a generic function
genericParameters = nullptr;
genericParametersCount = 0;
return false;
}
}
return true;
}
bool FrameStore::GetMetadataApi(ModuleID moduleId, FunctionID functionId, ComPtr<IMetaDataImport2>& pMetadataImport)
{
HRESULT hr = _pCorProfilerInfo->GetModuleMetaData(moduleId, CorOpenFlags::ofRead, IID_IMetaDataImport2, reinterpret_cast<IUnknown**>(pMetadataImport.GetAddressOf()));
if (FAILED(hr))
{
Log::Debug("GetModuleMetaData() failed with HRESULT = ", HResultConverter::ToStringWithCode(hr));
mdToken mdTokenFunc; // not used
hr = _pCorProfilerInfo->GetTokenAndMetaDataFromFunction(
functionId, IID_IMetaDataImport2, reinterpret_cast<IUnknown**>(pMetadataImport.GetAddressOf()), &mdTokenFunc);
if (FAILED(hr))
{
Log::Debug("GetTokenAndMetaDataFromFunction() failed with HRESULT = ", HResultConverter::ToStringWithCode(hr));
return false;
}
}
return true;
}
std::tuple<ULONG, std::string, std::string, mdTypeDef> FrameStore::GetMethodName(
FunctionID functionId,
IMetaDataImport2* pMetadataImport,
mdMethodDef mdTokenFunc,
ULONG32 genericParametersCount,
ClassID* genericParameters)
{
auto [methodName, mdTokenType, rva] = GetMethodNameFromMetadata(pMetadataImport, mdTokenFunc);
if ((methodName.empty()) || (genericParametersCount == 0))
{
return std::make_tuple(rva, std::move(methodName), std::string(), mdTokenType);
}
// Get generic parameters if any
//
// bool LongGenericParameterList<MT1, MT2, MT3, MT4, MT5, MT6, MT7, MT8>(K key, out V val)
// called as: LongGenericParameterList<byte, bool, bool, bool, string, bool, bool, bool>(i, out _)
// -->
// |fn:LongGenericParameterList |fg:<System.Byte, System.Boolean, System.Boolean, System.Boolean, T5, System.Boolean, System.Boolean, System.Boolean>
// since string is a reference type, the __canon implementation is used and we can't know it is a string
// --> this is why T5 (from the metadata) is used
std::stringstream builder;
builder << "<";
for (ULONG32 i = 0; i < genericParametersCount; i++)
{
auto [ns, typeName] = GetManagedTypeName(_pCorProfilerInfo, genericParameters[i]);
// deal with System.__Canon case
if (typeName == "__Canon")
{
builder << "T" << i;
}
else // normal namespace.type case
{
// a type declared outside of any namespace has no namespace: don't prefix it with a '.'
if (!ns.empty())
{
builder << ns << ".";
}
builder << typeName;
}
if (i < genericParametersCount - 1)
{
builder << ", ";
}
}
builder << ">";
return std::make_tuple(rva, methodName, builder.str(), mdTokenType);
}
bool FrameStore::GetAssemblyName(ICorProfilerInfo4* pInfo, ModuleID moduleId, std::string& assemblyName)
{
assemblyName = std::string("");
AssemblyID assemblyId;
INVOKE(pInfo->GetModuleInfo(moduleId, nullptr, 0, nullptr, nullptr, &assemblyId));
// 2 steps way to get the assembly name (get the buffer size first and then fill it up with the name)
ULONG nameCharCount = 0;
INVOKE(pInfo->GetAssemblyInfo(assemblyId, nameCharCount, &nameCharCount, nullptr, nullptr, nullptr));
auto buffer = std::make_unique<WCHAR[]>(nameCharCount);
INVOKE(pInfo->GetAssemblyInfo(assemblyId, nameCharCount, &nameCharCount, buffer.get(), nullptr, nullptr));
// convert from UTF16 to UTF8
assemblyName = shared::ToString(buffer.get());
return true;
}
// Remove `xx at the end of the given string
// ex: List`1 --> List
void FrameStore::FixTrailingGeneric(WCHAR* name)
{
ULONG currentCharPos = 0;
while (name[currentCharPos] != WStr('\0'))
{
if (name[currentCharPos] == WStr('`'))
{
// skip `xx
name[currentCharPos] = WStr('\0');
return; // this is a generic type
}
currentCharPos++;
}
// this is not a generic type
}
std::string FrameStore::GetTypeNameFromMetadata(IMetaDataImport2* pMetadata, mdTypeDef mdTokenType)
{
ULONG nameCharCount = 0;
HRESULT hr = pMetadata->GetTypeDefProps(mdTokenType, nullptr, 0, &nameCharCount, nullptr, nullptr);
if (FAILED(hr))
{
return std::string("");
}
auto buffer = std::make_unique<WCHAR[]>(nameCharCount);
hr = pMetadata->GetTypeDefProps(mdTokenType, buffer.get(), nameCharCount, &nameCharCount, nullptr, nullptr);
if (FAILED(hr))
{
return std::string("");
}
auto pBuffer = buffer.get();
FixTrailingGeneric(pBuffer);
// convert from UTF16 to UTF8
return shared::ToString(pBuffer);
}
std::pair<std::string, std::string> FrameStore::GetTypeWithNamespace(IMetaDataImport2* pMetadata, mdTypeDef mdTokenType)
{
mdTypeDef mdEnclosingType = 0;
HRESULT hr = pMetadata->GetNestedClassProps(mdTokenType, &mdEnclosingType);
bool isNested = SUCCEEDED(hr) && pMetadata->IsValidToken(mdEnclosingType);
std::string enclosingType;
std::string ns;
if (isNested)
{
std::tie(ns, enclosingType) = GetTypeWithNamespace(pMetadata, mdEnclosingType);
}
// Get type name
// Note: in case of nested type (i.e. type defined in another type), the namespace is not present in the name
auto typeName = GetTypeNameFromMetadata(pMetadata, mdTokenType);
if (typeName.empty())
{
// TODO: check if this is what we really want
typeName = "?";
}
if (isNested)
{
return std::make_pair(std::move(ns), enclosingType + "." + typeName);
}
else
{
// the namespace is only given for a non nested type
// --> look for the last '.': what is after is the type name and what is before is the namespace
std::string separated;
auto const pos = typeName.find_last_of('.');
if (pos == std::string::npos)
{
// no namespace
return std::make_pair("", std::move(typeName));
}
// need to split to get the namespace and type name
return std::make_pair(typeName.substr(0, pos), typeName.substr(pos + 1));
}
}
std::vector<std::string> GetGenericTypeParameters(IMetaDataImport2* pMetadata, mdTypeDef mdTokenType)
{
std::vector<std::string> parameters;
// Get all generic parameters definition (ex: "{|ct:K, |ct:V}" for Dictionary<K,V>)
// --> need to iterate on the generic arguments definition with metadata API
HCORENUM hEnum = nullptr;
// NOTE: unlike other COM iterators, it is not possible to get the real count in a first call
// and then allocate to get them all in a second call.
// 128 type parameters sounds more than enough: no need to detect the case where 128
// were retrieved and add ... before >
const ULONG MaxGenericParametersCount = 128;
ULONG genericParamsCount = MaxGenericParametersCount;
mdGenericParam genericParams[MaxGenericParametersCount];
HRESULT hr = pMetadata->EnumGenericParams(&hEnum, mdTokenType, genericParams, MaxGenericParametersCount, &genericParamsCount);
if (hr == S_OK) // S_FALSE is return if there is no generic parameters
{
WCHAR paramName[64];
ULONG paramNameLen = 64;
for (size_t currentParam = 0; currentParam < genericParamsCount; currentParam++)
{
ULONG index;
DWORD flags;
hr = pMetadata->GetGenericParamProps(genericParams[currentParam], &index, &flags, nullptr, nullptr, paramName, paramNameLen, ¶mNameLen);
if (SUCCEEDED(hr))
{
// need to convert from UTF16 to UTF8
parameters.push_back(shared::ToString(paramName));
}
else
{
// this should never happen if the enum succeeded: no need to count the parameters
parameters.push_back("T");
}
}
pMetadata->CloseEnum(hEnum);
}
return parameters;
}
std::string FrameStore::FormatGenericTypeParameters(IMetaDataImport2* pMetadata, mdTypeDef mdTokenType)
{
std::stringstream builder;
builder << "<";
// Get all generic parameters definition (ex: "{K, V}" for Dictionary<K,V>)
// --> need to iterate on the generic arguments definition with metadata API
std::vector<std::string> parameters = GetGenericTypeParameters(pMetadata, mdTokenType);
size_t genericParamsCount = parameters.size();
for (size_t currentParam = 0; currentParam < genericParamsCount; currentParam++)
{
builder << parameters[currentParam];
if (currentParam < genericParamsCount - 1)
{
builder << ", ";
}
}
builder << ">";
return builder.str();
}
void FrameStore::ConcatUnknownGenericType(std::stringstream& builder)
{
builder << "T";
}
std::string FrameStore::FormatGenericParameters(
ICorProfilerInfo4* pInfo,
ULONG32 numGenericTypeArgs,
ClassID* genericTypeArgs)
{
std::stringstream builder;
builder << "<";
for (size_t currentGenericArg = 0; currentGenericArg < numGenericTypeArgs; currentGenericArg++)
{
ClassID argClassId = genericTypeArgs[currentGenericArg];
if (argClassId == 0)
{
ConcatUnknownGenericType(builder);
}
else
{
ModuleID argModuleId;
mdTypeDef mdType;
HRESULT hr = pInfo->GetClassIDInfo2(argClassId, &argModuleId, &mdType, nullptr, 0, nullptr, nullptr);
if (FAILED(hr))
{
ConcatUnknownGenericType(builder);
}
else
{
ComPtr<IMetaDataImport2> pMetadata;
hr = pInfo->GetModuleMetaData(argModuleId, ofRead, IID_IMetaDataImport2, reinterpret_cast<IUnknown**>(pMetadata.GetAddressOf()));
if (FAILED(hr))
{
ConcatUnknownGenericType(builder);
}
else
{
auto [ns, ct, cg] = GetManagedTypeName(pInfo, pMetadata.Get(), argModuleId, argClassId, mdType, false, nullptr);
if (ns.empty())
{
builder << ct;
}
else
{
builder << ns << "." << ct;
}
}
}
}
if (currentGenericArg < numGenericTypeArgs - 1)
{
builder << ", ";
}
}
builder << ">";
return builder.str();
}
// for a given classId/mdTypeDef, get:
// the namespace (if any)
// outer types (if any) without generic information
// inner type with generic information (if any)
std::tuple<std::string, std::string, std::string> FrameStore::GetManagedTypeName(
ICorProfilerInfo4* pInfo,
IMetaDataImport2* pMetadata,
ModuleID moduleId,
ClassID classId,
mdTypeDef mdTokenType,
bool isArray,
const char* arraySuffix)
{
auto [ns, typeName] = GetTypeWithNamespace(pMetadata, mdTokenType);
// we have everything we need if not a generic type
// if classId == 0 (i.e. one generic parameter is a reference type), no way to get the exact generic parameters
// but we can get the original generic parameter type definition (i.e. "T" instead of "string")
if (classId == 0)
{
// concat the generic parameter types from metadata based on mdTokenType
auto genericParameters = FormatGenericTypeParameters(pMetadata, mdTokenType);
if (isArray)
{
return std::make_tuple(std::move(ns), typeName, genericParameters + arraySuffix);
}
else
{
return std::make_tuple(std::move(ns), typeName, genericParameters);
}
}
// figure out the instanciated generic parameters if any
mdTypeDef mdType;
ClassID parentClassId; // useful if we need parent type
ULONG32 numGenericTypeArgs = 0;
HRESULT hr = pInfo->GetClassIDInfo2(classId, nullptr, &mdType, &parentClassId, 0, &numGenericTypeArgs, nullptr);
if (FAILED(hr))
{
// this happens when the given classId is 0 so should not occur
if (isArray)
{
return std::make_tuple(std::move(ns), std::move(typeName), arraySuffix);
}
return std::make_tuple(std::move(ns), std::move(typeName), std::string());
}
// nothing else to do if not a generic
if (FAILED(hr) || (numGenericTypeArgs == 0))
{
if (isArray)
{
return std::make_tuple(std::move(ns), std::move(typeName), arraySuffix);
}
return std::make_tuple(std::move(ns), std::move(typeName), std::string());
}
// list generic parameters
auto genericTypeArgs = std::make_unique<ClassID[]>(numGenericTypeArgs);
hr = pInfo->GetClassIDInfo2(classId, nullptr, &mdType, &parentClassId, numGenericTypeArgs, &numGenericTypeArgs, genericTypeArgs.get());
if (FAILED(hr))
{
// why would it fail?
assert(SUCCEEDED(hr));
if (isArray)
{
return std::make_tuple(std::move(ns), std::move(typeName), arraySuffix);
}
return std::make_tuple(std::move(ns), std::move(typeName), std::string()); // should "<>" be added anyway?
}
// concat the generic parameter types
auto genericParameters = FormatGenericParameters(pInfo, numGenericTypeArgs, genericTypeArgs.get());
if (isArray)
{
return std::make_tuple(std::move(ns), std::move(typeName), genericParameters + arraySuffix);
}
else
{
return std::make_tuple(std::move(ns), std::move(typeName), std::move(genericParameters));
}
}
std::tuple<std::string, mdTypeDef, ULONG> FrameStore::GetMethodNameFromMetadata(IMetaDataImport2* pMetadataImport, mdMethodDef mdTokenFunc)
{
// get the method name
ULONG nameCharCount = 0;
ULONG rva = 0;
HRESULT hr = pMetadataImport->GetMethodProps(mdTokenFunc, nullptr, nullptr, 0, &nameCharCount, nullptr, nullptr, nullptr, nullptr, nullptr);
if (FAILED(hr))
{
return std::make_tuple(std::string(), mdTokenNil, rva);
}
auto buffer = std::make_unique<WCHAR[]>(nameCharCount);
mdTypeDef mdTokenType;
hr = pMetadataImport->GetMethodProps(mdTokenFunc, &mdTokenType, buffer.get(), nameCharCount, &nameCharCount, nullptr, nullptr, nullptr, &rva, nullptr);
if (FAILED(hr))
{
return std::make_tuple(std::string(), mdTokenNil, rva);
}
// convert from UTF16 to UTF8
return std::make_tuple(shared::ToString(buffer.get()), mdTokenType, rva);
}
std::string FrameStore::GetMethodSignature(ICorProfilerInfo4* pInfo, IMetaDataImport2* pMetaData, mdTypeDef mdTokenType, FunctionID functionId, mdMethodDef mdTokenFunc)
{
PCCOR_SIGNATURE pSigBlob;
ULONG blobSize, attributes;
DWORD flags;
ULONG codeRva;
// get the coded signature from metadata
HRESULT hr = pMetaData->GetMethodProps(mdTokenFunc, nullptr, nullptr, 0, nullptr, &attributes, &pSigBlob, &blobSize, &codeRva, &flags);
if (FAILED(hr))
{
return "(?)";
}
// read https://chnasarre.medium.com/decyphering-method-signature-with-clr-profiling-api-8328a72a216e for more details
ULONG elementType;
ULONG callConv;
std::stringstream builder;
// get the calling convention