-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
methodtable.cpp
9667 lines (8272 loc) · 347 KB
/
methodtable.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.
//
// File: methodtable.cpp
//
#include "common.h"
#include "clsload.hpp"
#include "method.hpp"
#include "class.h"
#include "classcompat.h"
#include "object.h"
#include "field.h"
#include "util.hpp"
#include "excep.h"
#include "siginfo.hpp"
#include "threads.h"
#include "stublink.h"
#include "ecall.h"
#include "dllimport.h"
#include "gcdesc.h"
#include "jitinterface.h"
#include "eeconfig.h"
#include "log.h"
#include "fieldmarshaler.h"
#include "cgensys.h"
#include "gcheaputilities.h"
#include "dbginterface.h"
#include "comdelegate.h"
#include "eventtrace.h"
#include "eeprofinterfaces.h"
#include "dllimportcallback.h"
#include "listlock.h"
#include "methodimpl.h"
#include "guidfromname.h"
#include "encee.h"
#include "encee.h"
#include "comsynchronizable.h"
#include "customattribute.h"
#include "virtualcallstub.h"
#include "contractimpl.h"
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#include "clrtocomcall.h"
#include "runtimecallablewrapper.h"
#endif // FEATURE_COMINTEROP
#include "typeequivalencehash.hpp"
#include "generics.h"
#include "genericdict.h"
#include "typestring.h"
#include "typedesc.h"
#include "array.h"
#include "castcache.h"
#include "dynamicinterfacecastable.h"
#include "frozenobjectheap.h"
#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#endif // FEATURE_INTERPRETER
#ifndef DACCESS_COMPILE
// Typedef for string comparison functions.
typedef int (__cdecl *UTF8StringCompareFuncPtr)(const char *, const char *);
MethodDataCache *MethodTable::s_pMethodDataCache = NULL;
#ifdef _DEBUG
extern unsigned g_dupMethods;
#endif
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
//==========================================================================================
class MethodDataCache
{
typedef MethodTable::MethodData MethodData;
public: // Ctor. Allocates cEntries entries. Throws.
static UINT32 GetObjectSize(UINT32 cEntries);
MethodDataCache(UINT32 cEntries);
MethodData *Find(MethodTable *pMT);
MethodData *Find(MethodTable *pMTDecl, MethodTable *pMTImpl);
void Insert(MethodData *pMData);
void Clear();
protected:
// This describes each entry in the cache.
struct Entry
{
MethodData *m_pMData;
UINT32 m_iTimestamp;
};
MethodData *FindHelper(MethodTable *pMTDecl, MethodTable *pMTImpl, UINT32 idx);
inline UINT32 GetNextTimestamp()
{ return ++m_iCurTimestamp; }
inline UINT32 NumEntries()
{ LIMITED_METHOD_CONTRACT; return m_cEntries; }
inline void TouchEntry(UINT32 i)
{ WRAPPER_NO_CONTRACT; m_iLastTouched = i; GetEntry(i)->m_iTimestamp = GetNextTimestamp(); }
inline UINT32 GetLastTouchedEntryIndex()
{ WRAPPER_NO_CONTRACT; return m_iLastTouched; }
// The end of this object contains an array of Entry
inline Entry *GetEntryData()
{ LIMITED_METHOD_CONTRACT; return (Entry *)(this + 1); }
inline Entry *GetEntry(UINT32 i)
{ WRAPPER_NO_CONTRACT; return GetEntryData() + i; }
private:
// This serializes access to the cache
SimpleRWLock m_lock;
// This allows ageing of entries to decide which to punt when
// inserting a new entry.
UINT32 m_iCurTimestamp;
// The number of entries in the cache
UINT32 m_cEntries;
UINT32 m_iLastTouched;
#ifdef HOST_64BIT
UINT32 pad; // insures that we are a multiple of 8-bytes
#endif
}; // class MethodDataCache
//==========================================================================================
UINT32 MethodDataCache::GetObjectSize(UINT32 cEntries)
{
LIMITED_METHOD_CONTRACT;
return sizeof(MethodDataCache) + (sizeof(Entry) * cEntries);
}
//==========================================================================================
MethodDataCache::MethodDataCache(UINT32 cEntries)
: m_lock(COOPERATIVE_OR_PREEMPTIVE, LOCK_TYPE_DEFAULT),
m_iCurTimestamp(0),
m_cEntries(cEntries),
m_iLastTouched(0)
{
WRAPPER_NO_CONTRACT;
ZeroMemory(GetEntryData(), cEntries * sizeof(Entry));
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::FindHelper(
MethodTable *pMTDecl, MethodTable *pMTImpl, UINT32 idx)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
MethodData *pEntry = GetEntry(idx)->m_pMData;
if (pEntry != NULL) {
MethodTable *pMTDeclEntry = pEntry->GetDeclMethodTable();
MethodTable *pMTImplEntry = pEntry->GetImplMethodTable();
if (pMTDeclEntry == pMTDecl && pMTImplEntry == pMTImpl) {
return pEntry;
}
else if (pMTDecl == pMTImpl) {
if (pMTDeclEntry == pMTDecl) {
return pEntry->GetDeclMethodData();
}
if (pMTImplEntry == pMTDecl) {
return pEntry->GetImplMethodData();
}
}
}
return NULL;
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::Find(MethodTable *pMTDecl, MethodTable *pMTImpl)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
#ifdef LOGGING
g_sdStats.m_cCacheLookups++;
#endif
SimpleReadLockHolder lh(&m_lock);
// Check the last touched entry.
MethodData *pEntry = FindHelper(pMTDecl, pMTImpl, GetLastTouchedEntryIndex());
// Now search the entire cache.
if (pEntry == NULL) {
for (UINT32 i = 0; i < NumEntries(); i++) {
pEntry = FindHelper(pMTDecl, pMTImpl, i);
if (pEntry != NULL) {
TouchEntry(i);
break;
}
}
}
if (pEntry != NULL) {
pEntry->AddRef();
}
#ifdef LOGGING
else {
// Failure to find the entry in the cache.
g_sdStats.m_cCacheMisses++;
}
#endif // LOGGING
return pEntry;
}
//==========================================================================================
MethodTable::MethodData *MethodDataCache::Find(MethodTable *pMT)
{
WRAPPER_NO_CONTRACT;
return Find(pMT, pMT);
}
//==========================================================================================
void MethodDataCache::Insert(MethodData *pMData)
{
CONTRACTL {
NOTHROW; // for now, because it does not yet resize.
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
SimpleWriteLockHolder hLock(&m_lock);
UINT32 iMin = UINT32_MAX;
UINT32 idxMin = UINT32_MAX;
for (UINT32 i = 0; i < NumEntries(); i++) {
if (GetEntry(i)->m_iTimestamp < iMin) {
idxMin = i;
iMin = GetEntry(i)->m_iTimestamp;
}
}
Entry *pEntry = GetEntry(idxMin);
if (pEntry->m_pMData != NULL) {
pEntry->m_pMData->Release();
}
pMData->AddRef();
pEntry->m_pMData = pMData;
pEntry->m_iTimestamp = GetNextTimestamp();
}
//==========================================================================================
void MethodDataCache::Clear()
{
CONTRACTL {
NOTHROW; // for now, because it does not yet resize.
GC_NOTRIGGER;
INSTANCE_CHECK;
} CONTRACTL_END;
// Taking the lock here is just a precaution. Really, the runtime
// should be suspended because this is called while unloading an
// AppDomain at the SysSuspendEE stage. But, if someone calls it
// outside of that context, we should be extra cautious.
SimpleWriteLockHolder lh(&m_lock);
for (UINT32 i = 0; i < NumEntries(); i++) {
Entry *pEntry = GetEntry(i);
if (pEntry->m_pMData != NULL) {
pEntry->m_pMData->Release();
}
}
ZeroMemory(GetEntryData(), NumEntries() * sizeof(Entry));
m_iCurTimestamp = 0;
} // MethodDataCache::Clear
#endif // !DACCESS_COMPILE
//==========================================================================================
// Optimization intended for MethodTable::GetDispatchMap
#include <optsmallperfcritical.h>
//==========================================================================================
PTR_DispatchMap MethodTable::GetDispatchMap()
{
LIMITED_METHOD_DAC_CONTRACT;
MethodTable * pMT = this;
if (!pMT->HasDispatchMapSlot())
{
pMT = pMT->GetCanonicalMethodTable();
if (!pMT->HasDispatchMapSlot())
return NULL;
}
return dac_cast<PTR_DispatchMap>((pMT->GetAuxiliaryData() + 1));
}
#include <optdefault.h>
//==========================================================================================
PTR_Module MethodTable::GetModuleIfLoaded()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END;
return GetModule();
}
//==========================================================================================
BOOL MethodTable::ValidateWithPossibleAV()
{
CANNOT_HAVE_CONTRACT;
SUPPORTS_DAC;
// MethodTables have the canonicalization property below.
// i.e. canonicalize, and canonicalize again, and check the result are
// the same. This is a property that holds for every single valid object in
// the system, but which should hold for very few other addresses.
// For non-generic classes, we can rely on comparing
// object->methodtable->class->methodtable
// to
// object->methodtable
//
// However, for generic instantiation this does not work. There we must
// compare
//
// object->methodtable->class->methodtable->class
// to
// object->methodtable->class
//
// Of course, that's not necessarily enough to verify that the method
// table and class are absolutely valid - we rely on type soundness
// for that. We need to do more sanity checking to
// make sure that our pointer here is in fact a valid object.
PTR_EEClass pEEClass = this->GetClassWithPossibleAV();
return ((pEEClass && (this == pEEClass->GetMethodTableWithPossibleAV())) ||
((HasInstantiation() || IsArray()) &&
(pEEClass && (pEEClass->GetMethodTableWithPossibleAV()->GetClassWithPossibleAV() == pEEClass))));
}
#ifndef DACCESS_COMPILE
//==========================================================================================
BOOL MethodTable::IsClassInited()
{
WRAPPER_NO_CONTRACT;
if (IsClassPreInited())
return TRUE;
if (IsSharedByGenericInstantiations())
return FALSE;
DomainLocalModule *pLocalModule = GetDomainLocalModule();
_ASSERTE(pLocalModule != NULL);
return pLocalModule->IsClassInitialized(this);
}
//==========================================================================================
BOOL MethodTable::IsInitError()
{
WRAPPER_NO_CONTRACT;
DomainLocalModule *pLocalModule = GetDomainLocalModule();
_ASSERTE(pLocalModule != NULL);
return pLocalModule->IsClassInitError(this);
}
//==========================================================================================
// mark the class as having its .cctor run
void MethodTable::SetClassInited()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(!IsClassPreInited());
GetDomainLocalModule()->SetClassInitialized(this);
}
//==========================================================================================
void MethodTable::SetClassInitError()
{
WRAPPER_NO_CONTRACT;
GetDomainLocalModule()->SetClassInitError(this);
}
//==========================================================================================
// mark as COM object type (System.__ComObject and types deriving from it)
void MethodTable::SetComObjectType()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_ComObject);
}
#ifdef FEATURE_ICASTABLE
void MethodTable::SetICastable()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_ICastable);
}
#endif
BOOL MethodTable::IsICastable()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_ICASTABLE
return GetFlag(enum_flag_ICastable);
#else
return FALSE;
#endif
}
void MethodTable::SetIDynamicInterfaceCastable()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_IDynamicInterfaceCastable);
}
BOOL MethodTable::IsIDynamicInterfaceCastable()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetFlag(enum_flag_IDynamicInterfaceCastable);
}
void MethodTable::SetIsTrackedReferenceWithFinalizer()
{
LIMITED_METHOD_CONTRACT;
SetFlag(enum_flag_IsTrackedReferenceWithFinalizer);
}
#endif // !DACCESS_COMPILE
BOOL MethodTable::IsTrackedReferenceWithFinalizer()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetFlag(enum_flag_IsTrackedReferenceWithFinalizer);
}
//==========================================================================================
WORD MethodTable::GetNumMethods()
{
LIMITED_METHOD_DAC_CONTRACT;
return GetClass()->GetNumMethods();
}
PTR_MethodTable MethodTable::GetTypicalMethodTable()
{
LIMITED_METHOD_DAC_CONTRACT;
if (IsArray())
return (PTR_MethodTable)this;
PTR_MethodTable methodTableMaybe = GetModule()->LookupTypeDef(GetCl()).AsMethodTable();
_ASSERTE(methodTableMaybe->IsTypicalTypeDefinition());
return methodTableMaybe;
}
//==========================================================================================
BOOL MethodTable::HasSameTypeDefAs(MethodTable *pMT)
{
LIMITED_METHOD_DAC_CONTRACT;
if (this == pMT)
return TRUE;
// optimize for the negative case where we expect RID mismatch
DWORD rid = GetTypeDefRid();
if (rid != pMT->GetTypeDefRid())
return FALSE;
// Types without RIDs are unrelated to each other. This case is taken for arrays.
if (rid == 0)
return FALSE;
return (GetModule() == pMT->GetModule());
}
#ifndef DACCESS_COMPILE
//==========================================================================================
PTR_MethodTable InterfaceInfo_t::GetApproxMethodTable(Module * pContainingModule)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
MethodTable * pItfMT = GetMethodTable();
ClassLoader::EnsureLoaded(TypeHandle(pItfMT), CLASS_LOAD_APPROXPARENTS);
return pItfMT;
}
//==========================================================================================
// get the method desc given the interface method desc
/* static */ MethodDesc *MethodTable::GetMethodDescForInterfaceMethodAndServer(
TypeHandle ownerType, MethodDesc *pItfMD, OBJECTREF *pServer)
{
CONTRACT(MethodDesc*)
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pItfMD));
PRECONDITION(pItfMD->IsInterface());
PRECONDITION(!ownerType.IsNull());
PRECONDITION(ownerType.GetMethodTable()->HasSameTypeDefAs(pItfMD->GetMethodTable()));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
VALIDATEOBJECTREF(*pServer);
#ifdef _DEBUG
MethodTable * pItfMT = ownerType.GetMethodTable();
PREFIX_ASSUME(pItfMT != NULL);
#endif // _DEBUG
MethodTable *pServerMT = (*pServer)->GetMethodTable();
PREFIX_ASSUME(pServerMT != NULL);
#ifdef FEATURE_ICASTABLE
// In case of ICastable, instead of trying to find method implementation in the real object type
// we call GetMethodDescForInterfaceMethod() again with whatever type it returns.
// It allows objects that implement ICastable to mimic behavior of other types.
if (pServerMT->IsICastable() &&
!pItfMD->HasMethodInstantiation() &&
!TypeHandle(pServerMT).CanCastTo(ownerType)) // we need to make sure object doesn't implement this interface in a natural way
{
GCStress<cfg_any>::MaybeTrigger();
// Make call to ICastableHelpers.GetImplType(obj, interfaceTypeObj)
PREPARE_NONVIRTUAL_CALLSITE(METHOD__ICASTABLEHELPERS__GETIMPLTYPE);
OBJECTREF ownerManagedType = ownerType.GetManagedClassObject(); //GC triggers
DECLARE_ARGHOLDER_ARRAY(args, 2);
args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*pServer);
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(ownerManagedType);
OBJECTREF impTypeObj = NULL;
CALL_MANAGED_METHOD_RETREF(impTypeObj, OBJECTREF, args);
INDEBUG(ownerManagedType = NULL); //ownerManagedType wasn't protected during the call
if (impTypeObj == NULL) // GetImplType returns default(RuntimeTypeHandle)
{
COMPlusThrow(kEntryPointNotFoundException);
}
ReflectClassBaseObject* resultTypeObj = ((ReflectClassBaseObject*)OBJECTREFToObject(impTypeObj));
TypeHandle resultTypeHnd = resultTypeObj->GetType();
MethodTable *pResultMT = resultTypeHnd.GetMethodTable();
RETURN(pResultMT->GetMethodDescForInterfaceMethod(ownerType, pItfMD, TRUE /* throwOnConflict */));
}
#endif
// For IDynamicInterfaceCastable, instead of trying to find method implementation in the real object type
// we call GetInterfaceImplementation on the object and call GetMethodDescForInterfaceMethod
// with whatever type it returns.
if (pServerMT->IsIDynamicInterfaceCastable()
&& !TypeHandle(pServerMT).CanCastTo(ownerType)) // we need to make sure object doesn't implement this interface in a natural way
{
TypeHandle implTypeHandle;
OBJECTREF obj = *pServer;
GCPROTECT_BEGIN(obj);
OBJECTREF implTypeRef = DynamicInterfaceCastable::GetInterfaceImplementation(&obj, ownerType);
_ASSERTE(implTypeRef != NULL);
ReflectClassBaseObject *implTypeObj = ((ReflectClassBaseObject *)OBJECTREFToObject(implTypeRef));
implTypeHandle = implTypeObj->GetType();
GCPROTECT_END();
RETURN(implTypeHandle.GetMethodTable()->GetMethodDescForInterfaceMethod(ownerType, pItfMD, TRUE /* throwOnConflict */));
}
#ifdef FEATURE_COMINTEROP
if (pServerMT->IsComObjectType() && !pItfMD->HasMethodInstantiation())
{
// interop needs an exact MethodDesc
pItfMD = MethodDesc::FindOrCreateAssociatedMethodDesc(
pItfMD,
ownerType.GetMethodTable(),
FALSE, // forceBoxedEntryPoint
Instantiation(), // methodInst
FALSE, // allowInstParam
TRUE); // forceRemotableMethod
RETURN(pServerMT->GetMethodDescForComInterfaceMethod(pItfMD, false));
}
#endif // !FEATURE_COMINTEROP
// Handle pure COM+ types.
RETURN (pServerMT->GetMethodDescForInterfaceMethod(ownerType, pItfMD, TRUE /* throwOnConflict */));
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
// get the method desc given the interface method desc on a COM implemented server
// (if fNullOk is set then NULL is an allowable return value)
MethodDesc *MethodTable::GetMethodDescForComInterfaceMethod(MethodDesc *pItfMD, bool fNullOk)
{
CONTRACT(MethodDesc*)
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pItfMD));
PRECONDITION(pItfMD->IsInterface());
PRECONDITION(IsComObjectType());
POSTCONDITION(fNullOk || CheckPointer(RETVAL));
}
CONTRACT_END;
MethodTable * pItfMT = pItfMD->GetMethodTable();
PREFIX_ASSUME(pItfMT != NULL);
// We now handle __ComObject class that doesn't have Dynamic Interface Map
if (!HasDynamicInterfaceMap())
{
RETURN(pItfMD);
}
else
{
// Now we handle the more complex extensible RCW's. The first thing to do is check
// to see if the static definition of the extensible RCW specifies that the class
// implements the interface.
DWORD slot = (DWORD) -1;
// Calling GetTarget here instead of FindDispatchImpl gives us caching functionality to increase speed.
PCODE tgt = VirtualCallStubManager::GetTarget(
pItfMT->GetLoaderAllocator()->GetDispatchToken(pItfMT->GetTypeID(), pItfMD->GetSlot()), this, TRUE /* throwOnConflict */);
if (tgt != NULL)
{
RETURN(MethodTable::GetMethodDescForSlotAddress(tgt));
}
// The interface is not in the static class definition so we need to look at the
// dynamic interfaces.
else if (FindDynamicallyAddedInterface(pItfMT))
{
// This interface was added to the class dynamically so it is implemented
// by the COM object. We treat this dynamically added interfaces the same
// way we treat COM objects. That is by using the interface vtable.
RETURN(pItfMD);
}
else
{
RETURN(NULL);
}
}
}
#endif // FEATURE_COMINTEROP
void MethodTable::AllocateAuxiliaryData(LoaderAllocator *pAllocator, Module *pLoaderModule, AllocMemTracker *pamTracker, bool hasGenericStatics, WORD nonVirtualSlots, S_SIZE_T extraAllocation)
{
S_SIZE_T cbAuxiliaryData = S_SIZE_T(sizeof(MethodTableAuxiliaryData));
size_t prependedAllocationSpace = 0;
prependedAllocationSpace = nonVirtualSlots * sizeof(TADDR);
if (hasGenericStatics)
prependedAllocationSpace = prependedAllocationSpace + sizeof(GenericsStaticsInfo);
cbAuxiliaryData = cbAuxiliaryData + S_SIZE_T(prependedAllocationSpace) + extraAllocation;
if (cbAuxiliaryData.IsOverflow())
ThrowHR(COR_E_OVERFLOW);
BYTE* pAuxiliaryDataRegion = (BYTE *)
pamTracker->Track(pAllocator->GetHighFrequencyHeap()->AllocMem(cbAuxiliaryData));
MethodTableAuxiliaryData * pMTAuxiliaryData;
pMTAuxiliaryData = (MethodTableAuxiliaryData *)(pAuxiliaryDataRegion + prependedAllocationSpace);
pMTAuxiliaryData->SetLoaderModule(pLoaderModule);
pMTAuxiliaryData->SetOffsetToNonVirtualSlots(hasGenericStatics ? -(int16_t)sizeof(GenericsStaticsInfo) : 0);
m_pAuxiliaryData = pMTAuxiliaryData;
}
//---------------------------------------------------------------------------------------
//
MethodTable* CreateMinimalMethodTable(Module* pContainingModule,
LoaderAllocator* pLoaderAllocator,
AllocMemTracker* pamTracker)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
EEClass* pClass = EEClass::CreateMinimalClass(pLoaderAllocator->GetHighFrequencyHeap(), pamTracker);
LOG((LF_BCL, LL_INFO100, "Level2 - Creating MethodTable {0x%p}...\n", pClass));
MethodTable* pMT = (MethodTable *)(void *)pamTracker->Track(pLoaderAllocator->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(MethodTable))));
// Note: Memory allocated on loader heap is zero filled
// memset(pMT, 0, sizeof(MethodTable));
// Allocate the private data block ("private" during runtime in the ngen'ed case).
pMT->AllocateAuxiliaryData(pLoaderAllocator, pContainingModule, pamTracker);
pMT->SetModule(pContainingModule);
pMT->SetLoaderAllocator(pLoaderAllocator);
//
// Set up the EEClass
//
pClass->SetMethodTable(pMT); // in the EEClass set the pointer to this MethodTable
pClass->SetAttrClass(tdPublic | tdSealed);
//
// Set up the MethodTable
//
// Does not need parent. Note that MethodTable for COR_GLOBAL_PARENT_TOKEN does not have parent either,
// so the system has to be wired for dealing with no parent anyway.
pMT->SetParentMethodTable(NULL);
pMT->SetClass(pClass);
pMT->SetInternalCorElementType(ELEMENT_TYPE_CLASS);
pMT->SetBaseSize(OBJECT_BASESIZE);
#ifdef _DEBUG
pClass->SetDebugClassName("dynamicClass");
pMT->SetDebugClassName("dynamicClass");
#endif
LOG((LF_BCL, LL_INFO10, "Level1 - MethodTable created {0x%p}\n", pClass));
return pMT;
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
OBJECTREF MethodTable::GetObjCreateDelegate()
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
_ASSERT(!IsInterface());
if (GetOHDelegate())
return ObjectFromHandle(GetOHDelegate());
else
return NULL;
}
//==========================================================================================
void MethodTable::SetObjCreateDelegate(OBJECTREF orDelegate)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
THROWS; // From CreateHandle
}
CONTRACTL_END;
if (GetOHDelegate())
StoreObjectInHandle(GetOHDelegate(), orDelegate);
else
SetOHDelegate (GetAppDomain()->CreateHandle(orDelegate));
}
#endif // FEATURE_COMINTEROP
//==========================================================================================
void MethodTable::SetInterfaceMap(WORD wNumInterfaces, InterfaceInfo_t* iMap)
{
LIMITED_METHOD_CONTRACT;
if (wNumInterfaces == 0)
{
_ASSERTE(!HasInterfaceMap());
return;
}
m_wNumInterfaces = wNumInterfaces;
CONSISTENCY_CHECK(IS_ALIGNED(iMap, sizeof(void*)));
m_pInterfaceMap = iMap;
}
//==========================================================================================
// Called after GetExtraInterfaceInfoSize above to setup a new MethodTable with the additional memory to track
// extra interface info. If there are a non-zero number of interfaces implemented on this class but
// GetExtraInterfaceInfoSize() returned zero, this call must still be made (with a NULL argument).
void MethodTable::InitializeExtraInterfaceInfo(PVOID pInfo)
{
STANDARD_VM_CONTRACT;
// Check that memory was allocated or not allocated in the right scenarios.
_ASSERTE(((pInfo == NULL) && (GetExtraInterfaceInfoSize(GetNumInterfaces()) == 0)) ||
((pInfo != NULL) && (GetExtraInterfaceInfoSize(GetNumInterfaces()) != 0)));
// This call is a no-op if we don't require extra interface info (in which case a buffer should never have
// been allocated).
if (!HasExtraInterfaceInfo())
{
_ASSERTE(pInfo == NULL);
return;
}
// Get pointer to optional slot that holds either a small inlined bitmap of flags or the pointer to a
// larger bitmap.
PTR_TADDR pInfoSlot = GetExtraInterfaceInfoPtr();
// In either case, data inlined or held in an external buffer, the correct thing to do is to write pInfo
// to the slot. In the inlined case we wish to set all flags to their default value (zero, false) and
// writing NULL does that. Otherwise we simply want to dump the buffer pointer directly into the slot (no
// need for a discriminator bit, we can always infer which format we're using based on the interface
// count).
*pInfoSlot = (TADDR)pInfo;
// There shouldn't be any need for further initialization in the buffered case since loader heap
// allocation zeroes data.
#ifdef _DEBUG
if (pInfo != NULL)
for (DWORD i = 0; i < GetExtraInterfaceInfoSize(GetNumInterfaces()); i++)
_ASSERTE(*((BYTE*)pInfo + i) == 0);
#endif // _DEBUG
}
// Define a macro that generates a mask for a given bit in a TADDR correctly on either 32 or 64 bit platforms.
#ifdef HOST_64BIT
#define SELECT_TADDR_BIT(_index) (1ULL << (_index))
#else
#define SELECT_TADDR_BIT(_index) (1U << (_index))
#endif
//==========================================================================================
// For the given interface in the map (specified via map index) mark the interface as declared explicitly on
// this class. This is not legal for dynamically added interfaces (as used by RCWs).
void MethodTable::SetInterfaceDeclaredOnClass(DWORD index)
{
STANDARD_VM_CONTRACT;
_ASSERTE(HasExtraInterfaceInfo());
_ASSERTE(index < GetNumInterfaces());
// Get address of optional slot for extra info.
PTR_TADDR pInfoSlot = GetExtraInterfaceInfoPtr();
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshold)
{
// Bitmap of flags is stored inline in the optional slot.
*pInfoSlot |= SELECT_TADDR_BIT(index);
}
else
{
// Slot points to a buffer containing a larger bitmap.
TADDR *pBitmap = (PTR_TADDR)*pInfoSlot;
DWORD idxTaddr = index / (sizeof(TADDR) * 8); // Select TADDR in array that covers the target bit
DWORD idxInTaddr = index % (sizeof(TADDR) * 8);
TADDR bitmask = SELECT_TADDR_BIT(idxInTaddr);
pBitmap[idxTaddr] |= bitmask;
_ASSERTE((pBitmap[idxTaddr] & bitmask) == bitmask);
}
}
//==========================================================================================
// For the given interface return true if the interface was declared explicitly on this class.
bool MethodTable::IsInterfaceDeclaredOnClass(DWORD index)
{
STANDARD_VM_CONTRACT;
_ASSERTE(HasExtraInterfaceInfo());
// Dynamic interfaces are always marked as not DeclaredOnClass (I don't know why but this is how the code
// was originally authored).
if (index >= GetNumInterfaces())
{
#ifdef FEATURE_COMINTEROP
_ASSERTE(HasDynamicInterfaceMap());
#endif // FEATURE_COMINTEROP
return false;
}
// Get data from the optional extra info slot.
TADDR taddrInfo = *GetExtraInterfaceInfoPtr();
if (GetNumInterfaces() <= kInlinedInterfaceInfoThreshold)
{
// Bitmap of flags is stored directly in the value.
return (taddrInfo & SELECT_TADDR_BIT(index)) != 0;
}
else
{
// Slot points to a buffer containing a larger bitmap.
TADDR *pBitmap = (PTR_TADDR)taddrInfo;
DWORD idxTaddr = index / (sizeof(TADDR) * 8); // Select TADDR in array that covers the target bit
DWORD idxInTaddr = index % (sizeof(TADDR) * 8);
TADDR bitmask = SELECT_TADDR_BIT(idxInTaddr);
return (pBitmap[idxTaddr] & bitmask) != 0;
}
}
#ifdef FEATURE_COMINTEROP
//==========================================================================================
PTR_InterfaceInfo MethodTable::GetDynamicallyAddedInterfaceMap()
{
LIMITED_METHOD_DAC_CONTRACT;
PRECONDITION(HasDynamicInterfaceMap());
return GetInterfaceMap() + GetNumInterfaces();
}
//==========================================================================================
unsigned MethodTable::GetNumDynamicallyAddedInterfaces()
{
LIMITED_METHOD_DAC_CONTRACT;
PRECONDITION(HasDynamicInterfaceMap());
PTR_InterfaceInfo pInterfaces = GetInterfaceMap();
PREFIX_ASSUME(pInterfaces != NULL);
return (unsigned)*(dac_cast<PTR_SIZE_T>(pInterfaces) - 1);
}
//==========================================================================================
BOOL MethodTable::FindDynamicallyAddedInterface(MethodTable *pInterface)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(HasDynamicInterfaceMap()); // This should never be called on for a type that is not an extensible RCW.
unsigned cDynInterfaces = GetNumDynamicallyAddedInterfaces();
InterfaceInfo_t *pDynItfMap = GetDynamicallyAddedInterfaceMap();
for (unsigned i = 0; i < cDynInterfaces; i++)
{
if (pDynItfMap[i].GetMethodTable() == pInterface)
return TRUE;
}
return FALSE;
}
//==========================================================================================
void MethodTable::AddDynamicInterface(MethodTable *pItfMT)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(HasDynamicInterfaceMap()); // This should never be called on for a type that is not an extensible RCW.
}
CONTRACTL_END;
unsigned NumDynAddedInterfaces = GetNumDynamicallyAddedInterfaces();
unsigned TotalNumInterfaces = GetNumInterfaces() + NumDynAddedInterfaces;
InterfaceInfo_t *pNewItfMap = NULL;
S_SIZE_T AllocSize = (S_SIZE_T(S_UINT32(TotalNumInterfaces) + S_UINT32(1)) * S_SIZE_T(sizeof(InterfaceInfo_t))) + S_SIZE_T(sizeof(DWORD_PTR));
if (AllocSize.IsOverflow())
ThrowHR(COR_E_OVERFLOW);