This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathgenmeth.cpp
More file actions
1697 lines (1444 loc) · 70 KB
/
Copy pathgenmeth.cpp
File metadata and controls
1697 lines (1444 loc) · 70 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
// 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: genmeth.cpp
//
// Most functionality for generic methods is put here
//
#include "common.h"
#include "method.hpp"
#include "field.h"
#include "eeconfig.h"
#include "crst.h"
#include "generics.h"
#include "genericdict.h"
#include "instmethhash.h"
#include "typestring.h"
#include "typedesc.h"
#include "comdelegate.h"
// Instantiated generic methods
//
// Method descriptors for instantiated generic methods are allocated on demand and inserted
// into the InstMethodHashTable for the LoaderModule of the descriptor. (See ceeload.h for more
// information about loader modules).
//
// For non-shared instantiations, entering the prestub for such a method descriptor causes the method to
// be JIT-compiled, specialized to that instantiation.
//
// For shared instantiations, entering the prestub generates a piece of stub code that passes the
// method descriptor as an extra argument and then jumps to code shared between compatible
// instantiations. This code has its own method descriptor whose instantiation is *canonical*
// (with reference-type type parameters replaced by Object).
//
// Thus for example the shared method descriptor for m<object> is different to the
// exact-instantiation method descriptor for m<object>.
//
// Complete example:
//
// class C<T> { public void m<S>(S x, T y) { ... } }
//
// Suppose that code sharing is turned on.
//
// Upon compiling calls to C<string>.m<string>, C<string>.m<Type>, C<Type>.m<string> and C<Type>.m<Type>
// Given a generic method descriptor and an instantiation, create a new instantiated method
// descriptor and chain it into the list attached to the generic method descriptor
//
// pMT is the owner method table. If looking for a shared MD this should be
// the MT for the shared class.
//
// pGenericMD is the generic method descriptor (owner may be instantiated)
// pWrappedMD is the corresponding shared md for use when creating stubs
// nGenericMethodArgs/genericMethodArgs is the instantiation
// getWrappedCode=TRUE if you want a shared instantiated md whose code expects an extra argument. In this
// case pWrappedMD should be NULL.
//
// The result is put in ppMD
//
// If getWrappedCode. In thise case the genericMethodArgs
// should be the normalized representative genericMethodArgs (see typehandle.h)
//
// Helper method that creates a method-desc off a template method desc
static MethodDesc* CreateMethodDesc(LoaderAllocator *pAllocator,
MethodTable *pMT,
MethodDesc *pTemplateMD,
DWORD classification,
BOOL fNativeCodeSlot,
BOOL fComPlusCallInfo,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pTemplateMD));
PRECONDITION(pTemplateMD->IsRestored());
PRECONDITION(pMT->IsRestored_NoLogging());
PRECONDITION(pTemplateMD->GetMethodTable()->GetCanonicalMethodTable() == pMT->GetCanonicalMethodTable());
}
CONTRACTL_END
mdMethodDef token = pTemplateMD->GetMemberDef();
// Create a singleton chunk for the method desc
MethodDescChunk *pChunk =
MethodDescChunk::CreateChunk(pAllocator->GetHighFrequencyHeap(),
1,
classification,
TRUE /* fNonVtableSlot*/,
fNativeCodeSlot,
fComPlusCallInfo,
pMT,
pamTracker);
// Now initialize the MDesc at the single method descriptor in
// the new chunk
MethodDesc *pMD = pChunk->GetFirstMethodDesc();
//We copy over the flags one by one. This is fragile w.r.t. adding
// new flags, but other techniques are also fragile. <NICE>We should move
// to using constructors on MethodDesc</NICE>
if (pTemplateMD->IsStatic())
{
pMD->SetStatic();
}
if (pTemplateMD->IsNotInline())
{
pMD->SetNotInline(true);
}
if (pTemplateMD->IsSynchronized())
{
pMD->SetSynchronized();
}
if (pTemplateMD->IsJitIntrinsic())
{
pMD->SetIsJitIntrinsic();
}
pMD->SetMemberDef(token);
pMD->SetSlot(pTemplateMD->GetSlot());
#ifdef _DEBUG
pMD->m_pszDebugMethodName = pTemplateMD->m_pszDebugMethodName;
//<NICE> more info here</NICE>
pMD->m_pszDebugMethodSignature = "<generic method signature>";
pMD->m_pszDebugClassName = "<generic method class name>";
pMD->m_pszDebugMethodName = "<generic method name>";
pMD->m_pDebugMethodTable.SetValue(pMT);
#endif // _DEBUG
return pMD;
}
//
// The following methods map between tightly bound boxing and unboxing MethodDesc.
// We always layout boxing and unboxing MethodDescs next to each other in same
// MethodDescChunk. It allows us to avoid brute-force iteration over all methods
// on the type to perform the mapping.
//
//
// Find matching tightly-bound methoddesc
//
static MethodDesc * FindTightlyBoundWrappedMethodDesc(MethodDesc * pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END
if (pMD->IsUnboxingStub() && pMD->GetClassification() == mcInstantiated)
pMD = pMD->AsInstantiatedMethodDesc()->IMD_GetWrappedMethodDesc();
// Find matching MethodDesc in the MethodTable
if (!pMD->IsTightlyBoundToMethodTable())
pMD = pMD->GetCanonicalMethodTable()->GetParallelMethodDesc(pMD);
_ASSERTE(pMD->IsTightlyBoundToMethodTable());
// Real MethodDesc immediately follows unboxing stub
if (pMD->IsUnboxingStub())
pMD = MethodTable::IntroducedMethodIterator::GetNext(pMD);
_ASSERTE(!pMD->IsUnboxingStub());
return pMD;
}
//
// Find matching tightly-bound unboxing stub if there is one
//
static MethodDesc * FindTightlyBoundUnboxingStub(MethodDesc * pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END
// Find matching MethodDesc in the MethodTable
if (!pMD->IsTightlyBoundToMethodTable())
pMD = pMD->GetCanonicalMethodTable()->GetParallelMethodDesc(pMD);
_ASSERTE(pMD->IsTightlyBoundToMethodTable());
// We are done if we have unboxing stub already
if (pMD->IsUnboxingStub())
return pMD;
//
// Unboxing stub immediately precedes real methoddesc
//
MethodDesc * pCurMD = pMD->GetMethodDescChunk()->GetFirstMethodDesc();
if (pCurMD == pMD)
return NULL;
for (;;)
{
MethodDesc * pNextMD = MethodTable::IntroducedMethodIterator::GetNext(pCurMD);
if (pNextMD == pMD)
break;
pCurMD = pNextMD;
}
return pCurMD->IsUnboxingStub() ? pCurMD : NULL;
}
#ifdef _DEBUG
//
// Alternative brute-force implementation of FindTightlyBoundWrappedMethodDesc for debug-only check.
//
// Please note that this does not do the same up-front checks as the non-debug version to
// see whether or not the input pMD is even an unboxing stub in the first place.
//
static MethodDesc * FindTightlyBoundWrappedMethodDesc_DEBUG(MethodDesc * pMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END
mdMethodDef methodDef = pMD->GetMemberDef();
Module *pModule = pMD->GetModule();
MethodTable::MethodIterator it(pMD->GetCanonicalMethodTable());
it.MoveToEnd();
for (; it.IsValid(); it.Prev()) {
if (!it.IsVirtual()) {
// Get the MethodDesc for current method
MethodDesc* pCurMethod = it.GetMethodDesc();
if (pCurMethod && !pCurMethod->IsUnboxingStub()) {
if ((pCurMethod->GetMemberDef() == methodDef) &&
(pCurMethod->GetModule() == pModule))
{
return pCurMethod;
}
}
}
}
return NULL;
}
//
// Alternative brute-force implementation of FindTightlyBoundUnboxingStub for debug-only check
//
// Please note that this does not do the same up-front checks as the non-debug version to
// see whether or not the input pMD even qualifies to have a corresponding unboxing stub.
//
static MethodDesc * FindTightlyBoundUnboxingStub_DEBUG(MethodDesc * pMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END
mdMethodDef methodDef = pMD->GetMemberDef();
Module *pModule = pMD->GetModule();
MethodTable::MethodIterator it(pMD->GetCanonicalMethodTable());
it.MoveToEnd();
for (; it.IsValid(); it.Prev()) {
if (it.IsVirtual()) {
MethodDesc* pCurMethod = it.GetMethodDesc();
if (pCurMethod && pCurMethod->IsUnboxingStub()) {
if ((pCurMethod->GetMemberDef() == methodDef) &&
(pCurMethod->GetModule() == pModule)) {
return pCurMethod;
}
}
}
}
return NULL;
}
#endif // _DEBUG
/* static */
InstantiatedMethodDesc *
InstantiatedMethodDesc::NewInstantiatedMethodDesc(MethodTable *pExactMT,
MethodDesc* pGenericMDescInRepMT,
MethodDesc* pWrappedMD,
Instantiation methodInst,
BOOL getWrappedCode)
{
CONTRACT(InstantiatedMethodDesc*)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pExactMT));
PRECONDITION(CheckPointer(pGenericMDescInRepMT));
PRECONDITION(pGenericMDescInRepMT->IsRestored());
PRECONDITION(pWrappedMD == NULL || pWrappedMD->IsRestored());
PRECONDITION(methodInst.IsEmpty() || pGenericMDescInRepMT->IsGenericMethodDefinition());
PRECONDITION(methodInst.GetNumArgs() == pGenericMDescInRepMT->GetNumGenericMethodArgs());
POSTCONDITION(CheckPointer(RETVAL));
POSTCONDITION(RETVAL->IsRestored());
POSTCONDITION(getWrappedCode == RETVAL->IsSharedByGenericInstantiations());
POSTCONDITION(methodInst.IsEmpty() || RETVAL->HasMethodInstantiation());
}
CONTRACT_END;
// All instantiated method descs live off the RepMT for the
// instantiated class they live in.
INDEBUG(MethodTable * pCanonMT = pExactMT->GetCanonicalMethodTable();)
_ASSERTE(pGenericMDescInRepMT->GetMethodTable() == pCanonMT);
if (getWrappedCode)
{
_ASSERTE(pWrappedMD == NULL);
_ASSERTE(pExactMT->IsCanonicalMethodTable());
_ASSERTE(pCanonMT == pExactMT);
_ASSERTE(pExactMT->IsSharedByGenericInstantiations() || ClassLoader::IsSharableInstantiation(methodInst));
}
InstantiatedMethodDesc *pNewMD;
//@todo : move this into the domain
Module * pExactMDLoaderModule = ClassLoader::ComputeLoaderModule(pExactMT, pGenericMDescInRepMT->GetMemberDef(), methodInst);
LoaderAllocator * pAllocator = pExactMDLoaderModule->GetLoaderAllocator();
// Create LoaderAllocator to LoaderAllocator links for members of the instantiations of this method
pAllocator->EnsureInstantiation(pExactMT->GetLoaderModule(), pExactMT->GetInstantiation());
pAllocator->EnsureInstantiation(pGenericMDescInRepMT->GetLoaderModule(), methodInst);
{
// Acquire crst to prevent tripping up other threads searching in the same hashtable
CrstHolder ch(&pExactMDLoaderModule->m_InstMethodHashTableCrst);
// Check whether another thread beat us to it!
pNewMD = FindLoadedInstantiatedMethodDesc(pExactMT,
pGenericMDescInRepMT->GetMemberDef(),
methodInst,
getWrappedCode);
// Crst goes out of scope here
// We don't need to hold the crst while we build the MethodDesc, but we reacquire it later
}
if (pNewMD != NULL)
{
pNewMD->CheckRestore();
}
else
{
TypeHandle *pInstOrPerInstInfo = NULL;
DictionaryLayout *pDL = NULL;
DWORD infoSize = 0;
IBCLoggerAwareAllocMemTracker amt;
if (!methodInst.IsEmpty())
{
if (pWrappedMD)
{
if (pWrappedMD->IsSharedByGenericMethodInstantiations())
{
pDL = pWrappedMD->AsInstantiatedMethodDesc()->GetDictLayoutRaw();
}
}
else if (getWrappedCode)
{
// 4 seems like a good number
pDL = DictionaryLayout::Allocate(4, pAllocator, &amt);
#ifdef _DEBUG
{
SString name;
TypeString::AppendMethodDebug(name, pGenericMDescInRepMT);
LOG((LF_JIT, LL_INFO1000, "GENERICS: Created new dictionary layout for dictionary of size %d for %S\n",
DictionaryLayout::GetFirstDictionaryBucketSize(pGenericMDescInRepMT->GetNumGenericMethodArgs(), pDL), name.GetUnicode()));
}
#endif // _DEBUG
}
// Allocate space for the instantiation and dictionary
infoSize = DictionaryLayout::GetFirstDictionaryBucketSize(methodInst.GetNumArgs(), pDL);
pInstOrPerInstInfo = (TypeHandle *) (void*) amt.Track(pAllocator->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(infoSize)));
for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
pInstOrPerInstInfo[i] = methodInst[i];
}
BOOL forComInterop = FALSE;
#ifdef FEATURE_COMINTEROP
if (pExactMT->IsProjectedFromWinRT())
{
forComInterop = (pExactMT->IsInterface() || (pExactMT->IsDelegate() && COMDelegate::IsDelegateInvokeMethod(pGenericMDescInRepMT)));
}
else
{
// redirected interfaces and delegates also support interop
forComInterop = (pExactMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative) ||
(pExactMT->IsWinRTRedirectedDelegate() && COMDelegate::IsDelegateInvokeMethod(pGenericMDescInRepMT)));
}
#endif // FEATURE_COMINTEROP
// Create a new singleton chunk for the new instantiated method descriptor
// Notice that we've passed in the method table pointer; this gets
// used in some of the subsequent setup methods for method descs.
//
pNewMD = (InstantiatedMethodDesc*) (CreateMethodDesc(pAllocator,
pExactMT,
pGenericMDescInRepMT,
mcInstantiated,
!pWrappedMD, // This is pesimistic estimate for fNativeCodeSlot
forComInterop,
&amt));
// Initialize the MD the way it needs to be
if (pWrappedMD)
{
pNewMD->SetupWrapperStubWithInstantiations(pWrappedMD, methodInst.GetNumArgs(), pInstOrPerInstInfo);
_ASSERTE(pNewMD->IsInstantiatingStub());
}
else if (getWrappedCode)
{
pNewMD->SetupSharedMethodInstantiation(methodInst.GetNumArgs(), pInstOrPerInstInfo, pDL);
_ASSERTE(!pNewMD->IsInstantiatingStub());
}
else
{
pNewMD->SetupUnsharedMethodInstantiation(methodInst.GetNumArgs(), pInstOrPerInstInfo);
}
// Check that whichever field holds the inst. got setup correctly
_ASSERTE((PVOID)pNewMD->GetMethodInstantiation().GetRawArgs() == (PVOID)pInstOrPerInstInfo);
pNewMD->SetTemporaryEntryPoint(pAllocator, &amt);
{
// The canonical instantiation is exempt from constraint checks. It's used as the basis
// for all other reference instantiations so we can't not load it. The Canon type is
// not visible to users so it can't be abused.
BOOL fExempt =
TypeHandle::IsCanonicalSubtypeInstantiation(methodInst) ||
TypeHandle::IsCanonicalSubtypeInstantiation(pNewMD->GetClassInstantiation());
if (!fExempt)
{
pNewMD->SatisfiesMethodConstraints(TypeHandle(pExactMT), TRUE);
}
}
// OK, now we have a candidate MethodDesc.
{
CrstHolder ch(&pExactMDLoaderModule->m_InstMethodHashTableCrst);
// We checked before, but make sure again that another thread didn't beat us to it!
InstantiatedMethodDesc *pOldMD = FindLoadedInstantiatedMethodDesc(pExactMT,
pGenericMDescInRepMT->GetMemberDef(),
methodInst,
getWrappedCode);
if (pOldMD == NULL)
{
// No one else got there first, our MethodDesc wins.
amt.SuppressRelease();
#ifdef _DEBUG
SString name(SString::Utf8);
TypeString::AppendMethodDebug(name, pNewMD);
StackScratchBuffer buff;
const char* pDebugNameUTF8 = name.GetUTF8(buff);
const char* verb = "Created";
if (pWrappedMD)
LOG((LF_CLASSLOADER, LL_INFO1000,
"GENERICS: %s instantiating-stub method desc %s with dictionary size %d\n",
verb, pDebugNameUTF8, infoSize));
else
LOG((LF_CLASSLOADER, LL_INFO1000,
"GENERICS: %s instantiated method desc %s\n",
verb, pDebugNameUTF8));
S_SIZE_T safeLen = S_SIZE_T(strlen(pDebugNameUTF8))+S_SIZE_T(1);
if(safeLen.IsOverflow()) COMPlusThrowHR(COR_E_OVERFLOW);
size_t len = safeLen.Value();
pNewMD->m_pszDebugMethodName = (char*) (void*)pAllocator->GetLowFrequencyHeap()->AllocMem(safeLen);
_ASSERTE(pNewMD->m_pszDebugMethodName);
strcpy_s((char *) pNewMD->m_pszDebugMethodName, len, pDebugNameUTF8);
pNewMD->m_pszDebugClassName = pExactMT->GetDebugClassName();
pNewMD->m_pszDebugMethodSignature = (LPUTF8)pNewMD->m_pszDebugMethodName;
#endif // _DEBUG
// Generic methods can't be varargs. code:MethodTableBuilder::ValidateMethods should have checked it.
_ASSERTE(!pNewMD->IsVarArg());
// Verify that we are not creating redundant MethodDescs
_ASSERTE(!pNewMD->IsTightlyBoundToMethodTable());
// The method desc is fully set up; now add to the table
InstMethodHashTable* pTable = pExactMDLoaderModule->GetInstMethodHashTable();
pTable->InsertMethodDesc(pNewMD);
}
else
pNewMD = pOldMD;
// CrstHolder goes out of scope here
}
}
RETURN pNewMD;
}
// Calling this method is equivalent to
// FindOrCreateAssociatedMethodDesc(pCanonicalMD, pExactMT, FALSE, Instantiation(), FALSE, TRUE)
// except that it also creates InstantiatedMethodDescs based on shared class methods. This is
// convenient for interop where, unlike ordinary managed methods, marshaling stubs for say Foo<string>
// and Foo<object> look very different and need separate representation.
InstantiatedMethodDesc*
InstantiatedMethodDesc::FindOrCreateExactClassMethod(MethodTable *pExactMT,
MethodDesc *pCanonicalMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(!pExactMT->IsSharedByGenericInstantiations());
PRECONDITION(pCanonicalMD->IsSharedByGenericInstantiations());
}
CONTRACTL_END;
InstantiatedMethodDesc *pInstMD = FindLoadedInstantiatedMethodDesc(pExactMT,
pCanonicalMD->GetMemberDef(),
Instantiation(),
FALSE);
if (pInstMD == NULL)
{
// create a new MD if not found
pInstMD = NewInstantiatedMethodDesc(pExactMT,
pCanonicalMD,
pCanonicalMD,
Instantiation(),
FALSE);
}
return pInstMD;
}
// N.B. it is not guarantee that the returned InstantiatedMethodDesc is restored.
// It is the caller's responsibility to call CheckRestore on the returned value.
/* static */
InstantiatedMethodDesc*
InstantiatedMethodDesc::FindLoadedInstantiatedMethodDesc(MethodTable *pExactOrRepMT,
mdMethodDef methodDef,
Instantiation methodInst,
BOOL getWrappedCode)
{
CONTRACT(InstantiatedMethodDesc *)
{
THROWS;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pExactOrRepMT));
// All wrapped method descriptors (except BoxedEntryPointStubs, which don't use this path) are
// canonical and exhibit some kind of code sharing.
PRECONDITION(!getWrappedCode || pExactOrRepMT->IsCanonicalMethodTable());
PRECONDITION(!getWrappedCode || pExactOrRepMT->IsSharedByGenericInstantiations() || ClassLoader::IsSharableInstantiation(methodInst));
// Unboxing stubs are dealt with separately in FindOrCreateAssociatedMethodDesc. This should
// probably be streamlined...
POSTCONDITION(!RETVAL || !RETVAL->IsUnboxingStub());
// All wrapped method descriptors (except BoxedEntryPointStubs, which don't use this path) take an inst arg.
// The only ones that don't should have been found in the type's meth table.
POSTCONDITION(!getWrappedCode || !RETVAL || !RETVAL->IsRestored() || RETVAL->RequiresInstArg());
}
CONTRACT_END
// First look in the table for the runtime loader module in case someone created it before any
// zap modules got loaded
Module *pLoaderModule = ClassLoader::ComputeLoaderModule(pExactOrRepMT, methodDef, methodInst);
InstMethodHashTable* pTable = pLoaderModule->GetInstMethodHashTable();
MethodDesc *resultMD = pTable->FindMethodDesc(TypeHandle(pExactOrRepMT),
methodDef,
FALSE /* not forceBoxedEntryPoint */,
methodInst,
getWrappedCode);
if (resultMD != NULL)
RETURN((InstantiatedMethodDesc*) resultMD);
#ifdef FEATURE_PREJIT
// Next look in the preferred zap module
Module *pPreferredZapModule = Module::ComputePreferredZapModule(pExactOrRepMT->GetModule(),
pExactOrRepMT->GetInstantiation(),
methodInst);
if (pPreferredZapModule->HasNativeImage())
{
resultMD = pPreferredZapModule->GetInstMethodHashTable()->FindMethodDesc(TypeHandle(pExactOrRepMT),
methodDef,
FALSE /* not forceBoxedEntryPoint */,
methodInst,
getWrappedCode);
if (resultMD != NULL)
RETURN((InstantiatedMethodDesc*) resultMD);
}
#endif // FEATURE_PREJIT
RETURN(NULL);
}
// Given a method descriptor, find (or create) an instantiated
// method descriptor or BoxedEntryPointStub associated with that method
// and a particular instantiation of any generic method arguments. Also check
// the method instantiation is valid.
//
// This routine also works for non-generic methods - it will be fast
// in most cases. In this case nothing in particular
// occurs except for static methods in shared generic classes, where an
// instantiating stub is needed.
//
// The generic parameters provided are only those for the generic method.
// pExactMT should be used to specify any class parameters.
//
// Unboxing stubs
// --------------
//
// These are required to provide callable addresses with a uniform calling convention
// for all methods on a boxed value class object. There are a wide range of possible
// methods:
// 1 virtual, non-generic instance methods
// 2 non-virtual, non-generic instance methods
// 3 virtual, generic instance methods
// 4 non-virtual, generic instance methods
// There is no substantial difference between case 3 and case 4: the only times
// when BoxedEntryPointStubs are used for non-virtual methods are when calling a delegate or
// making a reflection call.
//
// The only substantial difference between 1 and 2 is that the stubs are stored in
// different places - we are forced to create the BoxedEntryPointStubs for (1) at class
// creation time (they form part of the vtable and dispatch maps). Hence these
// stubs are "owned" by method tables. We store all other stubs in the AssociatedMethTable.
//
// Unboxing stubs and generics
// ---------------------------
//
// Generics code sharing complicates matters. The typical cases are where the struct
// is in a shared-codegenerics struct such as
//
// struct Pair<string,object>
//
// which shares code with other types such as Pair<object,object>. All the code that ends up
// being run for all the methods in such a struct takes an instantiation parameter, i.e.
// is RequiresInstArg(), a non-uniform calling convention. We obviously can't give these out as
// targets of delegate calls. Hence we have to wrap this shared code in various stubs in
// order to get the right type context parameter provided to the shared code.
//
// Unboxing stubs on shared-code generic structs, e.g. Pair<object,string>,
// acquire the class-portion of their type context from the "this" pointer.
//
// Thus there are two flavours of BoxedEntryPointStubs:
//
// - Methods that are not themselves generic:
//
// These wrap possibly-shared code (hence allowInstParam == TRUE).
//
// These directly call the possible-shared code for the instance method. This code
// can have the following calling conventions:
// - RequiresMethodTableInstArg() (if pMT->SharedByGenericInstantiations())
// - Uniform (if !pMT->SharedByGenericInstantiations())
//
// Thus if the code they are
//
// - Methods that are themselves generic:
//
// These wrap unshared code (hence allowInstParam == FALSE):
//
// These are always invoked by slow paths (how often do you use a generic method in a struct?),
// such as JIT_VirtualFunctionPointer or a reflection call. These paths eventually
// use FindOrCreateAssociatedMethodDesc to piece together the exact instantiation provided by the "this"
// pointer with the exact instantiation provided by the wrapped method pointer.
//
// These call a stub for the instance method which provides the instantiation
// context, possibly in turn calling further shared code. This stub will
// always be !RequiresInstArg()
//
// If the method being called is aMethod calls via BoxedEntryPointStubs
//
// Remotable methods
// -----------------
//
// Remoting has high requirements for method descs passed to it (i.e. the method desc that represents the client "view" of the
// method to be called on the real server object). Since the identity of the method call is serialized and passed on the wire before
// be resolved into the real target method on the server remoting needs to be able to extract exact instantiation information from
// its inputs (a method desc and a this pointer).
//
// To that end generic methods should always be passed via an instantiating stub (i.e. set allowInstParam to FALSE when calling
// FindOrCreateAssociatedMethodDesc).
//
// There's a more subtle problem though. If the client method call is via a non-generic method on a generic interface we won't have
// enough information to serialize the call. That's because such methods don't have instantiated method descs by default (these are
// weighty structures and most of the runtime would never use the extra information). The this pointer doesn't help provide the
// additional information in this case (consider the case of a class that implements both IFoo<String> and IFoo<Random>).
//
// So instead we create instantiated interface method descs on demand (i.e. during stub-based interface dispatch). Setting the
// forceRemotableMethod predicate to TRUE below will ensure this (it's a no-op for methods that don't match this pattern, so can be
// freely set to true for all calls intended to produce a remotable ready method). This characteristic of a methoddesc that is fully
// descriptive of the method and class used is also necessary in certain places in reflection. In particular, it is known to be needed
// for the Delegate.CreateDelegate logic.
//
// allowCreate may be set to FALSE to enforce that the method searched
// should already be in existence - thus preventing creation and GCs during
// inappropriate times.
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
/* static */
MethodDesc*
MethodDesc::FindOrCreateAssociatedMethodDesc(MethodDesc* pDefMD,
MethodTable *pExactMT,
BOOL forceBoxedEntryPoint,
Instantiation methodInst,
BOOL allowInstParam,
BOOL forceRemotableMethod,
BOOL allowCreate,
ClassLoadLevel level)
{
CONTRACT(MethodDesc*)
{
THROWS;
if (allowCreate) { GC_TRIGGERS; } else { GC_NOTRIGGER; }
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pDefMD));
PRECONDITION(CheckPointer(pExactMT));
PRECONDITION(pDefMD->IsRestored_NoLogging());
PRECONDITION(pExactMT->IsRestored_NoLogging());
// If the method descriptor belongs to a generic type then
// the input exact type must be an instantiation of that type.
// DISABLED PRECONDITION - too strict - the classes may be in
// a subtype relation to each other.
//
// PRECONDITION(!pDefMD->HasClassInstantiation() || pDefMD->GetMethodTable()->HasSameTypeDefAs(pExactMT));
// You may only request an BoxedEntryPointStub for an instance method on a value type
PRECONDITION(!forceBoxedEntryPoint || pExactMT->IsValueType());
PRECONDITION(!forceBoxedEntryPoint || !pDefMD->IsStatic());
// For remotable methods we better not be allowing instantiation parameters.
PRECONDITION(!forceRemotableMethod || !allowInstParam);
POSTCONDITION(((RETVAL == NULL) && !allowCreate) || CheckPointer(RETVAL));
POSTCONDITION(((RETVAL == NULL) && !allowCreate) || RETVAL->IsRestored());
POSTCONDITION(((RETVAL == NULL) && !allowCreate) || forceBoxedEntryPoint || !RETVAL->IsUnboxingStub());
POSTCONDITION(((RETVAL == NULL) && !allowCreate) || allowInstParam || !RETVAL->RequiresInstArg());
}
CONTRACT_END;
// Quick exit for the common cases where the result is the same as the primary MD we are given
if (!pDefMD->HasClassOrMethodInstantiation() &&
methodInst.IsEmpty() &&
!forceBoxedEntryPoint &&
!pDefMD->IsUnboxingStub())
{
// Make sure that pDefMD->GetMethodTable() and pExactMT are related types even
// if we took the fast path.
_ASSERTE(pDefMD->IsArray() || pDefMD->GetExactDeclaringType(pExactMT) != NULL);
RETURN pDefMD;
}
// Get the version of the method desc. for the instantiated shared class, e.g.
// e.g. if pDefMD == List<T>.m()
// pExactMT = List<string>
// then pMDescInCanonMT = List<object>.m()
// or
// e.g. if pDefMD == List<T>.m<U>()
// pExactMT = List<string>
// then pMDescInCanonMT = List<object>.m<U>()
MethodDesc * pMDescInCanonMT = pDefMD;
// Some callers pass a pExactMT that is a subtype of a parent type of pDefMD.
// Find the actual exact parent of pDefMD.
pExactMT = pDefMD->GetExactDeclaringType(pExactMT);
_ASSERTE(pExactMT != NULL);
if (pDefMD->HasClassOrMethodInstantiation() || !methodInst.IsEmpty())
{
// General checks related to generics: arity (if any) must match and generic method
// instantiation (if any) must be well-formed.
if (pDefMD->GetNumGenericMethodArgs() != methodInst.GetNumArgs() ||
!Generics::CheckInstantiation(methodInst))
{
COMPlusThrowHR(COR_E_BADIMAGEFORMAT);
}
pMDescInCanonMT = pExactMT->GetCanonicalMethodTable()->GetParallelMethodDesc(pDefMD);
if (!allowCreate && (!pMDescInCanonMT->IsRestored() ||
!pMDescInCanonMT->GetMethodTable()->IsFullyLoaded()))
{
RETURN(NULL);
}
pMDescInCanonMT->CheckRestore(level);
}
// This case covers nearly all "normal" (i.e. non-associate) MethodDescs. Just return
// the MethodDesc in the canonical method table.
//
// Also, it will be taken for methods which acquire their type context from the "this" parameter
// - we don't need instantiating stubs for these.
if ( methodInst.IsEmpty()
&& (allowInstParam || !pMDescInCanonMT->RequiresInstArg())
&& (forceBoxedEntryPoint == pMDescInCanonMT->IsUnboxingStub())
&& (!forceRemotableMethod || !pMDescInCanonMT->IsInterface()
|| !pMDescInCanonMT->GetMethodTable()->IsSharedByGenericInstantiations()) )
{
RETURN(pMDescInCanonMT);
}
// Unboxing stubs
else if (forceBoxedEntryPoint)
{
// This assert isn't quite right, for example the repro from NDPWhidbey 18737
// fires it, because we fetch an BoxedEntryPointStub for a virtual method on a struct
// when the uninstantiated MethodDesc for the generic virtual method actually
// qualifies as an BoxedEntryPointStub... Hence we weaken the assert a little.
//
// _ASSERTE(!pDefMD->IsUnboxingStub());
// _ASSERTE(pDefMD->IsGenericMethodDefinition() || !pDefMD->IsUnboxingStub());
//Unboxing stubs for non-generic methods and generic methods are
// subtly different... For non-generic methods we can look in the
// shared vtable, and then go to the hash table only if needed.
// Furthermore even if we have to go to hash table we still base
// the BoxedEntryPointStub on an unerlying _shared_ method descriptor.
//
// For generic methods we must build an BoxedEntryPointStub that calls an
// underlying instantiating stub. The underlying instantiating stub
// will be an _exact_ method descriptor.
MethodDesc *pResultMD;
if (methodInst.IsEmpty())
{
// First search for the unboxing MD in the shared vtable for the value type
pResultMD = FindTightlyBoundUnboxingStub(pMDescInCanonMT);
// Verify that we get the same result by alternative method. There is a possibility
// that there is no associated unboxing stub, and FindTightlyBoundUnboxingStub takes
// this into account but the _DEBUG version does not, so only use it if the method
// returned is actually different.
_ASSERTE(pResultMD == pMDescInCanonMT ||
pResultMD == FindTightlyBoundUnboxingStub_DEBUG(pMDescInCanonMT));
if (pResultMD != NULL)
{
_ASSERTE(pResultMD->IsRestored() && pResultMD->GetMethodTable()->IsFullyLoaded());
g_IBCLogger.LogMethodDescAccess(pResultMD);
RETURN(pResultMD);
}
MethodTable *pRepMT = pMDescInCanonMT->GetMethodTable();
mdMethodDef methodDef = pDefMD->GetMemberDef();
Module *pLoaderModule = ClassLoader::ComputeLoaderModule(pRepMT, methodDef, methodInst);
LoaderAllocator* pAllocator=pLoaderModule->GetLoaderAllocator();
InstMethodHashTable* pTable = pLoaderModule->GetInstMethodHashTable();
// If we didn't find it there then go to the hash table
pResultMD = pTable->FindMethodDesc(TypeHandle(pRepMT),
methodDef,
TRUE /* forceBoxedEntryPoint */,
Instantiation(),
FALSE /* no inst param */);
// If we didn't find it then create it...
if (!pResultMD)
{
// !allowCreate ==> GC_NOTRIGGER ==> no entering Crst
if (!allowCreate)
{
RETURN(NULL);
}
CrstHolder ch(&pLoaderModule->m_InstMethodHashTableCrst);
// Check whether another thread beat us to it!
pResultMD = pTable->FindMethodDesc(TypeHandle(pRepMT),
methodDef,
TRUE,
Instantiation(),
FALSE);
if (pResultMD == NULL)
{
IBCLoggerAwareAllocMemTracker amt;
pResultMD = CreateMethodDesc(pAllocator,
pRepMT,
pMDescInCanonMT,
mcInstantiated,
FALSE /* fNativeCodeSlot */,
FALSE /* fComPlusCallInfo */,
&amt);
// Indicate that this is a stub method which takes a BOXed this pointer.
// An BoxedEntryPointStub may still be an InstantiatedMethodDesc
pResultMD->SetIsUnboxingStub();
pResultMD->AsInstantiatedMethodDesc()->SetupWrapperStubWithInstantiations(pMDescInCanonMT, NULL, NULL);
pResultMD->SetTemporaryEntryPoint(pAllocator, &amt);
amt.SuppressRelease();
// Verify that we are not creating redundant MethodDescs
_ASSERTE(!pResultMD->IsTightlyBoundToMethodTable());
// Add it to the table
pTable->InsertMethodDesc(pResultMD);
}
// CrstHolder goes out of scope here
}
}
else
{
mdMethodDef methodDef = pDefMD->GetMemberDef();
Module *pLoaderModule = ClassLoader::ComputeLoaderModule(pExactMT, methodDef, methodInst);
LoaderAllocator* pAllocator = pLoaderModule->GetLoaderAllocator();
InstMethodHashTable* pTable = pLoaderModule->GetInstMethodHashTable();
// First check the hash table...
pResultMD = pTable->FindMethodDesc(TypeHandle(pExactMT),
methodDef,
TRUE, /* forceBoxedEntryPoint */
methodInst,
FALSE /* no inst param */);
if (!pResultMD)
{
// !allowCreate ==> GC_NOTRIGGER ==> no entering Crst
if (!allowCreate)
{
RETURN(NULL);
}
// Enter the critical section *after* we've found or created the non-unboxing instantiating stub (else we'd have a race)
CrstHolder ch(&pLoaderModule->m_InstMethodHashTableCrst);
// Check whether another thread beat us to it!
pResultMD = pTable->FindMethodDesc(TypeHandle(pExactMT),
methodDef,
TRUE, /* forceBoxedEntryPoint */
methodInst,
FALSE /* no inst param */);
if (pResultMD == NULL)
{
// Recursively get the non-unboxing instantiating stub. Thus we chain an unboxing
// stub with an instantiating stub.
MethodDesc* pNonUnboxingStub=
MethodDesc::FindOrCreateAssociatedMethodDesc(pDefMD,
pExactMT,
FALSE /* not Unboxing */,
methodInst,
FALSE);
_ASSERTE(pNonUnboxingStub->GetClassification() == mcInstantiated);
_ASSERTE(!pNonUnboxingStub->RequiresInstArg());
_ASSERTE(!pNonUnboxingStub->IsUnboxingStub());
IBCLoggerAwareAllocMemTracker amt;
_ASSERTE(pDefMD->GetClassification() == mcInstantiated);
pResultMD = CreateMethodDesc(pAllocator,
pExactMT,