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
/
methodtablebuilder.cpp
12396 lines (10702 loc) · 490 KB
/
methodtablebuilder.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: METHODTABLEBUILDER.CPP
//
//
//
// ============================================================================
#include "common.h"
#include "methodtablebuilder.h"
#include "sigbuilder.h"
#include "dllimport.h"
#include "fieldmarshaler.h"
#include "encee.h"
#include "ecmakey.h"
#include "customattribute.h"
#include "typestring.h"
#include "compile.h"
//*******************************************************************************
// Helper functions to sort GCdescs by offset (decending order)
int __cdecl compareCGCDescSeries(const void *arg1, const void *arg2)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
CGCDescSeries* gcInfo1 = (CGCDescSeries*) arg1;
CGCDescSeries* gcInfo2 = (CGCDescSeries*) arg2;
return (int)(gcInfo2->GetSeriesOffset() - gcInfo1->GetSeriesOffset());
}
//*******************************************************************************
const char* FormatSig(MethodDesc* pMD, LoaderHeap *pHeap, AllocMemTracker *pamTracker);
#ifdef _DEBUG
unsigned g_dupMethods = 0;
#endif // _DEBUG
//==========================================================================
// This function is very specific about how it constructs a EEClass. It first
// determines the necessary size of the vtable and the number of statics that
// this class requires. The necessary memory is then allocated for a EEClass
// and its vtable and statics. The class members are then initialized and
// the memory is then returned to the caller
//
// LPEEClass CreateClass()
//
// Parameters :
// [in] scope - scope of the current class not the one requested to be opened
// [in] cl - class token of the class to be created.
// [out] ppEEClass - pointer to pointer to hold the address of the EEClass
// allocated in this function.
// Return : returns an HRESULT indicating the success of this function.
//
// This parameter has been removed but might need to be reinstated if the
// global for the metadata loader is removed.
// [in] pIMLoad - MetaDataLoader class/object for the current scope.
//==========================================================================
/*static*/ EEClass *
MethodTableBuilder::CreateClass( Module *pModule,
mdTypeDef cl,
BOOL fHasLayout,
BOOL fDelegate,
BOOL fIsEnum,
const MethodTableBuilder::bmtGenericsInfo *bmtGenericsInfo,
LoaderAllocator * pAllocator,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(!(fHasLayout && fDelegate));
PRECONDITION(!(fHasLayout && fIsEnum));
PRECONDITION(CheckPointer(bmtGenericsInfo));
}
CONTRACTL_END;
EEClass *pEEClass = NULL;
IMDInternalImport *pInternalImport;
//<TODO>============================================================================
// vtabsize and static size need to be converted from pointer sizes to #'s
// of bytes this will be very important for 64 bit NT!
// We will need to call on IMetaDataLoad to get these sizes and fill out the
// tables
// From the classref call on metadata to resolve the classref and check scope
// to make sure that this class is in the same scope otherwise we need to open
// a new scope and possibly file.
// if the scopes are different call the code to load a new file and get the new scope
// scopes are the same so we can use the existing scope to get the class info
// This method needs to be fleshed out.more it currently just returns enough
// space for the defined EEClass and the vtable and statics are not set.
//=============================================================================</TODO>
if (fHasLayout)
{
pEEClass = new (pAllocator->GetLowFrequencyHeap(), pamTracker) LayoutEEClass();
}
else if (fDelegate)
{
pEEClass = new (pAllocator->GetLowFrequencyHeap(), pamTracker) DelegateEEClass();
}
else
{
pEEClass = new (pAllocator->GetLowFrequencyHeap(), pamTracker) EEClass(sizeof(EEClass));
}
DWORD dwAttrClass = 0;
mdToken tkExtends = mdTokenNil;
// Set up variance info
if (bmtGenericsInfo->pVarianceInfo)
{
// Variance info is an optional field on EEClass, so ensure the optional field descriptor has been
// allocated.
EnsureOptionalFieldsAreAllocated(pEEClass, pamTracker, pAllocator->GetLowFrequencyHeap());
pEEClass->SetVarianceInfo((BYTE*) pamTracker->Track(
pAllocator->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(bmtGenericsInfo->GetNumGenericArgs()))));
memcpy(pEEClass->GetVarianceInfo(), bmtGenericsInfo->pVarianceInfo, bmtGenericsInfo->GetNumGenericArgs());
}
pInternalImport = pModule->GetMDImport();
if (pInternalImport == NULL)
COMPlusThrowHR(COR_E_TYPELOAD);
IfFailThrow(pInternalImport->GetTypeDefProps(
cl,
&dwAttrClass,
&tkExtends));
pEEClass->m_dwAttrClass = dwAttrClass;
// MDVal check: can't be both tdSequentialLayout and tdExplicitLayout
if((dwAttrClass & tdLayoutMask) == tdLayoutMask)
COMPlusThrowHR(COR_E_TYPELOAD);
if (IsTdInterface(dwAttrClass))
{
// MDVal check: must have nil tkExtends and must be tdAbstract
if((tkExtends & 0x00FFFFFF)||(!IsTdAbstract(dwAttrClass)))
COMPlusThrowHR(COR_E_TYPELOAD);
}
if (fHasLayout)
pEEClass->SetHasLayout();
#ifdef FEATURE_COMINTEROP
if (IsTdWindowsRuntime(dwAttrClass))
{
Assembly *pAssembly = pModule->GetAssembly();
// On the desktop CLR, we do not allow non-FX assemblies to use/define WindowsRuntimeImport attribute.
//
// On CoreCLR, however, we do allow non-FX assemblies to have this attribute. This enables scenarios where we can
// activate 3rd-party WinRT components outside AppContainer - 1st party WinRT components are already allowed
// to be activated outside AppContainer (on both Desktop and CoreCLR).
pEEClass->SetProjectedFromWinRT();
}
if (pEEClass->IsProjectedFromWinRT())
{
if (IsTdInterface(dwAttrClass))
{
//
// Check for GuidAttribute
//
BOOL bHasGuid = FALSE;
GUID guid;
HRESULT hr = pModule->GetMDImport()->GetItemGuid(cl, &guid);
IfFailThrow(hr);
if (IsEqualGUID(guid, GUID_NULL))
{
// A WinRT interface should have a GUID
pModule->GetAssembly()->ThrowTypeLoadException(pModule->GetMDImport(), cl, IDS_EE_WINRT_INTERFACE_WITHOUT_GUID);
}
}
}
WinMDAdapter::RedirectedTypeIndex redirectedTypeIndex;
redirectedTypeIndex = WinRTTypeNameConverter::GetRedirectedTypeIndexByName(pModule, cl);
if (redirectedTypeIndex != WinMDAdapter::RedirectedTypeIndex_Invalid)
{
EnsureOptionalFieldsAreAllocated(pEEClass, pamTracker, pAllocator->GetLowFrequencyHeap());
pEEClass->SetWinRTRedirectedTypeIndex(redirectedTypeIndex);
}
#endif // FEAUTRE_COMINTEROP
#ifdef _DEBUG
pModule->GetClassLoader()->m_dwDebugClasses++;
#endif
return pEEClass;
}
//*******************************************************************************
//
// Create a hash of all methods in this class. The hash is from method name to MethodDesc.
//
MethodTableBuilder::MethodNameHash *
MethodTableBuilder::CreateMethodChainHash(
MethodTable *pMT)
{
STANDARD_VM_CONTRACT;
MethodNameHash *pHash = new (GetStackingAllocator()) MethodNameHash();
pHash->Init(pMT->GetNumVirtuals(), GetStackingAllocator());
unsigned numVirtuals = GetParentMethodTable()->GetNumVirtuals();
for (unsigned i = 0; i < numVirtuals; ++i)
{
bmtMethodSlot &slot = (*bmtParent->pSlotTable)[i];
bmtRTMethod * pMethod = slot.Decl().AsRTMethod();
const MethodSignature &sig = pMethod->GetMethodSignature();
pHash->Insert(sig.GetName(), pMethod);
}
// Success
return pHash;
}
//*******************************************************************************
//
// Find a method in this class hierarchy - used ONLY by the loader during layout. Do not use at runtime.
//
// *ppMemberSignature must be NULL on entry - it and *pcMemberSignature may or may not be filled out
//
// ppMethodDesc will be filled out with NULL if no matching method in the hierarchy is found.
//
// Returns FALSE if there was an error of some kind.
//
// pMethodConstraintsMatch receives the result of comparing the method constraints.
MethodTableBuilder::bmtRTMethod *
MethodTableBuilder::LoaderFindMethodInParentClass(
const MethodSignature & methodSig,
BOOL * pMethodConstraintsMatch)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(this));
PRECONDITION(CheckPointer(bmtParent));
PRECONDITION(CheckPointer(methodSig.GetModule()));
PRECONDITION(CheckPointer(methodSig.GetSignature()));
PRECONDITION(HasParent());
PRECONDITION(methodSig.GetSignatureLength() != 0);
}
CONTRACTL_END;
//#if 0
MethodNameHash::HashEntry * pEntry;
// Have we created a hash of all the methods in the class chain?
if (bmtParent->pParentMethodHash == NULL)
{
// There may be such a method, so we will now create a hash table to reduce the pain for
// further lookups
// <TODO> Are we really sure that this is worth doing? </TODO>
bmtParent->pParentMethodHash = CreateMethodChainHash(GetParentMethodTable());
}
// We have a hash table, so use it
pEntry = bmtParent->pParentMethodHash->Lookup(methodSig.GetName());
// Traverse the chain of all methods with this name
while (pEntry != NULL)
{
bmtRTMethod * pEntryMethod = pEntry->m_data;
const MethodSignature & entrySig = pEntryMethod->GetMethodSignature();
// Note instantiation info
{
if (methodSig.Equivalent(entrySig))
{
if (pMethodConstraintsMatch != NULL)
{
// Check the constraints are consistent,
// and return the result to the caller.
// We do this here to avoid recalculating pSubst.
*pMethodConstraintsMatch = MetaSig::CompareMethodConstraints(
&methodSig.GetSubstitution(), methodSig.GetModule(), methodSig.GetToken(),
&entrySig.GetSubstitution(), entrySig.GetModule(), entrySig.GetToken());
}
return pEntryMethod;
}
}
// Advance to next item in the hash chain which has the same name
pEntry = bmtParent->pParentMethodHash->FindNext(pEntry);
}
//#endif
//@TODO: Move to this code, as the use of a HashTable is broken; overriding semantics
//@TODO: require matching against the most-derived slot of a given name and signature,
//@TODO: (which deals specifically with newslot methods with identical name and sig), but
//@TODO: HashTables are by definition unordered and so we've only been getting by with the
//@TODO: implementation being compatible with the order in which methods were added to
//@TODO: the HashTable in CreateMethodChainHash.
#if 0
bmtParentInfo::Iterator it(bmtParent->IterateSlots());
it.MoveTo(static_cast<size_t>(GetParentMethodTable()->GetNumVirtuals()));
while (it.Prev())
{
bmtMethodHandle decl(it->Decl());
const MethodSignature &declSig(decl.GetMethodSignature());
if (declSig == methodSig)
{
if (pMethodConstraintsMatch != NULL)
{
// Check the constraints are consistent,
// and return the result to the caller.
// We do this here to avoid recalculating pSubst.
*pMethodConstraintsMatch = MetaSig::CompareMethodConstraints(
&methodSig.GetSubstitution(), methodSig.GetModule(), methodSig.GetToken(),
&declSig.GetSubstitution(), declSig.GetModule(), declSig.GetToken());
}
return decl.AsRTMethod();
}
}
#endif // 0
return NULL;
}
//*******************************************************************************
//
// Given an interface map to fill out, expand pNewInterface (and its sub-interfaces) into it, increasing
// pdwInterfaceListSize as appropriate, and avoiding duplicates.
//
void
MethodTableBuilder::ExpandApproxInterface(
bmtInterfaceInfo * bmtInterface, // out parameter, various parts cumulatively written to.
const Substitution * pNewInterfaceSubstChain,
MethodTable * pNewInterface,
InterfaceDeclarationScope declScope
COMMA_INDEBUG(MethodTable * dbg_pClassMT))
{
STANDARD_VM_CONTRACT;
//#ExpandingInterfaces
// We expand the tree of inherited interfaces into a set by adding the
// current node BEFORE expanding the parents of the current node.
// ****** This must be consistent with code:ExpandExactInterface *******
// ****** This must be consistent with code:ClassCompat::MethodTableBuilder::BuildInteropVTable_ExpandInterface *******
// The interface list contains the fully expanded set of interfaces from the parent then
// we start adding all the interfaces we declare. We need to know which interfaces
// we declare but do not need duplicates of the ones we declare. This means we can
// duplicate our parent entries.
// Is it already present in the list?
for (DWORD i = 0; i < bmtInterface->dwInterfaceMapSize; i++)
{
bmtInterfaceEntry * pItfEntry = &bmtInterface->pInterfaceMap[i];
bmtRTType * pItfType = pItfEntry->GetInterfaceType();
// Type Equivalence is not respected for this comparision as you can have multiple type equivalent interfaces on a class
TokenPairList newVisited = TokenPairList::AdjustForTypeEquivalenceForbiddenScope(NULL);
if (MetaSig::CompareTypeDefsUnderSubstitutions(pItfType->GetMethodTable(),
pNewInterface,
&pItfType->GetSubstitution(),
pNewInterfaceSubstChain,
&newVisited))
{
if (declScope.fIsInterfaceDeclaredOnType)
{
pItfEntry->IsDeclaredOnType() = true;
}
#ifdef _DEBUG
//#InjectInterfaceDuplicates_ApproxInterfaces
// We can inject duplicate interfaces in check builds.
// Has to be in sync with code:#InjectInterfaceDuplicates_Main
if (((dbg_pClassMT == NULL) && bmtInterface->dbg_fShouldInjectInterfaceDuplicates) ||
((dbg_pClassMT != NULL) && dbg_pClassMT->Debug_HasInjectedInterfaceDuplicates()))
{
// The injected duplicate interface should have the same status 'ImplementedByParent' as
// the original interface (can be false if the interface is implemented indirectly twice)
declScope.fIsInterfaceDeclaredOnParent = pItfEntry->IsImplementedByParent();
// Just pretend we didn't find this match, but mark all duplicates as 'DeclaredOnType' if
// needed
continue;
}
#endif //_DEBUG
return; // found it, don't add it again
}
}
bmtRTType * pNewItfType =
new (GetStackingAllocator()) bmtRTType(*pNewInterfaceSubstChain, pNewInterface);
if (bmtInterface->dwInterfaceMapSize >= bmtInterface->dwInterfaceMapAllocated)
{
//
// Grow the array of interfaces
//
S_UINT32 dwNewAllocated = S_UINT32(2) * S_UINT32(bmtInterface->dwInterfaceMapAllocated) + S_UINT32(5);
if (dwNewAllocated.IsOverflow())
{
BuildMethodTableThrowException(COR_E_OVERFLOW);
}
S_SIZE_T safeSize = S_SIZE_T(sizeof(bmtInterfaceEntry)) *
S_SIZE_T(dwNewAllocated.Value());
if (safeSize.IsOverflow())
{
BuildMethodTableThrowException(COR_E_OVERFLOW);
}
bmtInterfaceEntry * pNewMap = (bmtInterfaceEntry *)new (GetStackingAllocator()) BYTE[safeSize.Value()];
memcpy(pNewMap, bmtInterface->pInterfaceMap, sizeof(bmtInterfaceEntry) * bmtInterface->dwInterfaceMapAllocated);
bmtInterface->pInterfaceMap = pNewMap;
bmtInterface->dwInterfaceMapAllocated = dwNewAllocated.Value();
}
// The interface map memory was just allocated as an array of bytes, so we use
// in place new to init the new map entry. No need to do anything with the result,
// so just chuck it.
CONSISTENCY_CHECK(bmtInterface->dwInterfaceMapSize < bmtInterface->dwInterfaceMapAllocated);
new ((void *)&bmtInterface->pInterfaceMap[bmtInterface->dwInterfaceMapSize])
bmtInterfaceEntry(pNewItfType, declScope);
bmtInterface->dwInterfaceMapSize++;
// Make sure to pass in the substitution from the new itf type created above as
// these methods assume that substitutions are allocated in the stacking heap,
// not the stack.
InterfaceDeclarationScope declaredItfScope(declScope.fIsInterfaceDeclaredOnParent, false);
ExpandApproxDeclaredInterfaces(
bmtInterface,
bmtTypeHandle(pNewItfType),
declaredItfScope
COMMA_INDEBUG(dbg_pClassMT));
} // MethodTableBuilder::ExpandApproxInterface
//*******************************************************************************
// Arguments:
// dbg_pClassMT - Class on which the interfaces are declared (either explicitly or implicitly).
// It will never be an interface. It may be NULL (if it is the type being built).
void
MethodTableBuilder::ExpandApproxDeclaredInterfaces(
bmtInterfaceInfo * bmtInterface, // out parameter, various parts cumulatively written to.
bmtTypeHandle thType,
InterfaceDeclarationScope declScope
COMMA_INDEBUG(MethodTable * dbg_pClassMT))
{
STANDARD_VM_CONTRACT;
_ASSERTE((dbg_pClassMT == NULL) || !dbg_pClassMT->IsInterface());
HRESULT hr;
// Iterate the list of interfaces declared by thType and add them to the map.
InterfaceImplEnum ie(thType.GetModule(), thType.GetTypeDefToken(), &thType.GetSubstitution());
while ((hr = ie.Next()) == S_OK)
{
MethodTable *pGenericIntf = ClassLoader::LoadApproxTypeThrowing(
thType.GetModule(), ie.CurrentToken(), NULL, NULL).GetMethodTable();
CONSISTENCY_CHECK(pGenericIntf->IsInterface());
ExpandApproxInterface(bmtInterface,
ie.CurrentSubst(),
pGenericIntf,
declScope
COMMA_INDEBUG(dbg_pClassMT));
}
if (FAILED(hr))
{
BuildMethodTableThrowException(IDS_CLASSLOAD_BADFORMAT);
}
} // MethodTableBuilder::ExpandApproxDeclaredInterfaces
//*******************************************************************************
void
MethodTableBuilder::ExpandApproxInheritedInterfaces(
bmtInterfaceInfo * bmtInterface,
bmtRTType * pParentType)
{
STANDARD_VM_CONTRACT;
// Expand interfaces in superclasses first. Interfaces inherited from parents
// must have identical indexes as in the parent.
bmtRTType * pParentOfParent = pParentType->GetParentType();
//#InterfaceMap_SupersetOfParent
// We have to load parent's interface map the same way the parent did it (as open type).
// Further code depends on this:
// code:#InterfaceMap_UseParentInterfaceImplementations
// We check that it is truth:
// code:#ApproxInterfaceMap_SupersetOfParent
// code:#ExactInterfaceMap_SupersetOfParent
//
//#InterfaceMap_CanonicalSupersetOfParent
// Note that canonical instantiation of parent can have different interface instantiations in the
// interface map than derived type:
// class MyClass<T> : MyBase<string, T>, I<T>
// class MyBase<U, V> : I<U>
// Type MyClass<_Canon> has MyBase<_Canon,_Canon> as parent. The interface maps are:
// MyBase<_Canon,_Canon> ... I<_Canon>
// MyClass<_Canon> ... I<string> (#1)
// I<_Canon> (#2)
// The I's instantiation I<string> (#1) in MyClass and I<_Canon> from MyBase are not the same
// instantiations.
// Backup parent substitution
Substitution parentSubstitution = pParentType->GetSubstitution();
// Make parent an open type
pParentType->SetSubstitution(Substitution());
if (pParentOfParent != NULL)
{
ExpandApproxInheritedInterfaces(bmtInterface, pParentOfParent);
}
InterfaceDeclarationScope declScope(true, false);
ExpandApproxDeclaredInterfaces(
bmtInterface,
bmtTypeHandle(pParentType),
declScope
COMMA_INDEBUG(pParentType->GetMethodTable()));
// Make sure we loaded the same number of interfaces as the parent type itself
CONSISTENCY_CHECK(pParentType->GetMethodTable()->GetNumInterfaces() == bmtInterface->dwInterfaceMapSize);
// Restore parent's substitution
pParentType->SetSubstitution(parentSubstitution);
} // MethodTableBuilder::ExpandApproxInheritedInterfaces
//*******************************************************************************
// Fill out a fully expanded interface map, such that if we are declared to
// implement I3, and I3 extends I1,I2, then I1,I2 are added to our list if
// they are not already present.
void
MethodTableBuilder::LoadApproxInterfaceMap()
{
STANDARD_VM_CONTRACT;
bmtInterface->dwInterfaceMapSize = 0;
#ifdef _DEBUG
//#InjectInterfaceDuplicates_Main
// We will inject duplicate interfaces in check builds if env. var.
// COMPLUS_INTERNAL_TypeLoader_InjectInterfaceDuplicates is set to TRUE for all types (incl. non-generic
// types).
// This should allow us better test coverage of duplicates in interface map.
//
// The duplicates are legal for some types:
// A<T> : I<T>
// B<U,V> : A<U>, I<V>
// C : B<int,int>
// where the interface maps are:
// A<T> ... 1 item: I<T>
// A<int> ... 1 item: I<int>
// B<U,V> ... 2 items: I<U>, I<V>
// B<int,int> ... 2 items: I<int>, I<int>
// B<_Canon,_Canon> ... 2 items: I<_Canon>, I<_Canon>
// B<string,string> ... 2 items: I<string>, I<string>
// C ... 2 items: I<int>, I<int>
// Note: C had only 1 item (I<int>) in CLR 2.0 RTM/SP1/SP2 and early in CLR 4.0.
//
// We will create duplicate from every re-implemented interface (incl. non-generic):
// code:#InjectInterfaceDuplicates_ApproxInterfaces
// code:#InjectInterfaceDuplicates_LoadExactInterfaceMap
// code:#InjectInterfaceDuplicates_ExactInterfaces
//
// Note that we don't have to do anything for COM, because COM has its own interface map
// (code:InteropMethodTableData)which is independent on type's interface map and is created only from
// non-generic interfaces (see code:ClassCompat::MethodTableBuilder::BuildInteropVTable_InterfaceList)
// We need to keep track which interface duplicates were injected. Right now its either all interfaces
// (declared on the type being built, not inheritted) or none. In the future we could inject duplicates
// just for some of them.
bmtInterface->dbg_fShouldInjectInterfaceDuplicates =
(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_TypeLoader_InjectInterfaceDuplicates) != 0);
if (bmtGenerics->Debug_GetTypicalMethodTable() != NULL)
{ // It's safer to require that all instantiations have the same injected interface duplicates.
// In future we could inject different duplicates for various non-shared instantiations.
// Use the same injection status as typical instantiation
bmtInterface->dbg_fShouldInjectInterfaceDuplicates =
bmtGenerics->Debug_GetTypicalMethodTable()->Debug_HasInjectedInterfaceDuplicates();
if (GetModule() == g_pObjectClass->GetModule())
{ // mscorlib has some weird hardcoded information about interfaces (e.g.
// code:CEEPreloader::ApplyTypeDependencyForSZArrayHelper), so we don't inject duplicates into
// mscorlib types
bmtInterface->dbg_fShouldInjectInterfaceDuplicates = FALSE;
}
}
#endif //_DEBUG
// First inherit all the parent's interfaces. This is important, because our interface map must
// list the interfaces in identical order to our parent.
//
// <NICE> we should document the reasons why. One reason is that DispatchMapTypeIDs can be indexes
// into the list </NICE>
if (HasParent())
{
ExpandApproxInheritedInterfaces(bmtInterface, GetParentType());
#ifdef _DEBUG
//#ApproxInterfaceMap_SupersetOfParent
// Check that parent's interface map is the same as what we just computed
// See code:#InterfaceMap_SupersetOfParent
{
MethodTable * pParentMT = GetParentMethodTable();
_ASSERTE(pParentMT->GetNumInterfaces() == bmtInterface->dwInterfaceMapSize);
MethodTable::InterfaceMapIterator parentInterfacesIterator = pParentMT->IterateInterfaceMap();
UINT32 nInterfaceIndex = 0;
while (parentInterfacesIterator.Next())
{
// Compare TypeDefs of the parent's interface and this interface (full MT comparison is in
// code:#ExactInterfaceMap_SupersetOfParent)
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOAD_APPROXPARENTS);
_ASSERTE(parentInterfacesIterator.GetInterfaceInfo()->GetApproxMethodTable(pParentMT->GetLoaderModule())->HasSameTypeDefAs(
bmtInterface->pInterfaceMap[nInterfaceIndex].GetInterfaceType()->GetMethodTable()));
nInterfaceIndex++;
}
_ASSERTE(nInterfaceIndex == bmtInterface->dwInterfaceMapSize);
}
#endif //_DEBUG
}
// Now add in any freshly declared interfaces, possibly augmenting the flags
InterfaceDeclarationScope declScope(false, true);
ExpandApproxDeclaredInterfaces(
bmtInterface,
bmtInternal->pType,
declScope
COMMA_INDEBUG(NULL));
} // MethodTableBuilder::LoadApproxInterfaceMap
//*******************************************************************************
// Fills array of TypeIDs with all duplicate occurences of pDeclIntfMT in the interface map.
//
// Arguments:
// rg/c DispatchMapTypeIDs - Array of TypeIDs and its count of elements.
// pcIfaceDuplicates - Number of duplicate occurences of the interface in the interface map (ideally <=
// count of elements TypeIDs.
//
// Note: If the passed rgDispatchMapTypeIDs array is smaller than the number of duplicates, fills it
// with the duplicates that fit and returns number of all existing duplicates (not just those fileld in the
// array) in pcIfaceDuplicates.
//
void
MethodTableBuilder::ComputeDispatchMapTypeIDs(
MethodTable * pDeclInftMT,
const Substitution * pDeclIntfSubst,
DispatchMapTypeID * rgDispatchMapTypeIDs,
UINT32 cDispatchMapTypeIDs,
UINT32 * pcIfaceDuplicates)
{
STANDARD_VM_CONTRACT;
_ASSERTE(pDeclInftMT->IsInterface());
// Count of interface duplicates (also used as index into TypeIDs array)
*pcIfaceDuplicates = 0;
for (DWORD idx = 0; idx < bmtInterface->dwInterfaceMapSize; idx++)
{
bmtInterfaceEntry * pItfEntry = &bmtInterface->pInterfaceMap[idx];
bmtRTType * pItfType = pItfEntry->GetInterfaceType();
// Type Equivalence is forbidden in interface type ids.
TokenPairList newVisited = TokenPairList::AdjustForTypeEquivalenceForbiddenScope(NULL);
if (MetaSig::CompareTypeDefsUnderSubstitutions(pItfType->GetMethodTable(),
pDeclInftMT,
&pItfType->GetSubstitution(),
pDeclIntfSubst,
&newVisited))
{ // We found another occurence of this interface
// Can we fit it into the TypeID array?
if (*pcIfaceDuplicates < cDispatchMapTypeIDs)
{
rgDispatchMapTypeIDs[*pcIfaceDuplicates] = DispatchMapTypeID::InterfaceClassID(idx);
}
// Increase number of duplicate interfaces
(*pcIfaceDuplicates)++;
}
}
} // MethodTableBuilder::ComputeDispatchMapTypeIDs
//*******************************************************************************
/*static*/
VOID DECLSPEC_NORETURN
MethodTableBuilder::BuildMethodTableThrowException(
HRESULT hr,
const bmtErrorInfo & bmtError)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LPCUTF8 pszClassName, pszNameSpace;
if (FAILED(bmtError.pModule->GetMDImport()->GetNameOfTypeDef(bmtError.cl, &pszClassName, &pszNameSpace)))
{
pszClassName = pszNameSpace = "Invalid TypeDef record";
}
if (IsNilToken(bmtError.dMethodDefInError) && (bmtError.szMethodNameForError == NULL))
{
if (hr == E_OUTOFMEMORY)
{
COMPlusThrowOM();
}
else
bmtError.pModule->GetAssembly()->ThrowTypeLoadException(
pszNameSpace, pszClassName, bmtError.resIDWhy);
}
else
{
LPCUTF8 szMethodName;
if (bmtError.szMethodNameForError == NULL)
{
if (FAILED((bmtError.pModule->GetMDImport())->GetNameOfMethodDef(bmtError.dMethodDefInError, &szMethodName)))
{
szMethodName = "Invalid MethodDef record";
}
}
else
{
szMethodName = bmtError.szMethodNameForError;
}
bmtError.pModule->GetAssembly()->ThrowTypeLoadException(
pszNameSpace, pszClassName, szMethodName, bmtError.resIDWhy);
}
} // MethodTableBuilder::BuildMethodTableThrowException
//*******************************************************************************
void MethodTableBuilder::SetBMTData(
LoaderAllocator *bmtAllocator,
bmtErrorInfo *bmtError,
bmtProperties *bmtProp,
bmtVtable *bmtVT,
bmtParentInfo *bmtParent,
bmtInterfaceInfo *bmtInterface,
bmtMetaDataInfo *bmtMetaData,
bmtMethodInfo *bmtMethod,
bmtMethAndFieldDescs *bmtMFDescs,
bmtFieldPlacement *bmtFP,
bmtInternalInfo *bmtInternal,
bmtGCSeriesInfo *bmtGCSeries,
bmtMethodImplInfo *bmtMethodImpl,
const bmtGenericsInfo *bmtGenerics,
bmtEnumFieldInfo *bmtEnumFields)
{
LIMITED_METHOD_CONTRACT;
this->bmtAllocator = bmtAllocator;
this->bmtError = bmtError;
this->bmtProp = bmtProp;
this->bmtVT = bmtVT;
this->bmtParent = bmtParent;
this->bmtInterface = bmtInterface;
this->bmtMetaData = bmtMetaData;
this->bmtMethod = bmtMethod;
this->bmtMFDescs = bmtMFDescs;
this->bmtFP = bmtFP;
this->bmtInternal = bmtInternal;
this->bmtGCSeries = bmtGCSeries;
this->bmtMethodImpl = bmtMethodImpl;
this->bmtGenerics = bmtGenerics;
this->bmtEnumFields = bmtEnumFields;
}
//*******************************************************************************
// Used by MethodTableBuilder
MethodTableBuilder::bmtRTType *
MethodTableBuilder::CreateTypeChain(
MethodTable * pMT,
const Substitution & subst)
{
CONTRACTL
{
STANDARD_VM_CHECK;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(GetStackingAllocator()));
PRECONDITION(CheckPointer(pMT));
} CONTRACTL_END;
pMT = pMT->GetCanonicalMethodTable();
bmtRTType * pType = new (GetStackingAllocator())
bmtRTType(subst, pMT);
MethodTable * pMTParent = pMT->GetParentMethodTable();
if (pMTParent != NULL)
{
pType->SetParentType(
CreateTypeChain(
pMTParent,
pMT->GetSubstitutionForParent(&pType->GetSubstitution())));
}
return pType;
}
//*******************************************************************************
/* static */
MethodTableBuilder::bmtRTType *
MethodTableBuilder::bmtRTType::FindType(
bmtRTType * pType,
MethodTable * pTargetMT)
{
CONTRACTL {
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pType));
PRECONDITION(CheckPointer(pTargetMT));
} CONTRACTL_END;
pTargetMT = pTargetMT->GetCanonicalMethodTable();
while (pType != NULL &&
pType->GetMethodTable()->GetCanonicalMethodTable() != pTargetMT)
{
pType = pType->GetParentType();
}
return pType;
}
//*******************************************************************************
mdTypeDef
MethodTableBuilder::bmtRTType::GetEnclosingTypeToken() const
{
STANDARD_VM_CONTRACT;
mdTypeDef tok = mdTypeDefNil;
if (IsNested())
{ // This is guaranteed to succeed because the EEClass would not have been
// set as nested unless a valid token was stored in metadata.
if (FAILED(GetModule()->GetMDImport()->GetNestedClassProps(
GetTypeDefToken(), &tok)))
{
return mdTypeDefNil;
}
}
return tok;
}
//*******************************************************************************
/*static*/ bool
MethodTableBuilder::MethodSignature::NamesEqual(
const MethodSignature & sig1,
const MethodSignature & sig2)
{
STANDARD_VM_CONTRACT;
if (sig1.GetNameHash() != sig2.GetNameHash())
{
return false;
}
if (strcmp(sig1.GetName(), sig2.GetName()) != 0)
{
return false;
}
return true;
}
//*******************************************************************************
/*static*/ bool
MethodTableBuilder::MethodSignature::SignaturesEquivalent(
const MethodSignature & sig1,
const MethodSignature & sig2)
{
STANDARD_VM_CONTRACT;
return !!MetaSig::CompareMethodSigs(
sig1.GetSignature(), static_cast<DWORD>(sig1.GetSignatureLength()), sig1.GetModule(), &sig1.GetSubstitution(),
sig2.GetSignature(), static_cast<DWORD>(sig2.GetSignatureLength()), sig2.GetModule(), &sig2.GetSubstitution());
}
//*******************************************************************************
/*static*/ bool
MethodTableBuilder::MethodSignature::SignaturesExactlyEqual(
const MethodSignature & sig1,
const MethodSignature & sig2)
{
STANDARD_VM_CONTRACT;
TokenPairList newVisited = TokenPairList::AdjustForTypeEquivalenceForbiddenScope(NULL);
return !!MetaSig::CompareMethodSigs(
sig1.GetSignature(), static_cast<DWORD>(sig1.GetSignatureLength()), sig1.GetModule(), &sig1.GetSubstitution(),
sig2.GetSignature(), static_cast<DWORD>(sig2.GetSignatureLength()), sig2.GetModule(), &sig2.GetSubstitution(),
&newVisited);
}
//*******************************************************************************
bool
MethodTableBuilder::MethodSignature::Equivalent(
const MethodSignature &rhs) const
{
STANDARD_VM_CONTRACT;
return NamesEqual(*this, rhs) && SignaturesEquivalent(*this, rhs);
}
//*******************************************************************************
bool
MethodTableBuilder::MethodSignature::ExactlyEqual(
const MethodSignature &rhs) const
{
STANDARD_VM_CONTRACT;
return NamesEqual(*this, rhs) && SignaturesExactlyEqual(*this, rhs);
}
//*******************************************************************************
void
MethodTableBuilder::MethodSignature::GetMethodAttributes() const
{
STANDARD_VM_CONTRACT;
IMDInternalImport * pIMD = GetModule()->GetMDImport();
if (TypeFromToken(GetToken()) == mdtMethodDef)
{
DWORD cSig;
if (FAILED(pIMD->GetNameAndSigOfMethodDef(GetToken(), &m_pSig, &cSig, &m_szName)))
{ // We have empty name or signature on error, do nothing
}
m_cSig = static_cast<size_t>(cSig);
}
else
{
CONSISTENCY_CHECK(TypeFromToken(m_tok) == mdtMemberRef);
DWORD cSig;
if (FAILED(pIMD->GetNameAndSigOfMemberRef(GetToken(), &m_pSig, &cSig, &m_szName)))
{ // We have empty name or signature on error, do nothing
}
m_cSig = static_cast<size_t>(cSig);
}
}
//*******************************************************************************
UINT32
MethodTableBuilder::MethodSignature::GetNameHash() const
{
STANDARD_VM_CONTRACT;
CheckGetMethodAttributes();
if (m_nameHash == INVALID_NAME_HASH)
{
ULONG nameHash = HashStringA(GetName());
if (nameHash == INVALID_NAME_HASH)
{
nameHash /= 2;
}
m_nameHash = nameHash;
}
return m_nameHash;
}
//*******************************************************************************
MethodTableBuilder::bmtMDType::bmtMDType(
bmtRTType * pParentType,
Module * pModule,
mdTypeDef tok,
const SigTypeContext & sigContext)
: m_pParentType(pParentType),
m_pModule(pModule),
m_tok(tok),
m_enclTok(mdTypeDefNil),
m_sigContext(sigContext),
m_subst(),
m_dwAttrs(0),
m_pMT(NULL)
{