-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
comdelegate.cpp
3138 lines (2578 loc) · 117 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.
//
// 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 "cgensys.h"
#include "asmconstants.h"
#include "virtualcallstub.h"
#include "typestring.h"
#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#endif // FEATURE_COMINTEROP
#define DELEGATE_MARKER_UNMANAGEDFPTR -1
#ifndef DACCESS_COMPILE
#if 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);
}
#endif
#ifdef FEATURE_PORTABLE_SHUFFLE_THUNKS
// 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 byte stack index (relative to the ArgLocDesc::m_byteStackIndex)
int m_currentByteStackIndex;
#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_currentByteStackIndex(0)
{
}
// Check if there are more offsets to shuffle
bool HasNextOfs()
{
return (m_currentGenRegIndex < m_argLocDesc->m_cGenReg) ||
(m_currentFloatRegIndex < m_argLocDesc->m_cFloatReg) ||
(m_currentByteStackIndex < m_argLocDesc->m_byteStackSize);
}
// Get next offset to shuffle. There has to be at least one offset left.
// It returns an offset encoded properly for a ShuffleEntry offset.
// - For floating register arguments it returns regNum | ShuffleEntry::REGMASK | ShuffleEntry::FPREGMASK.
// - For register arguments it returns regNum | ShuffleEntry::REGMASK.
// - For stack arguments it returns stack offset index in stack slots for most architectures. For macOS-arm64,
// it returns an encoded stack offset, see below.
int 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)
{
index = GetNextOfsInStruct();
_ASSERT((index & ShuffleEntry::REGMASK) != 0);
return index;
}
#endif // UNIX_AMD64_ABI
// Shuffle float registers first
if (m_currentFloatRegIndex < m_argLocDesc->m_cFloatReg)
{
#if defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
if ((m_argLocDesc->m_structFields.flags & FpStruct::IntFloat) && (m_currentGenRegIndex < m_argLocDesc->m_cGenReg))
{
// the first field is integer so just skip this.
}
else
#endif
{
index = m_argLocDesc->m_idxFloatReg + m_currentFloatRegIndex;
m_currentFloatRegIndex++;
return index | ShuffleEntry::REGMASK | ShuffleEntry::FPREGMASK;
}
}
// 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)
{
#if defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
if (7 < (m_currentGenRegIndex + m_argLocDesc->m_idxGenReg))
{
m_currentGenRegIndex++;
index = m_currentByteStackIndex;
m_currentByteStackIndex += TARGET_POINTER_SIZE;
return index;
}
#endif
index = m_argLocDesc->m_idxGenReg + m_currentGenRegIndex;
m_currentGenRegIndex++;
return 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_currentByteStackIndex < m_argLocDesc->m_byteStackSize)
{
const unsigned byteIndex = m_argLocDesc->m_byteStackIndex + m_currentByteStackIndex;
#if !defined(TARGET_OSX) || !defined(TARGET_ARM64)
index = byteIndex / TARGET_POINTER_SIZE;
m_currentByteStackIndex += TARGET_POINTER_SIZE;
// Delegates cannot handle overly large argument stacks due to shuffle entry encoding limitations.
if (index >= ShuffleEntry::REGMASK)
{
COMPlusThrow(kNotSupportedException);
}
// Only Apple Silicon ABI currently supports unaligned stack argument shuffling
_ASSERTE(byteIndex == unsigned(index * TARGET_POINTER_SIZE));
return index;
#else
// Tha Apple Silicon ABI does not consume an entire stack slot for every argument
// Arguments smaller than TARGET_POINTER_SIZE are always aligned to their argument size
// But may not begin at the beginning of a stack slot
//
// The argument location description has been updated to describe the stack offest and
// size in bytes. We will use it as our source of truth.
//
// The ShuffleEntries will be implemented by the Arm64 StubLinkerCPU::EmitLoadStoreRegImm
// using the 12-bit scaled immediate stack offset. The load/stores can be implemented as 1/2/4/8
// bytes each (natural binary sizes).
//
// Each offset is encode as a log2 size and a 12-bit unsigned scaled offset.
// We only emit offsets of these natural binary sizes
//
// We choose the offset based on the ABI stack alignment requirements
// - Small integers are shuffled based on their size
// - HFA are shuffled based on their element size
// - Others are shuffled in full 8 byte chunks.
int bytesRemaining = m_argLocDesc->m_byteStackSize - m_currentByteStackIndex;
int log2Size = 3;
// If isHFA, shuffle based on field size
// otherwise shuffle based on stack size
switch(m_argLocDesc->m_hfaFieldSize ? m_argLocDesc->m_hfaFieldSize : m_argLocDesc->m_byteStackSize)
{
case 1:
log2Size = 0;
break;
case 2:
log2Size = 1;
break;
case 4:
log2Size = 2;
break;
case 3: // Unsupported Size
case 5: // Unsupported Size
case 6: // Unsupported Size
case 7: // Unsupported Size
_ASSERTE(false);
break;
default: // Should be a multiple of 8 (TARGET_POINTER_SIZE)
_ASSERTE(bytesRemaining >= TARGET_POINTER_SIZE);
break;
}
m_currentByteStackIndex += (1 << log2Size);
// Delegates cannot handle overly large argument stacks due to shuffle entry encoding limitations.
// Arm64 current implementation only supports 12 bit unsigned scaled offset
if ((byteIndex >> log2Size) > 0xfff)
{
COMPlusThrow(kNotSupportedException);
}
_ASSERTE((byteIndex & ((1 << log2Size) - 1)) == 0);
return (byteIndex >> log2Size) | (log2Size << 12);
#endif
}
// There are no more offsets to get, the caller should not have called us
_ASSERTE(false);
return 0;
}
};
// 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.
static UINT16 GetNormalizedArgumentSlotIndex(UINT16 offset)
{
UINT16 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
#ifdef NUM_FLOAT_ARGUMENT_REGISTERS
+ NUM_FLOAT_ARGUMENT_REGISTERS
#endif
+ (offset & ShuffleEntry::OFSMASK);
}
return index;
}
// Node of a directed graph where nodes represent registers / stack slots
// and edges represent moves of data.
struct ShuffleGraphNode
{
static const UINT16 NoNode = 0xffff;
// Previous node (represents source of data for the register / stack of the current node)
UINT16 prev;
// Offset of the register / stack slot
UINT16 ofs;
// Set to true for nodes that are source of data for a destination node
UINT8 isSource;
// Nodes that are marked are either already processed or don't participate in the shuffling
UINT8 isMarked;
};
BOOL AddNextShuffleEntryToArray(ArgLocDesc sArgSrc, ArgLocDesc sArgDst, SArray<ShuffleEntry> * pShuffleEntryArray, ShuffleComputationType shuffleType)
{
ShuffleEntry entry;
ZeroMemory(&entry, sizeof(entry));
ShuffleIterator iteratorSrc(&sArgSrc);
ShuffleIterator iteratorDst(&sArgDst);
// Shuffle each slot in the argument (register or stack slot) from source to destination.
while (iteratorSrc.HasNextOfs())
{
// We should have slots to shuffle in the destination at the same time as the source.
_ASSERTE(iteratorDst.HasNextOfs());
// Locate the next slot to shuffle in the source and destination and encode the transfer into a
// shuffle entry.
const int srcOffset = iteratorSrc.GetNextOfs();
const int dstOffset = iteratorDst.GetNextOfs();
// Only emit this entry if it's not a no-op (i.e. the source and destination locations are
// different).
if (srcOffset != dstOffset)
{
entry.srcofs = (UINT16)srcOffset;
entry.dstofs = (UINT16)dstOffset;
if (shuffleType == ShuffleComputationType::InstantiatingStub)
{
// Instantiating Stub shuffles only support general register to register moves. More complex cases are handled by IL stubs
if (!(entry.srcofs & ShuffleEntry::REGMASK) || !(entry.dstofs & ShuffleEntry::REGMASK))
{
return FALSE;
}
if ((entry.srcofs == ShuffleEntry::HELPERREG) || (entry.dstofs == ShuffleEntry::HELPERREG))
{
return FALSE;
}
}
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());
return TRUE;
}
BOOL GenerateShuffleArrayPortable(MethodDesc* pMethodSrc, MethodDesc *pMethodDst, SArray<ShuffleEntry> * pShuffleEntryArray, ShuffleComputationType shuffleType)
{
STANDARD_VM_CONTRACT;
ShuffleEntry entry;
ZeroMemory(&entry, sizeof(entry));
MetaSig sSigSrc(pMethodSrc);
MetaSig sSigDst(pMethodDst);
// 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);
if (shuffleType == ShuffleComputationType::InstantiatingStub)
{
// Instantiating Stub shuffles only support register to register moves. More complex cases are handled by IL stubs
UINT stackSizeSrc = sArgPlacerSrc.SizeOfArgStack();
UINT stackSizeDst = sArgPlacerDst.SizeOfArgStack();
if (stackSizeSrc != stackSizeDst)
return FALSE;
}
UINT stackSizeDelta = 0;
#if defined(TARGET_X86) && !defined(UNIX_X86_ABI)
{
UINT stackSizeSrc = sArgPlacerSrc.SizeOfArgStack();
UINT stackSizeDst = sArgPlacerDst.SizeOfArgStack();
// Windows X86 calling convention requires the stack to shrink when removing
// arguments, as it is callee pop
if (stackSizeDst > stackSizeSrc)
{
// we can drop arguments but we can never make them up - this is definitely not allowed
COMPlusThrow(kVerificationException);
}
stackSizeDelta = stackSizeSrc - stackSizeDst;
}
#endif // Callee pop architectures - defined(TARGET_X86) && !defined(UNIX_X86_ABI)
INT ofsSrc;
INT ofsDst;
ArgLocDesc sArgSrc;
ArgLocDesc sArgDst;
unsigned int argSlots = NUM_ARGUMENT_REGISTERS
#ifdef NUM_FLOAT_ARGUMENT_REGISTERS
+ NUM_FLOAT_ARGUMENT_REGISTERS
#endif
+ sArgPlacerSrc.SizeOfArgStack() / sizeof(size_t);
// 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())
{
if (shuffleType == ShuffleComputationType::DelegateShuffleThunk)
{
// 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);
}
else if (shuffleType == ShuffleComputationType::InstantiatingStub)
{
_ASSERTE(sSigSrc.HasThis()); // Instantiating stubs should have the same HasThis flag
sArgPlacerDst.GetThisLoc(&sArgDst);
sArgPlacerSrc.GetThisLoc(&sArgSrc);
}
else
{
_ASSERTE(FALSE); // Unknown shuffle type being generated
}
if (!AddNextShuffleEntryToArray(sArgSrc, sArgDst, pShuffleEntryArray, shuffleType))
return FALSE;
}
// Handle any return buffer argument.
_ASSERTE(!!sArgPlacerDst.HasRetBuffArg() == !!sArgPlacerSrc.HasRetBuffArg());
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);
if (!AddNextShuffleEntryToArray(sArgSrc, sArgDst, pShuffleEntryArray, shuffleType))
return FALSE;
#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);
if (!AddNextShuffleEntryToArray(sArgSrc, sArgDst, pShuffleEntryArray, shuffleType))
return FALSE;
}
if (shuffleType == ShuffleComputationType::InstantiatingStub
#if defined(UNIX_AMD64_ABI)
|| true
#endif // 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 perform the shuffling in correct order
NewArrayHolder<ShuffleGraphNode> pGraphNodes = new ShuffleGraphNode[argSlots];
// Initialize the graph array
for (unsigned int i = 0; i < argSlots; i++)
{
pGraphNodes[i].prev = ShuffleGraphNode::NoNode;
pGraphNodes[i].isMarked = true;
pGraphNodes[i].isSource = false;
}
// Build the directed graph representing register and stack slot shuffling.
// The links are directed from destination to source.
// During the build also set isSource flag for nodes that are sources of data.
// The ones that don't have the isSource flag set are beginnings of non-cyclic
// segments of the graph.
for (unsigned int i = 0; i < pShuffleEntryArray->GetCount(); i++)
{
ShuffleEntry entry = (*pShuffleEntryArray)[i];
UINT16 srcIndex = GetNormalizedArgumentSlotIndex(entry.srcofs);
UINT16 dstIndex = GetNormalizedArgumentSlotIndex(entry.dstofs);
_ASSERTE((srcIndex >= 0) && (srcIndex < argSlots));
_ASSERTE((dstIndex >= 0) && (dstIndex < argSlots));
// Unmark the node to indicate that it was not processed yet
pGraphNodes[srcIndex].isMarked = false;
// The node contains a register / stack slot that is a source from which we move data to a destination one
pGraphNodes[srcIndex].isSource = true;
pGraphNodes[srcIndex].ofs = entry.srcofs;
// Unmark the node to indicate that it was not processed yet
pGraphNodes[dstIndex].isMarked = false;
// Link to the previous node in the graph (source of data for the current node)
pGraphNodes[dstIndex].prev = srcIndex;
pGraphNodes[dstIndex].ofs = entry.dstofs;
}
// Now that we've built the graph, clear the array, we will regenerate it from the graph ensuring a proper order of shuffling
pShuffleEntryArray->Clear();
// Add all non-cyclic subgraphs to the target shuffle array and mark their nodes as visited
for (unsigned int startIndex = 0; startIndex < argSlots; startIndex++)
{
unsigned int index = startIndex;
if (!pGraphNodes[index].isMarked && !pGraphNodes[index].isSource)
{
// This node is not a source, that means it is an end of shuffle chain
// Generate shuffle array entries for all nodes in the chain in a correct
// order.
UINT16 dstOfs = ShuffleEntry::SENTINEL;
do
{
_ASSERTE(index < argSlots);
pGraphNodes[index].isMarked = true;
if (dstOfs != ShuffleEntry::SENTINEL)
{
entry.srcofs = pGraphNodes[index].ofs;
entry.dstofs = dstOfs;
pShuffleEntryArray->Append(entry);
}
dstOfs = pGraphNodes[index].ofs;
index = pGraphNodes[index].prev;
}
while (index != ShuffleGraphNode::NoNode);
}
}
// Process all cycles in the graph
for (unsigned int startIndex = 0; startIndex < argSlots; startIndex++)
{
unsigned int index = startIndex;
if (!pGraphNodes[index].isMarked)
{
if (shuffleType == ShuffleComputationType::InstantiatingStub)
{
// Use of the helper reg isn't supported for these stubs.
return FALSE;
}
// This node is part of a new cycle as all non-cyclic parts of the graphs were already visited
// Move the first node register / stack slot to a helper reg
UINT16 dstOfs = ShuffleEntry::HELPERREG;
do
{
_ASSERTE(index < argSlots);
pGraphNodes[index].isMarked = true;
entry.srcofs = pGraphNodes[index].ofs;
entry.dstofs = dstOfs;
pShuffleEntryArray->Append(entry);
dstOfs = pGraphNodes[index].ofs;
index = pGraphNodes[index].prev;
}
while (index != startIndex);
// Move helper reg to the last node register / stack slot
entry.srcofs = ShuffleEntry::HELPERREG;
entry.dstofs = dstOfs;
pShuffleEntryArray->Append(entry);
}
}
}
entry.srcofs = ShuffleEntry::SENTINEL;
entry.dstofs = 0;
pShuffleEntryArray->Append(entry);
return TRUE;
}
#endif // FEATURE_PORTABLE_SHUFFLE_THUNKS
VOID GenerateShuffleArray(MethodDesc* pInvoke, MethodDesc *pTargetMeth, SArray<ShuffleEntry> * pShuffleEntryArray)
{
STANDARD_VM_CONTRACT;
#ifdef FEATURE_PORTABLE_SHUFFLE_THUNKS
// Portable default implementation
GenerateShuffleArrayPortable(pInvoke, pTargetMeth, pShuffleEntryArray, ShuffleComputationType::DelegateShuffleThunk);
#elif defined(TARGET_X86)
ShuffleEntry entry;
ZeroMemory(&entry, sizeof(entry));
// 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 += TARGET_POINTER_SIZE;
ofsDst += TARGET_POINTER_SIZE;
if (entry.srcofs != entry.dstofs)
pShuffleEntryArray->Append(entry);
cbSize -= TARGET_POINTER_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.stacksizedelta = static_cast<UINT16>(stackSizeDelta);
pShuffleEntryArray->Append(entry);
#else
#error Unsupported architecture
#endif
}
ShuffleThunkCache *COMDelegate::m_pShuffleThunkCache = 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());
}
#ifdef FEATURE_COMINTEROP
CLRToCOMCallInfo * COMDelegate::PopulateCLRToCOMCallInfo(MethodTable * pDelMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
DelegateEEClass * pClass = (DelegateEEClass *)pDelMT->GetClass();
// set up the CLRToCOMCallInfo if it does not exist already
if (pClass->m_pCLRToCOMCallInfo == NULL)
{
LoaderHeap *pHeap = pDelMT->GetLoaderAllocator()->GetHighFrequencyHeap();
CLRToCOMCallInfo *pTemp = (CLRToCOMCallInfo *)(void *)pHeap->AllocMem(S_SIZE_T(sizeof(CLRToCOMCallInfo)));
pTemp->m_cachedComSlot = ComMethodTable::GetNumExtraSlots(ifVtable);
pTemp->InitStackArgumentSize();
InterlockedCompareExchangeT(&pClass->m_pCLRToCOMCallInfo, pTemp, NULL);
}
pClass->m_pCLRToCOMCallInfo->m_pInterfaceMT = pDelMT;
return pClass->m_pCLRToCOMCallInfo;
}
#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();
}
if (!pTargetMeth->IsStatic() && pTargetMeth->HasRetBuffArg() && IsRetBuffPassedAsFirstArg())
{
if (InterlockedCompareExchangeT(&pClass->m_pInstRetBuffCallStub, pShuffleThunk, NULL ) != NULL)
{
ExecutableWriterHolder<Stub> shuffleThunkWriterHolder(pShuffleThunk, sizeof(Stub));
shuffleThunkWriterHolder.GetRW()->DecRef();
pShuffleThunk = pClass->m_pInstRetBuffCallStub;
}
}
else
{
if (InterlockedCompareExchangeT(&pClass->m_pStaticCallStub, pShuffleThunk, NULL ) != NULL)
{
ExecutableWriterHolder<Stub> shuffleThunkWriterHolder(pShuffleThunk, sizeof(Stub));
shuffleThunkWriterHolder.GetRW()->DecRef();
pShuffleThunk = pClass->m_pStaticCallStub;
}
}
return pShuffleThunk;
}
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;
}
extern "C" BOOL QCALLTYPE Delegate_BindToMethodName(QCall::ObjectHandleOnStack d, QCall::ObjectHandleOnStack target,
QCall::TypeHandle pMethodType, LPCUTF8 pszMethodName, DelegateBindingFlags flags)
{
QCALL_CONTRACT;
MethodDesc *pMatchingMethod = NULL;
BEGIN_QCALL;
GCX_COOP();
struct
{
DELEGATEREF refThis;
OBJECTREF target;
} gc;
gc.refThis = (DELEGATEREF) d.Get();
gc.target = target.Get();
GCPROTECT_BEGIN(gc);
TypeHandle methodType = pMethodType.AsTypeHandle();
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
//
// 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(pszMethodName, 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->GetTypeHandle(),
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.
COMDelegate::BindToMethod(&gc.refThis,
&gc.target,
pCurMethod,
methodType.GetMethodTable(),
fIsOpenDelegate);
pMatchingMethod = pCurMethod;
goto done;
}
}
}
done:
;
GCPROTECT_END();
END_QCALL;
return (pMatchingMethod != NULL);
}
extern "C" BOOL QCALLTYPE Delegate_BindToMethodInfo(QCall::ObjectHandleOnStack d, QCall::ObjectHandleOnStack target,
MethodDesc * method, QCall::TypeHandle pMethodType, DelegateBindingFlags flags)
{
QCALL_CONTRACT;
BOOL result = TRUE;
BEGIN_QCALL;