This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathcomdelegate.cpp
3646 lines (2985 loc) · 135 KB
/
comdelegate.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: COMDelegate.cpp
//
// This module contains the implementation of the native methods for the
// Delegate class.
//
#include "common.h"
#include "comdelegate.h"
#include "invokeutil.h"
#include "excep.h"
#include "class.h"
#include "field.h"
#include "dllimportcallback.h"
#include "dllimport.h"
#include "eeconfig.h"
#include "mdaassistants.h"
#include "cgensys.h"
#include "asmconstants.h"
#include "virtualcallstub.h"
#include "callingconvention.h"
#include "customattribute.h"
#include "typestring.h"
#include "../md/compiler/custattr.h"
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#endif // FEATURE_COMINTEROP
#define DELEGATE_MARKER_UNMANAGEDFPTR -1
#ifndef DACCESS_COMPILE
#if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI)
// ShuffleOfs not needed
#elif defined(_TARGET_X86_)
// Return an encoded shuffle entry describing a general register or stack offset that needs to be shuffled.
static UINT16 ShuffleOfs(INT ofs, UINT stackSizeDelta = 0)
{
STANDARD_VM_CONTRACT;
if (TransitionBlock::IsStackArgumentOffset(ofs))
{
ofs = (ofs - TransitionBlock::GetOffsetOfReturnAddress()) + stackSizeDelta;
if (ofs >= ShuffleEntry::REGMASK)
{
// method takes too many stack args
COMPlusThrow(kNotSupportedException);
}
}
else
{
ofs -= TransitionBlock::GetOffsetOfArgumentRegisters();
ofs |= ShuffleEntry::REGMASK;
}
return static_cast<UINT16>(ofs);
}
#else // Portable default implementation
// Iterator for extracting shuffle entries for argument desribed by an ArgLocDesc.
// Used when calculating shuffle array entries in GenerateShuffleArray below.
class ShuffleIterator
{
// Argument location description
ArgLocDesc* m_argLocDesc;
#if defined(UNIX_AMD64_ABI)
// Current eightByte used for struct arguments in registers
int m_currentEightByte;
#endif
// Current general purpose register index (relative to the ArgLocDesc::m_idxGenReg)
int m_currentGenRegIndex;
// Current floating point register index (relative to the ArgLocDesc::m_idxFloatReg)
int m_currentFloatRegIndex;
// Current stack slot index (relative to the ArgLocDesc::m_idxStack)
int m_currentStackSlotIndex;
#if defined(UNIX_AMD64_ABI)
// Get next shuffle offset for struct passed in registers. There has to be at least one offset left.
UINT16 GetNextOfsInStruct()
{
EEClass* eeClass = m_argLocDesc->m_eeClass;
_ASSERTE(eeClass != NULL);
if (m_currentEightByte < eeClass->GetNumberEightBytes())
{
SystemVClassificationType eightByte = eeClass->GetEightByteClassification(m_currentEightByte);
unsigned int eightByteSize = eeClass->GetEightByteSize(m_currentEightByte);
m_currentEightByte++;
int index;
UINT16 mask = ShuffleEntry::REGMASK;
if (eightByte == SystemVClassificationTypeSSE)
{
_ASSERTE(m_currentFloatRegIndex < m_argLocDesc->m_cFloatReg);
index = m_argLocDesc->m_idxFloatReg + m_currentFloatRegIndex;
m_currentFloatRegIndex++;
mask |= ShuffleEntry::FPREGMASK;
if (eightByteSize == 4)
{
mask |= ShuffleEntry::FPSINGLEMASK;
}
}
else
{
_ASSERTE(m_currentGenRegIndex < m_argLocDesc->m_cGenReg);
index = m_argLocDesc->m_idxGenReg + m_currentGenRegIndex;
m_currentGenRegIndex++;
}
return (UINT16)index | mask;
}
// There are no more offsets to get, the caller should not have called us
_ASSERTE(false);
return 0;
}
#endif // UNIX_AMD64_ABI
public:
// Construct the iterator for the ArgLocDesc
ShuffleIterator(ArgLocDesc* argLocDesc)
:
m_argLocDesc(argLocDesc),
#if defined(UNIX_AMD64_ABI)
m_currentEightByte(0),
#endif
m_currentGenRegIndex(0),
m_currentFloatRegIndex(0),
m_currentStackSlotIndex(0)
{
}
// Check if there are more offsets to shuffle
bool HasNextOfs()
{
return (m_currentGenRegIndex < m_argLocDesc->m_cGenReg) ||
#if defined(UNIX_AMD64_ABI)
(m_currentFloatRegIndex < m_argLocDesc->m_cFloatReg) ||
#endif
(m_currentStackSlotIndex < m_argLocDesc->m_cStack);
}
// Get next offset to shuffle. There has to be at least one offset left.
UINT16 GetNextOfs()
{
int index;
#if defined(UNIX_AMD64_ABI)
// Check if the argLocDesc is for a struct in registers
EEClass* eeClass = m_argLocDesc->m_eeClass;
if (m_argLocDesc->m_eeClass != 0)
{
return GetNextOfsInStruct();
}
// Shuffle float registers first
if (m_currentFloatRegIndex < m_argLocDesc->m_cFloatReg)
{
index = m_argLocDesc->m_idxFloatReg + m_currentFloatRegIndex;
m_currentFloatRegIndex++;
return (UINT16)index | ShuffleEntry::REGMASK | ShuffleEntry::FPREGMASK;
}
#endif // UNIX_AMD64_ABI
// Shuffle any registers first (the order matters since otherwise we could end up shuffling a stack slot
// over a register we later need to shuffle down as well).
if (m_currentGenRegIndex < m_argLocDesc->m_cGenReg)
{
index = m_argLocDesc->m_idxGenReg + m_currentGenRegIndex;
m_currentGenRegIndex++;
return (UINT16)index | ShuffleEntry::REGMASK;
}
// If we get here we must have at least one stack slot left to shuffle (this method should only be called
// when AnythingToShuffle(pArg) == true).
if (m_currentStackSlotIndex < m_argLocDesc->m_cStack)
{
index = m_argLocDesc->m_idxStack + m_currentStackSlotIndex;
m_currentStackSlotIndex++;
// Delegates cannot handle overly large argument stacks due to shuffle entry encoding limitations.
if (index >= ShuffleEntry::REGMASK)
{
COMPlusThrow(kNotSupportedException);
}
return (UINT16)index;
}
// There are no more offsets to get, the caller should not have called us
_ASSERTE(false);
return 0;
}
};
#endif
#if defined(UNIX_AMD64_ABI)
// Return an index of argument slot. First indices are reserved for general purpose registers,
// the following ones for float registers and then the rest for stack slots.
// This index is independent of how many registers are actually used to pass arguments.
int GetNormalizedArgumentSlotIndex(UINT16 offset)
{
int index;
if (offset & ShuffleEntry::FPREGMASK)
{
index = NUM_ARGUMENT_REGISTERS + (offset & ShuffleEntry::OFSREGMASK);
}
else if (offset & ShuffleEntry::REGMASK)
{
index = offset & ShuffleEntry::OFSREGMASK;
}
else
{
// stack slot
index = NUM_ARGUMENT_REGISTERS + NUM_FLOAT_ARGUMENT_REGISTERS + (offset & ShuffleEntry::OFSMASK);
}
return index;
}
#endif // UNIX_AMD64_ABI
VOID GenerateShuffleArray(MethodDesc* pInvoke, MethodDesc *pTargetMeth, SArray<ShuffleEntry> * pShuffleEntryArray)
{
STANDARD_VM_CONTRACT;
ShuffleEntry entry;
ZeroMemory(&entry, sizeof(entry));
#if defined(_TARGET_AMD64_) && !defined(UNIX_AMD64_ABI)
MetaSig msig(pInvoke);
ArgIterator argit(&msig);
if (argit.HasRetBuffArg())
{
if (!pTargetMeth->IsStatic())
{
// Use ELEMENT_TYPE_END to signal the special handling required by
// instance method with return buffer. "this" needs to come from
// the first argument.
entry.argtype = ELEMENT_TYPE_END;
pShuffleEntryArray->Append(entry);
msig.NextArgNormalized();
}
else
{
entry.argtype = ELEMENT_TYPE_PTR;
pShuffleEntryArray->Append(entry);
}
}
CorElementType sigType;
while ((sigType = msig.NextArgNormalized()) != ELEMENT_TYPE_END)
{
ZeroMemory(&entry, sizeof(entry));
entry.argtype = sigType;
pShuffleEntryArray->Append(entry);
}
ZeroMemory(&entry, sizeof(entry));
entry.srcofs = ShuffleEntry::SENTINEL;
pShuffleEntryArray->Append(entry);
#elif defined(_TARGET_X86_)
// Must create independent msigs to prevent the argiterators from
// interfering with other.
MetaSig sSigSrc(pInvoke);
MetaSig sSigDst(pTargetMeth);
_ASSERTE(sSigSrc.HasThis());
ArgIterator sArgPlacerSrc(&sSigSrc);
ArgIterator sArgPlacerDst(&sSigDst);
UINT stackSizeSrc = sArgPlacerSrc.SizeOfArgStack();
UINT stackSizeDst = sArgPlacerDst.SizeOfArgStack();
if (stackSizeDst > stackSizeSrc)
{
// we can drop arguments but we can never make them up - this is definitely not allowed
COMPlusThrow(kVerificationException);
}
UINT stackSizeDelta;
#ifdef UNIX_X86_ABI
// Stack does not shrink as UNIX_X86_ABI uses CDECL (instead of STDCALL).
stackSizeDelta = 0;
#else
stackSizeDelta = stackSizeSrc - stackSizeDst;
#endif
INT ofsSrc, ofsDst;
// if the function is non static we need to place the 'this' first
if (!pTargetMeth->IsStatic())
{
entry.srcofs = ShuffleOfs(sArgPlacerSrc.GetNextOffset());
entry.dstofs = ShuffleEntry::REGMASK | 4;
pShuffleEntryArray->Append(entry);
}
else if (sArgPlacerSrc.HasRetBuffArg())
{
// the first register is used for 'this'
entry.srcofs = ShuffleOfs(sArgPlacerSrc.GetRetBuffArgOffset());
entry.dstofs = ShuffleOfs(sArgPlacerDst.GetRetBuffArgOffset(), stackSizeDelta);
if (entry.srcofs != entry.dstofs)
pShuffleEntryArray->Append(entry);
}
while (TransitionBlock::InvalidOffset != (ofsSrc = sArgPlacerSrc.GetNextOffset()))
{
ofsDst = sArgPlacerDst.GetNextOffset();
int cbSize = sArgPlacerDst.GetArgSize();
do
{
entry.srcofs = ShuffleOfs(ofsSrc);
entry.dstofs = ShuffleOfs(ofsDst, stackSizeDelta);
ofsSrc += STACK_ELEM_SIZE;
ofsDst += STACK_ELEM_SIZE;
if (entry.srcofs != entry.dstofs)
pShuffleEntryArray->Append(entry);
cbSize -= STACK_ELEM_SIZE;
}
while (cbSize > 0);
}
if (stackSizeDelta != 0)
{
// Emit code to move the return address
entry.srcofs = 0; // retaddress is assumed to be at esp
entry.dstofs = static_cast<UINT16>(stackSizeDelta);
pShuffleEntryArray->Append(entry);
}
entry.srcofs = ShuffleEntry::SENTINEL;
entry.dstofs = static_cast<UINT16>(stackSizeDelta);
pShuffleEntryArray->Append(entry);
#else // Portable default implementation
MetaSig sSigSrc(pInvoke);
MetaSig sSigDst(pTargetMeth);
// Initialize helpers that determine how each argument for the source and destination signatures is placed
// in registers or on the stack.
ArgIterator sArgPlacerSrc(&sSigSrc);
ArgIterator sArgPlacerDst(&sSigDst);
INT ofsSrc;
INT ofsDst;
ArgLocDesc sArgSrc;
ArgLocDesc sArgDst;
#if defined(UNIX_AMD64_ABI)
int argSlots = NUM_FLOAT_ARGUMENT_REGISTERS + NUM_ARGUMENT_REGISTERS + sArgPlacerSrc.SizeOfArgStack() / sizeof(size_t);
#endif // UNIX_AMD64_ABI
// If the target method in non-static (this happens for open instance delegates), we need to account for
// the implicit this parameter.
if (sSigDst.HasThis())
{
// The this pointer is an implicit argument for the destination signature. But on the source side it's
// just another regular argument and needs to be iterated over by sArgPlacerSrc and the MetaSig.
sArgPlacerSrc.GetArgLoc(sArgPlacerSrc.GetNextOffset(), &sArgSrc);
sArgPlacerSrc.GetThisLoc(&sArgDst);
ShuffleIterator iteratorSrc(&sArgSrc);
ShuffleIterator iteratorDst(&sArgDst);
entry.srcofs = iteratorSrc.GetNextOfs();
entry.dstofs = iteratorDst.GetNextOfs();
pShuffleEntryArray->Append(entry);
}
// Handle any return buffer argument.
if (sArgPlacerDst.HasRetBuffArg())
{
// The return buffer argument is implicit in both signatures.
#if !defined(_TARGET_ARM64_) || !defined(CALLDESCR_RETBUFFARGREG)
// The ifdef above disables this code if the ret buff arg is always in the same register, which
// means that we don't need to do any shuffling for it.
sArgPlacerSrc.GetRetBuffArgLoc(&sArgSrc);
sArgPlacerDst.GetRetBuffArgLoc(&sArgDst);
ShuffleIterator iteratorSrc(&sArgSrc);
ShuffleIterator iteratorDst(&sArgDst);
entry.srcofs = iteratorSrc.GetNextOfs();
entry.dstofs = iteratorDst.GetNextOfs();
// Depending on the type of target method (static vs instance) the return buffer argument may end up
// in the same register in both signatures. So we only commit the entry (by moving the entry pointer
// along) in the case where it's not a no-op (i.e. the source and destination ops are different).
if (entry.srcofs != entry.dstofs)
pShuffleEntryArray->Append(entry);
#endif // !defined(_TARGET_ARM64_) || !defined(CALLDESCR_RETBUFFARGREG)
}
// Iterate all the regular arguments. mapping source registers and stack locations to the corresponding
// destination locations.
while ((ofsSrc = sArgPlacerSrc.GetNextOffset()) != TransitionBlock::InvalidOffset)
{
ofsDst = sArgPlacerDst.GetNextOffset();
// Find the argument location mapping for both source and destination signature. A single argument can
// occupy a floating point register, a general purpose register, a pair of registers of any kind or
// a stack slot.
sArgPlacerSrc.GetArgLoc(ofsSrc, &sArgSrc);
sArgPlacerDst.GetArgLoc(ofsDst, &sArgDst);
ShuffleIterator iteratorSrc(&sArgSrc);
ShuffleIterator iteratorDst(&sArgDst);
// Shuffle each slot in the argument (register or stack slot) from source to destination.
while (iteratorSrc.HasNextOfs())
{
// Locate the next slot to shuffle in the source and destination and encode the transfer into a
// shuffle entry.
entry.srcofs = iteratorSrc.GetNextOfs();
entry.dstofs = iteratorDst.GetNextOfs();
// Only emit this entry if it's not a no-op (i.e. the source and destination locations are
// different).
if (entry.srcofs != entry.dstofs)
pShuffleEntryArray->Append(entry);
}
// We should have run out of slots to shuffle in the destination at the same time as the source.
_ASSERTE(!iteratorDst.HasNextOfs());
}
#if defined(UNIX_AMD64_ABI)
// The Unix AMD64 ABI can cause a struct to be passed on stack for the source and in registers for the destination.
// That can cause some arguments that are passed on stack for the destination to be passed in registers in the source.
// An extreme example of that is e.g.:
// void fn(int, int, int, int, int, struct {int, double}, double, double, double, double, double, double, double, double, double, double)
// For this signature, the shuffle needs to move slots as follows (please note the "forward" movement of xmm registers):
// RDI->RSI, RDX->RCX, R8->RDX, R9->R8, stack[0]->R9, xmm0->xmm1, xmm1->xmm2, ... xmm6->xmm7, xmm7->stack[0], stack[1]->xmm0, stack[2]->stack[1], stack[3]->stack[2]
// To prevent overwriting of slots before they are moved, we need to sort the move operations.
NewArrayHolder<bool> filledSlots = new bool[argSlots];
bool reordered;
do
{
reordered = false;
for (int i = 0; i < argSlots; i++)
{
filledSlots[i] = false;
}
for (unsigned int i = 0; i < pShuffleEntryArray->GetCount(); i++)
{
entry = (*pShuffleEntryArray)[i];
// If the slot that we are moving the argument to was filled in already, we need to move this entry in front
// of the entry that filled it in.
if (filledSlots[GetNormalizedArgumentSlotIndex(entry.srcofs)])
{
unsigned int j;
for (j = i; (*pShuffleEntryArray)[j].dstofs != entry.srcofs; j--)
(*pShuffleEntryArray)[j] = (*pShuffleEntryArray)[j - 1];
(*pShuffleEntryArray)[j] = entry;
reordered = true;
}
filledSlots[GetNormalizedArgumentSlotIndex(entry.dstofs)] = true;
}
}
while (reordered);
#endif // UNIX_AMD64_ABI
entry.srcofs = ShuffleEntry::SENTINEL;
entry.dstofs = 0;
pShuffleEntryArray->Append(entry);
#endif
}
ShuffleThunkCache *COMDelegate::m_pShuffleThunkCache = NULL;
MulticastStubCache *COMDelegate::m_pSecureDelegateStubCache = NULL;
MulticastStubCache *COMDelegate::m_pMulticastStubCache = NULL;
CrstStatic COMDelegate::s_DelegateToFPtrHashCrst;
PtrHashMap* COMDelegate::s_pDelegateToFPtrHash = NULL;
// One time init.
void COMDelegate::Init()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
s_DelegateToFPtrHashCrst.Init(CrstDelegateToFPtrHash, CRST_UNSAFE_ANYMODE);
s_pDelegateToFPtrHash = ::new PtrHashMap();
LockOwner lock = {&COMDelegate::s_DelegateToFPtrHashCrst, IsOwnerOfCrst};
s_pDelegateToFPtrHash->Init(TRUE, &lock);
m_pShuffleThunkCache = new ShuffleThunkCache(SystemDomain::GetGlobalLoaderAllocator()->GetStubHeap());
m_pMulticastStubCache = new MulticastStubCache();
m_pSecureDelegateStubCache = new MulticastStubCache();
}
#ifdef FEATURE_COMINTEROP
ComPlusCallInfo * COMDelegate::PopulateComPlusCallInfo(MethodTable * pDelMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
DelegateEEClass * pClass = (DelegateEEClass *)pDelMT->GetClass();
// set up the ComPlusCallInfo if it does not exist already
if (pClass->m_pComPlusCallInfo == NULL)
{
LoaderHeap *pHeap = pDelMT->GetLoaderAllocator()->GetHighFrequencyHeap();
ComPlusCallInfo *pTemp = (ComPlusCallInfo *)(void *)pHeap->AllocMem(S_SIZE_T(sizeof(ComPlusCallInfo)));
pTemp->m_cachedComSlot = ComMethodTable::GetNumExtraSlots(ifVtable);
pTemp->InitStackArgumentSize();
InterlockedCompareExchangeT(EnsureWritablePages(&pClass->m_pComPlusCallInfo), pTemp, NULL);
}
*EnsureWritablePages(&pClass->m_pComPlusCallInfo->m_pInterfaceMT) = pDelMT;
return pClass->m_pComPlusCallInfo;
}
#endif // FEATURE_COMINTEROP
// We need a LoaderHeap that lives at least as long as the DelegateEEClass, but ideally no longer
LoaderHeap *DelegateEEClass::GetStubHeap()
{
return GetInvokeMethod()->GetLoaderAllocator()->GetStubHeap();
}
Stub* COMDelegate::SetupShuffleThunk(MethodTable * pDelMT, MethodDesc *pTargetMeth)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
GCX_PREEMP();
DelegateEEClass * pClass = (DelegateEEClass *)pDelMT->GetClass();
MethodDesc *pMD = pClass->GetInvokeMethod();
StackSArray<ShuffleEntry> rShuffleEntryArray;
GenerateShuffleArray(pMD, pTargetMeth, &rShuffleEntryArray);
ShuffleThunkCache* pShuffleThunkCache = m_pShuffleThunkCache;
LoaderAllocator* pLoaderAllocator = pDelMT->GetLoaderAllocator();
if (pLoaderAllocator->IsCollectible())
{
pShuffleThunkCache = ((AssemblyLoaderAllocator*)pLoaderAllocator)->GetShuffleThunkCache();
}
Stub* pShuffleThunk = pShuffleThunkCache->Canonicalize((const BYTE *)&rShuffleEntryArray[0]);
if (!pShuffleThunk)
{
COMPlusThrowOM();
}
g_IBCLogger.LogEEClassCOWTableAccess(pDelMT);
EnsureWritablePages(pClass);
if (!pTargetMeth->IsStatic() && pTargetMeth->HasRetBuffArg() && IsRetBuffPassedAsFirstArg())
{
if (FastInterlockCompareExchangePointer(&pClass->m_pInstRetBuffCallStub, pShuffleThunk, NULL ) != NULL)
{
pShuffleThunk->DecRef();
pShuffleThunk = pClass->m_pInstRetBuffCallStub;
}
}
else
{
if (FastInterlockCompareExchangePointer(&pClass->m_pStaticCallStub, pShuffleThunk, NULL ) != NULL)
{
pShuffleThunk->DecRef();
pShuffleThunk = pClass->m_pStaticCallStub;
}
}
return pShuffleThunk;
}
#ifndef CROSSGEN_COMPILE
static PCODE GetVirtualCallStub(MethodDesc *method, TypeHandle scopeType)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM()); // from MetaSig::SizeOfArgStack
}
CONTRACTL_END;
//TODO: depending on what we decide for generics method we may want to move this check to better places
if (method->IsGenericMethodDefinition() || method->HasMethodInstantiation())
{
COMPlusThrow(kNotSupportedException);
}
// need to grab a virtual dispatch stub
// method can be on a canonical MethodTable, we need to allocate the stub on the loader allocator associated with the exact type instantiation.
VirtualCallStubManager *pVirtualStubManager = scopeType.GetMethodTable()->GetLoaderAllocator()->GetVirtualCallStubManager();
PCODE pTargetCall = pVirtualStubManager->GetCallStub(scopeType, method);
_ASSERTE(pTargetCall);
return pTargetCall;
}
FCIMPL5(FC_BOOL_RET, COMDelegate::BindToMethodName,
Object *refThisUNSAFE,
Object *targetUNSAFE,
ReflectClassBaseObject *pMethodTypeUNSAFE,
StringObject* methodNameUNSAFE,
int flags)
{
FCALL_CONTRACT;
struct _gc
{
DELEGATEREF refThis;
OBJECTREF target;
STRINGREF methodName;
REFLECTCLASSBASEREF refMethodType;
} gc;
gc.refThis = (DELEGATEREF) ObjectToOBJECTREF(refThisUNSAFE);
gc.target = (OBJECTREF) targetUNSAFE;
gc.methodName = (STRINGREF) methodNameUNSAFE;
gc.refMethodType = (REFLECTCLASSBASEREF) ObjectToOBJECTREF(pMethodTypeUNSAFE);
TypeHandle methodType = gc.refMethodType->GetType();
MethodDesc *pMatchingMethod = NULL;
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
// Caching of MethodDescs (impl and decl) for MethodTable slots provided significant
// performance gain in some reflection emit scenarios.
MethodTable::AllowMethodDataCaching();
TypeHandle targetType((gc.target != NULL) ? gc.target->GetMethodTable() : NULL);
// get the invoke of the delegate
MethodTable * pDelegateType = gc.refThis->GetMethodTable();
MethodDesc* pInvokeMeth = COMDelegate::FindDelegateInvokeMethod(pDelegateType);
_ASSERTE(pInvokeMeth);
//
// now loop through the methods looking for a match
//
// get the name in UTF8 format
SString wszName(SString::Literal, gc.methodName->GetBuffer());
StackScratchBuffer utf8Name;
LPCUTF8 szNameStr = wszName.GetUTF8(utf8Name);
// pick a proper compare function
typedef int (__cdecl *UTF8StringCompareFuncPtr)(const char *, const char *);
UTF8StringCompareFuncPtr StrCompFunc = (flags & DBF_CaselessMatching) ? stricmpUTF8 : strcmp;
// search the type hierarchy
MethodTable *pMTOrig = methodType.GetMethodTable()->GetCanonicalMethodTable();
for (MethodTable *pMT = pMTOrig; pMT != NULL; pMT = pMT->GetParentMethodTable())
{
MethodTable::MethodIterator it(pMT);
it.MoveToEnd();
for (; it.IsValid() && (pMT == pMTOrig || !it.IsVirtual()); it.Prev())
{
MethodDesc *pCurMethod = it.GetDeclMethodDesc();
// We can't match generic methods (since no instantiation information has been provided).
if (pCurMethod->IsGenericMethodDefinition())
continue;
if ((pCurMethod != NULL) && (StrCompFunc(szNameStr, pCurMethod->GetName()) == 0))
{
// found a matching string, get an associated method desc if needed
// Use unboxing stubs for instance and virtual methods on value types.
// If this is a open delegate to an instance method BindToMethod will rebind it to the non-unboxing method.
// Open delegate
// Static: never use unboxing stub
// BindToMethodInfo/Name will bind to the non-unboxing stub. BindToMethod will reinforce that.
// Instance: We only support binding to an unboxed value type reference here, so we must never use an unboxing stub
// BindToMethodInfo/Name will bind to the unboxing stub. BindToMethod will rebind to the non-unboxing stub.
// Virtual: trivial (not allowed)
// Closed delegate
// Static: never use unboxing stub
// BindToMethodInfo/Name will bind to the non-unboxing stub.
// Instance: always use unboxing stub
// BindToMethodInfo/Name will bind to the unboxing stub.
// Virtual: always use unboxing stub
// BindToMethodInfo/Name will bind to the unboxing stub.
pCurMethod =
MethodDesc::FindOrCreateAssociatedMethodDesc(pCurMethod,
methodType.GetMethodTable(),
(!pCurMethod->IsStatic() && pCurMethod->GetMethodTable()->IsValueType()),
pCurMethod->GetMethodInstantiation(),
false /* do not allow code with a shared-code calling convention to be returned */,
true /* Ensure that methods on generic interfaces are returned as instantiated method descs */);
BOOL fIsOpenDelegate;
if (!COMDelegate::IsMethodDescCompatible((gc.target == NULL) ? TypeHandle() : gc.target->GetTrueTypeHandle(),
methodType,
pCurMethod,
gc.refThis->GetTypeHandle(),
pInvokeMeth,
flags,
&fIsOpenDelegate))
{
// Signature doesn't match, skip.
continue;
}
// Found the target that matches the signature and satisfies security transparency rules
// Initialize the delegate to point to the target method.
BindToMethod(&gc.refThis,
&gc.target,
pCurMethod,
methodType.GetMethodTable(),
fIsOpenDelegate,
TRUE);
pMatchingMethod = pCurMethod;
goto done;
}
}
}
done:
;
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(pMatchingMethod != NULL);
}
FCIMPLEND
FCIMPL5(FC_BOOL_RET, COMDelegate::BindToMethodInfo, Object* refThisUNSAFE, Object* targetUNSAFE, ReflectMethodObject *pMethodUNSAFE, ReflectClassBaseObject *pMethodTypeUNSAFE, int flags)
{
FCALL_CONTRACT;
BOOL result = TRUE;
struct _gc
{
DELEGATEREF refThis;
OBJECTREF refFirstArg;
REFLECTCLASSBASEREF refMethodType;
REFLECTMETHODREF refMethod;
} gc;
gc.refThis = (DELEGATEREF) ObjectToOBJECTREF(refThisUNSAFE);
gc.refFirstArg = ObjectToOBJECTREF(targetUNSAFE);
gc.refMethodType = (REFLECTCLASSBASEREF) ObjectToOBJECTREF(pMethodTypeUNSAFE);
gc.refMethod = (REFLECTMETHODREF) ObjectToOBJECTREF(pMethodUNSAFE);
MethodTable *pMethMT = gc.refMethodType->GetType().GetMethodTable();
MethodDesc *method = gc.refMethod->GetMethod();
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
// Assert to track down VS#458689.
_ASSERTE(gc.refThis != gc.refFirstArg);
// A generic method had better be instantiated (we can't dispatch to an uninstantiated one).
if (method->IsGenericMethodDefinition())
COMPlusThrow(kArgumentException, W("Arg_DlgtTargMeth"));
// get the invoke of the delegate
MethodTable * pDelegateType = gc.refThis->GetMethodTable();
MethodDesc* pInvokeMeth = COMDelegate::FindDelegateInvokeMethod(pDelegateType);
_ASSERTE(pInvokeMeth);
// See the comment in BindToMethodName
method =
MethodDesc::FindOrCreateAssociatedMethodDesc(method,
pMethMT,
(!method->IsStatic() && pMethMT->IsValueType()),
method->GetMethodInstantiation(),
false /* do not allow code with a shared-code calling convention to be returned */,
true /* Ensure that methods on generic interfaces are returned as instantiated method descs */);
BOOL fIsOpenDelegate;
if (COMDelegate::IsMethodDescCompatible((gc.refFirstArg == NULL) ? TypeHandle() : gc.refFirstArg->GetTrueTypeHandle(),
TypeHandle(pMethMT),
method,
gc.refThis->GetTypeHandle(),
pInvokeMeth,
flags,
&fIsOpenDelegate))
{
// Initialize the delegate to point to the target method.
BindToMethod(&gc.refThis,
&gc.refFirstArg,
method,
pMethMT,
fIsOpenDelegate,
!(flags & DBF_SkipSecurityChecks));
}
else
result = FALSE;
HELPER_METHOD_FRAME_END();
FC_RETURN_BOOL(result);
}
FCIMPLEND
// This method is called (in the late bound case only) once a target method has been decided on. All the consistency checks
// (signature matching etc.) have been done at this point and the only major reason we could fail now is on security grounds
// (someone trying to create a delegate over a method that's not visible to them for instance). This method will initialize the
// delegate (wrapping it in a secure delegate if necessary). Upon return the delegate should be ready for invocation.
void COMDelegate::BindToMethod(DELEGATEREF *pRefThis,
OBJECTREF *pRefFirstArg,
MethodDesc *pTargetMethod,
MethodTable *pExactMethodType,
BOOL fIsOpenDelegate,
BOOL fCheckSecurity)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pRefThis));
PRECONDITION(CheckPointer(pRefFirstArg, NULL_OK));
PRECONDITION(CheckPointer(pTargetMethod));
PRECONDITION(CheckPointer(pExactMethodType));
}
CONTRACTL_END;
// We might have to wrap the delegate in a secure delegate depending on the location of the target method. The following local
// keeps track of the real (i.e. non-secure) delegate whether or not this is required.
DELEGATEREF refRealDelegate = NULL;
GCPROTECT_BEGIN(refRealDelegate);
// Security checks (i.e. whether the creator of the delegate is allowed to access the target method) are the norm. They are only
// disabled when:
// 1. this is called by deserialization to recreate an existing delegate instance, where such checks are unwarranted.
// 2. this is called from DynamicMethod.CreateDelegate which doesn't need access check.
if (fCheckSecurity)
{
MethodTable *pInstanceMT = pExactMethodType;
bool targetPossiblyRemoted = false;
if (fIsOpenDelegate)
{
_ASSERTE(pRefFirstArg == NULL || *pRefFirstArg == NULL);
}
else
{
// closed-static is OK and we can check the target in the closed-instance case
pInstanceMT = (*pRefFirstArg == NULL ? NULL : (*pRefFirstArg)->GetMethodTable());
}
RefSecContext sCtx(InvokeUtil::GetInvocationAccessCheckType(targetPossiblyRemoted));
// Check visibility of the target method. If it's an instance method, we have to pass the type
// of the instance being accessed which we get from the first argument or from the method itself.
// The type of the instance is necessary for visibility checks of protected methods.
InvokeUtil::CheckAccessMethod(&sCtx,
pExactMethodType,
pTargetMethod->IsStatic() ? NULL : pInstanceMT,
pTargetMethod);
}
// If we didn't wrap the real delegate in a secure delegate then the real delegate is the one passed in.
if (refRealDelegate == NULL)
{
if (NeedsWrapperDelegate(pTargetMethod))
refRealDelegate = CreateSecureDelegate(*pRefThis, NULL, pTargetMethod);
else
refRealDelegate = *pRefThis;
}
pTargetMethod->EnsureActive();
if (fIsOpenDelegate)
{
_ASSERTE(pRefFirstArg == NULL || *pRefFirstArg == NULL);
// Open delegates use themselves as the target (which handily allows their shuffle thunks to locate additional data at
// invocation time).
refRealDelegate->SetTarget(refRealDelegate);
// We need to shuffle arguments for open delegates since the first argument on the calling side is not meaningful to the
// callee.
MethodTable * pDelegateMT = (*pRefThis)->GetMethodTable();
DelegateEEClass *pDelegateClass = (DelegateEEClass*)pDelegateMT->GetClass();
Stub *pShuffleThunk = NULL;
// Look for a thunk cached on the delegate class first. Note we need a different thunk for instance methods with a
// hidden return buffer argument because the extra argument switches place with the target when coming from the caller.
if (!pTargetMethod->IsStatic() && pTargetMethod->HasRetBuffArg() && IsRetBuffPassedAsFirstArg())
pShuffleThunk = pDelegateClass->m_pInstRetBuffCallStub;
else
pShuffleThunk = pDelegateClass->m_pStaticCallStub;
// If we haven't already setup a shuffle thunk go do it now (which will cache the result automatically).
if (!pShuffleThunk)
pShuffleThunk = SetupShuffleThunk(pDelegateMT, pTargetMethod);
// Indicate that the delegate will jump to the shuffle thunk rather than directly to the target method.
refRealDelegate->SetMethodPtr(pShuffleThunk->GetEntryPoint());
// Use stub dispatch for all virtuals.
// <TODO> Investigate not using this for non-interface virtuals. </TODO>
// The virtual dispatch stub doesn't work on unboxed value type objects which don't have MT pointers.
// Since open instance delegates on value type methods require unboxed objects we cannot use the
// virtual dispatch stub for them. On the other hand, virtual methods on value types don't need
// to be dispatched because value types cannot be derived. So we treat them like non-virtual methods.
if (pTargetMethod->IsVirtual() && !pTargetMethod->GetMethodTable()->IsValueType())
{
// Since this is an open delegate over a virtual method we cannot virtualize the call target now. So the shuffle thunk
// needs to jump to another stub (this time provided by the VirtualStubManager) that will virtualize the call at
// runtime.
PCODE pTargetCall = GetVirtualCallStub(pTargetMethod, TypeHandle(pExactMethodType));
refRealDelegate->SetMethodPtrAux(pTargetCall);
refRealDelegate->SetInvocationCount((INT_PTR)(void *)pTargetMethod);
}
else
{
// <TODO> If VSD isn't compiled in this gives the wrong result for virtuals (we need run time virtualization). </TODO>
// Reflection or the code in BindToMethodName will pass us the unboxing stub for non-static methods on value types. But
// for open invocation on value type methods the actual reference will be passed so we need the unboxed method desc
// instead.
if (pTargetMethod->IsUnboxingStub())
{
// We want a MethodDesc which is not an unboxing stub, but is an instantiating stub if needed.
pTargetMethod = MethodDesc::FindOrCreateAssociatedMethodDesc(
pTargetMethod,
pExactMethodType,
FALSE /* don't want unboxing entry point */,
pTargetMethod->GetMethodInstantiation(),
FALSE /* don't want MD that requires inst. arguments */,
true /* Ensure that methods on generic interfaces are returned as instantiated method descs */);
}
// The method must not require any extra hidden instantiation arguments.
_ASSERTE(!pTargetMethod->RequiresInstArg());
// Note that it is important to cache pTargetCode in local variable to avoid GC hole.
// GetMultiCallableAddrOfCode() can trigger GC.
PCODE pTargetCode = pTargetMethod->GetMultiCallableAddrOfCode();