-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
dllimport.cpp
6279 lines (5257 loc) · 209 KB
/
dllimport.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: DllImport.cpp
//
//
// P/Invoke support.
//
#include "common.h"
#include "vars.hpp"
#include "stublink.h"
#include "threads.h"
#include "excep.h"
#include "dllimport.h"
#include "method.hpp"
#include "siginfo.hpp"
#include "callconvbuilder.hpp"
#include "comdelegate.h"
#include "ceeload.h"
#include "mlinfo.h"
#include "eeconfig.h"
#include "comutilnative.h"
#include "corhost.h"
#include "asmconstants.h"
#include "customattribute.h"
#include "ilstubcache.h"
#include "typeparse.h"
#include "typestring.h"
#include "sigbuilder.h"
#include "sigformat.h"
#include "ecall.h"
#include "fieldmarshaler.h"
#include "pinvokeoverride.h"
#include "nativelibrary.h"
#include "interoplibinterface.h"
#include <formattype.h>
#include "../md/compiler/custattr.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "clrtocomcall.h"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif // FEATURE_PREJIT
#include "eventtrace.h"
namespace
{
void AppendEHClause(int nClauses, COR_ILMETHOD_SECT_EH * pEHSect, ILStubEHClause * pClause, int * pCurIdx)
{
LIMITED_METHOD_CONTRACT;
if (pClause->kind == ILStubEHClause::kNone)
return;
int idx = *pCurIdx;
*pCurIdx = idx + 1;
CorExceptionFlag flags;
switch (pClause->kind)
{
case ILStubEHClause::kFinally: flags = COR_ILEXCEPTION_CLAUSE_FINALLY; break;
case ILStubEHClause::kTypedCatch: flags = COR_ILEXCEPTION_CLAUSE_NONE; break;
default:
UNREACHABLE_MSG("unexpected ILStubEHClause kind");
}
_ASSERTE(idx < nClauses);
pEHSect->Fat.Clauses[idx].Flags = flags;
pEHSect->Fat.Clauses[idx].TryOffset = pClause->dwTryBeginOffset;
pEHSect->Fat.Clauses[idx].TryLength = pClause->cbTryLength;
pEHSect->Fat.Clauses[idx].HandlerOffset = pClause->dwHandlerBeginOffset;
pEHSect->Fat.Clauses[idx].HandlerLength = pClause->cbHandlerLength;
pEHSect->Fat.Clauses[idx].ClassToken = pClause->dwTypeToken;
}
VOID PopulateEHSect(COR_ILMETHOD_SECT_EH * pEHSect, int nClauses, ILStubEHClause * pOne, ILStubEHClause * pTwo)
{
LIMITED_METHOD_CONTRACT;
pEHSect->Fat.Kind = (CorILMethod_Sect_EHTable | CorILMethod_Sect_FatFormat);
pEHSect->Fat.DataSize = COR_ILMETHOD_SECT_EH_FAT::Size(nClauses);
int curIdx = 0;
AppendEHClause(nClauses, pEHSect, pOne, &curIdx);
AppendEHClause(nClauses, pEHSect, pTwo, &curIdx);
}
}
StubSigDesc::StubSigDesc(MethodDesc *pMD)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(pMD != NULL);
}
CONTRACTL_END;
m_pMD = pMD;
m_pMT = nullptr;
m_sig = pMD->GetSignature();
m_pModule = pMD->GetModule(); // Used for token resolution.
m_tkMethodDef = pMD->GetMemberDef();
SigTypeContext::InitTypeContext(pMD, &m_typeContext);
m_pLoaderModule = pMD->GetLoaderModule(); // Used for ILStubCache selection and MethodTable creation.
INDEBUG(InitDebugNames());
}
StubSigDesc::StubSigDesc(MethodDesc* pMD, const Signature& sig, Module* pModule)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(!sig.IsEmpty());
PRECONDITION(pModule != NULL);
}
CONTRACTL_END;
m_pMD = pMD;
m_pMT = nullptr;
m_sig = sig;
m_pModule = pModule;
if (pMD != NULL)
{
m_tkMethodDef = pMD->GetMemberDef();
SigTypeContext::InitTypeContext(pMD, &m_typeContext);
m_pLoaderModule = pMD->GetLoaderModule(); // Used for ILStubCache selection and MethodTable creation.
}
else
{
m_tkMethodDef = mdMethodDefNil;
m_pLoaderModule = m_pModule;
}
INDEBUG(InitDebugNames());
}
StubSigDesc::StubSigDesc(MethodTable* pMT, const Signature& sig, Module* pModule)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(!sig.IsEmpty());
PRECONDITION(pModule != NULL);
}
CONTRACTL_END;
m_pMD = nullptr;
m_pMT = pMT;
m_sig = sig;
m_pModule = pModule;
m_tkMethodDef = mdMethodDefNil;
if (pMT != NULL)
{
SigTypeContext::InitTypeContext(pMT, &m_typeContext);
m_pLoaderModule = pMT->GetLoaderModule(); // Used for ILStubCache selection and MethodTable creation.
}
else
{
m_pLoaderModule = m_pModule;
}
INDEBUG(InitDebugNames());
}
StubSigDesc::StubSigDesc(const Signature& sig, Module* pModule)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(!sig.IsEmpty());
PRECONDITION(pModule != NULL);
}
CONTRACTL_END;
m_pMD = nullptr;
m_pMT = nullptr;
m_sig = sig;
m_pModule = pModule;
m_tkMethodDef = mdMethodDefNil;
m_pLoaderModule = m_pModule;
INDEBUG(InitDebugNames());
}
#ifndef DACCESS_COMPILE
class StubState
{
public:
virtual void SetLastError(BOOL fSetLastError) = 0;
virtual void BeginEmit(DWORD dwStubFlags) = 0;
virtual void MarshalReturn(MarshalInfo* pInfo, int argOffset) = 0;
virtual void MarshalArgument(MarshalInfo* pInfo, int argOffset, UINT nativeStackOffset) = 0;
virtual void MarshalLCID(int argIdx) = 0;
virtual void MarshalField(MarshalInfo* pInfo, UINT32 managedOffset, UINT32 nativeOffset, FieldDesc* pFieldDesc) = 0;
virtual void EmitInvokeTarget(MethodDesc *pStubMD) = 0;
virtual void FinishEmit(MethodDesc* pMD) = 0;
virtual ~StubState()
{
LIMITED_METHOD_CONTRACT;
}
};
class ILStubState : public StubState
{
protected:
ILStubState(
Module* pStubModule,
const Signature &signature,
SigTypeContext* pTypeContext,
DWORD dwStubFlags,
int iLCIDParamIdx,
MethodDesc* pTargetMD)
: m_slIL(dwStubFlags, pStubModule, signature, pTypeContext, pTargetMD, iLCIDParamIdx)
, m_dwStubFlags(dwStubFlags)
{
STANDARD_VM_CONTRACT;
m_fSetLastError = 0;
}
public:
void SetLastError(BOOL fSetLastError)
{
LIMITED_METHOD_CONTRACT;
m_fSetLastError = fSetLastError;
}
// We use three stub linkers to generate IL stubs. The pre linker is the main one. It does all the marshaling and
// then calls the target method. The post return linker is only used to unmarshal the return value after we return
// from the target method. The post linker handles all the unmarshaling for by ref arguments and clean-up. It
// also checks if we should throw an exception etc.
//
// Currently, we have two "emittable" ILCodeLabel's. The first one is at the beginning of the pre linker. This
// label is used to emit code to declare and initialize clean-up flags. Each argument which requires clean-up
// emits one flag. This flag is set only after the marshaling is done, and it is checked before we do any clean-up
// in the finally.
//
// The second "emittable" ILCodeLabel is at the beginning of the post linker. It is used to emit code which is
// not safe to run in the case of an exception. The rest of the post linker is wrapped in a finally, and it contains
// with the necessary clean-up which should be executed in both normal and exception cases.
void BeginEmit(DWORD dwStubFlags)
{
WRAPPER_NO_CONTRACT;
m_slIL.Begin(dwStubFlags);
_ASSERTE(m_dwStubFlags == dwStubFlags);
}
void MarshalReturn(MarshalInfo* pInfo, int argOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
pInfo->GenerateReturnIL(&m_slIL, argOffset,
SF_IsForwardStub(m_dwStubFlags),
SF_IsFieldGetterStub(m_dwStubFlags),
SF_IsHRESULTSwapping(m_dwStubFlags));
}
void MarshalArgument(MarshalInfo* pInfo, int argOffset, UINT nativeStackOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
pInfo->GenerateArgumentIL(&m_slIL, argOffset, nativeStackOffset, SF_IsForwardStub(m_dwStubFlags));
}
void MarshalField(MarshalInfo* pInfo, UINT32 managedOffset, UINT32 nativeOffset, FieldDesc* pFieldDesc)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
pInfo->GenerateFieldIL(&m_slIL, managedOffset, nativeOffset, pFieldDesc);
}
#ifdef FEATURE_COMINTEROP
static void EmitInterfaceClearNative(ILCodeStream* pcsEmit, DWORD dwLocalNum)
{
STANDARD_VM_CONTRACT;
ILCodeLabel *pSkipClearNativeLabel = pcsEmit->NewCodeLabel();
pcsEmit->EmitLDLOC(dwLocalNum);
pcsEmit->EmitBRFALSE(pSkipClearNativeLabel);
pcsEmit->EmitLDLOC(dwLocalNum);
pcsEmit->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0);
pcsEmit->EmitLabel(pSkipClearNativeLabel);
}
#endif // FEATURE_COMINTEROP
void MarshalLCID(int argIdx)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcs = m_slIL.GetDispatchCodeStream();
if (SF_IsReverseStub(m_dwStubFlags))
{
if ((m_slIL.GetStubTargetCallingConv() & IMAGE_CEE_CS_CALLCONV_HASTHIS) == IMAGE_CEE_CS_CALLCONV_HASTHIS)
{
// the arg number will be incremented by LDARG if we are in an instance method
_ASSERTE(argIdx > 0);
argIdx--;
}
// call CultureInfo.get_CurrentCulture()
pcs->EmitCALL(METHOD__CULTURE_INFO__GET_CURRENT_CULTURE, 0, 1);
// save the current culture
LocalDesc locDescCulture(CoreLibBinder::GetClass(CLASS__CULTURE_INFO));
DWORD dwCultureLocalNum = pcs->NewLocal(locDescCulture);
pcs->EmitSTLOC(dwCultureLocalNum);
// set a new one based on the LCID passed from unmanaged
pcs->EmitLDARG(argIdx);
// call CultureInfo..ctor(lcid)
// call CultureInfo.set_CurrentCulture(culture)
pcs->EmitNEWOBJ(METHOD__CULTURE_INFO__INT_CTOR, 1);
pcs->EmitCALL(METHOD__CULTURE_INFO__SET_CURRENT_CULTURE, 1, 0);
// and restore the current one after the call
m_slIL.SetCleanupNeeded();
ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream();
// call CultureInfo.set_CurrentCulture(original_culture)
pcsCleanup->EmitLDLOC(dwCultureLocalNum);
pcsCleanup->EmitCALL(METHOD__CULTURE_INFO__SET_CURRENT_CULTURE, 1, 0);
}
else
{
if (SF_IsCOMStub(m_dwStubFlags))
{
// We used to get LCID from current thread's culture here. The code
// was replaced by the hardcoded LCID_ENGLISH_US as requested by VSTO.
pcs->EmitLDC(0x0409); // LCID_ENGLISH_US
}
else
{
// call CultureInfo.get_CurrentCulture()
pcs->EmitCALL(METHOD__CULTURE_INFO__GET_CURRENT_CULTURE, 0, 1);
//call CultureInfo.get_LCID(this)
pcs->EmitCALL(METHOD__CULTURE_INFO__GET_ID, 1, 1);
}
}
// add the extra arg to the unmanaged signature
LocalDesc locDescNative(ELEMENT_TYPE_I4);
pcs->SetStubTargetArgType(&locDescNative, false);
}
void SwapStubSignatures(MethodDesc* pStubMD)
{
STANDARD_VM_CONTRACT;
//
// Since the stub handles native-to-managed transitions, we have to swap the
// stub-state-calculated stub target sig with the stub sig itself. This is
// because the stub target sig represents the native signature and the stub
// sig represents the managed signature.
//
// The first step is to convert the managed signature to a module-independent
// signature and then pass it off to SetStubTargetMethodSig. Note that the
// ILStubResolver will copy the sig, so we only need to make a temporary copy
// of it.
//
SigBuilder sigBuilder;
{
SigPointer sigPtr(pStubMD->GetSig());
sigPtr.ConvertToInternalSignature(pStubMD->GetModule(), NULL, &sigBuilder);
}
//
// The second step is to reset the sig on the stub MethodDesc to be the
// stub-state-calculated stub target sig.
//
{
//
// make a domain-local copy of the sig so that this state can outlive the
// compile time state.
//
DWORD cbNewSig;
PCCOR_SIGNATURE pNewSig;
cbNewSig = GetStubTargetMethodSigLength();
pNewSig = (PCCOR_SIGNATURE)(void *)pStubMD->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(cbNewSig));
memcpyNoGCRefs((void *)pNewSig, GetStubTargetMethodSig(), cbNewSig);
pStubMD->AsDynamicMethodDesc()->SetStoredMethodSig(pNewSig, cbNewSig);
SigPointer sigPtr(pNewSig, cbNewSig);
uint32_t callConvInfo;
IfFailThrow(sigPtr.GetCallingConvInfo(&callConvInfo));
if (callConvInfo & CORINFO_CALLCONV_HASTHIS)
{
((PTR_DynamicMethodDesc)pStubMD)->m_dwExtendedFlags &= ~mdStatic;
pStubMD->ClearStatic();
}
else
{
((PTR_DynamicMethodDesc)pStubMD)->m_dwExtendedFlags |= mdStatic;
pStubMD->SetStatic();
}
#ifndef TARGET_X86
// we store the real managed argument stack size in the stub MethodDesc on non-X86
UINT stackSize = pStubMD->SizeOfNativeArgStack();
if (!FitsInU2(stackSize))
COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX);
pStubMD->AsDynamicMethodDesc()->SetNativeStackArgSize(static_cast<WORD>(stackSize));
#endif // TARGET_X86
}
DWORD cbTempModuleIndependentSigLength;
BYTE * pTempModuleIndependentSig = (BYTE *)sigBuilder.GetSignature(&cbTempModuleIndependentSigLength);
// Finish it
SetStubTargetMethodSig(pTempModuleIndependentSig,
cbTempModuleIndependentSigLength);
}
void EmitInvokeTarget(MethodDesc *pStubMD)
{
STANDARD_VM_CONTRACT;
m_slIL.DoNDirect(m_slIL.GetDispatchCodeStream(), m_dwStubFlags, pStubMD);
}
virtual void EmitExceptionHandler(LocalDesc* pNativeReturnType, LocalDesc* pManagedReturnType,
ILCodeLabel** ppTryBeginLabel, ILCodeLabel** ppTryEndAndCatchBeginLabel, ILCodeLabel** ppCatchEndAndReturnLabel)
{
#ifdef FEATURE_COMINTEROP
STANDARD_VM_CONTRACT;
ILCodeStream* pcsExceptionHandler = m_slIL.NewCodeStream(ILStubLinker::kExceptionHandler);
*ppTryEndAndCatchBeginLabel = pcsExceptionHandler->NewCodeLabel(); // try ends at the same place the catch begins
*ppCatchEndAndReturnLabel = pcsExceptionHandler->NewCodeLabel(); // catch ends at the same place we resume afterwards
pcsExceptionHandler->EmitLEAVE(*ppCatchEndAndReturnLabel);
pcsExceptionHandler->EmitLabel(*ppTryEndAndCatchBeginLabel);
BYTE nativeReturnElemType = pNativeReturnType->ElementType[0]; // return type of the stub
BYTE managedReturnElemType = pManagedReturnType->ElementType[0]; // return type of the mananged target
bool returnTheHRESULT = SF_IsHRESULTSwapping(m_dwStubFlags) ||
(managedReturnElemType == ELEMENT_TYPE_I4) ||
(managedReturnElemType == ELEMENT_TYPE_U4);
DWORD retvalLocalNum = m_slIL.GetReturnValueLocalNum();
BinderMethodID getHRForException;
getHRForException = METHOD__MARSHAL__GET_HR_FOR_EXCEPTION;
pcsExceptionHandler->EmitCALL(getHRForException,
0, // WARNING: This method takes 1 input arg, the exception object. But the ILStubLinker
// has no knowledge that the exception object is on the stack (because it is
// unaware that we've just entered a catch block), so we lie and claim that we
// don't take any input arguments.
1);
switch (nativeReturnElemType)
{
default:
UNREACHABLE_MSG("Unexpected element type found on native return type.");
break;
case ELEMENT_TYPE_VOID:
_ASSERTE(retvalLocalNum == (DWORD)-1);
pcsExceptionHandler->EmitPOP();
break;
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
{
if (!returnTheHRESULT)
{
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC(0);
pcsExceptionHandler->EmitCONV_T((CorElementType)nativeReturnElemType);
}
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
}
break;
case ELEMENT_TYPE_R4:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC_R4(CLR_NAN_32);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
case ELEMENT_TYPE_R8:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC_R8(CLR_NAN_64);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
case ELEMENT_TYPE_INTERNAL:
{
TypeHandle returnTypeHnd = pNativeReturnType->InternalToken;
CONSISTENCY_CHECK(returnTypeHnd.IsValueType());
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitLDLOCA(retvalLocalNum);
pcsExceptionHandler->EmitINITOBJ(m_slIL.GetDispatchCodeStream()->GetToken(returnTypeHnd));
}
break;
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_CHAR:
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
case ELEMENT_TYPE_I:
case ELEMENT_TYPE_U:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC(0);
pcsExceptionHandler->EmitCONV_T((CorElementType)nativeReturnElemType);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
}
pcsExceptionHandler->EmitLEAVE(*ppCatchEndAndReturnLabel);
pcsExceptionHandler->EmitLabel(*ppCatchEndAndReturnLabel);
if (nativeReturnElemType != ELEMENT_TYPE_VOID)
{
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitLDLOC(retvalLocalNum);
}
pcsExceptionHandler->EmitRET();
#endif // FEATURE_COMINTEROP
}
#ifndef DACCESS_COMPILE
void FinishEmit(MethodDesc* pStubMD)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcsMarshal = m_slIL.GetMarshalCodeStream();
ILCodeStream* pcsUnmarshal = m_slIL.GetUnmarshalCodeStream();
ILCodeStream* pcsDispatch = m_slIL.GetDispatchCodeStream();
if (SF_IsHRESULTSwapping(m_dwStubFlags) && m_slIL.StubHasVoidReturnType())
{
// if the return type is void, but we're doing HRESULT swapping, we
// need to set the return type here. Otherwise, the return value
// marshaler will do this.
pcsMarshal->SetStubTargetReturnType(ELEMENT_TYPE_I4); // HRESULT
if (SF_IsReverseStub(m_dwStubFlags))
{
// reverse interop needs to seed the return value if the
// managed function returns void but we're doing hresult
// swapping.
pcsUnmarshal->EmitLDC(S_OK);
}
}
LocalDesc nativeReturnType;
LocalDesc managedReturnType;
bool hasTryCatchForHRESULT = SF_IsReverseCOMStub(m_dwStubFlags)
&& !SF_IsFieldGetterStub(m_dwStubFlags)
&& !SF_IsFieldSetterStub(m_dwStubFlags);
bool hasTryCatchExceptionHandler = hasTryCatchForHRESULT || SF_IsStructMarshalStub(m_dwStubFlags);
#ifdef FEATURE_COMINTEROP
if (hasTryCatchForHRESULT)
{
m_slIL.GetStubTargetReturnType(&nativeReturnType);
m_slIL.GetStubReturnType(&managedReturnType);
}
#endif // FEATURE_COMINTEROP
// Don't touch target signatures from this point on otherwise it messes up the
// cache in ILStubState::GetStubTargetMethodSig.
#ifdef _DEBUG
{
// The native and local signatures should not have any tokens.
// All token references should have been converted to
// ELEMENT_TYPE_INTERNAL.
//
// Note that MetaSig::GetReturnType and NextArg will normalize
// ELEMENT_TYPE_INTERNAL back to CLASS or VALUETYPE.
//
// <TODO> need to recursively check ELEMENT_TYPE_FNPTR signatures </TODO>
SigTypeContext typeContext; // this is an empty type context: COM calls are guaranteed to not be generics.
MetaSig nsig(
GetStubTargetMethodSig(),
GetStubTargetMethodSigLength(),
CoreLibBinder::GetModule(),
&typeContext);
CorElementType type;
IfFailThrow(nsig.GetReturnProps().PeekElemType(&type));
CONSISTENCY_CHECK(ELEMENT_TYPE_CLASS != type && ELEMENT_TYPE_VALUETYPE != type);
while (ELEMENT_TYPE_END != (type = nsig.NextArg()))
{
IfFailThrow(nsig.GetArgProps().PeekElemType(&type));
CONSISTENCY_CHECK(ELEMENT_TYPE_CLASS != type && ELEMENT_TYPE_VALUETYPE != type);
}
}
#endif // _DEBUG
// <NOTE>
// The profiler helpers below must be called immediately before and after the call to the target.
// The debugger trace call helpers are invoked from StubRareDisableWorker
// </NOTE>
#if defined(PROFILING_SUPPORTED)
DWORD dwMethodDescLocalNum = (DWORD)-1;
// Notify the profiler of call out of the runtime
if (!SF_IsReverseCOMStub(m_dwStubFlags) && !SF_IsStructMarshalStub(m_dwStubFlags) && (CORProfilerTrackTransitions() || (!IsReadyToRunCompilation() && SF_IsNGENedStubForProfiling(m_dwStubFlags))))
{
dwMethodDescLocalNum = m_slIL.EmitProfilerBeginTransitionCallback(pcsDispatch, m_dwStubFlags);
_ASSERTE(dwMethodDescLocalNum != (DWORD)-1);
}
#endif // PROFILING_SUPPORTED
// For CoreClr, clear the last error before calling the target that returns last error.
// There isn't always a way to know the function have failed without checking last error,
// in particular on Unix.
if (m_fSetLastError && SF_IsForwardStub(m_dwStubFlags))
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__CLEAR_LAST_ERROR, 0, 0);
}
// Invoke the target (calli, call method, call delegate, get/set field, etc.)
EmitInvokeTarget(pStubMD);
// Saving last error must be the first thing we do after returning from the target
if (m_fSetLastError && SF_IsForwardStub(m_dwStubFlags))
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__SET_LAST_ERROR, 0, 0);
}
#if defined(TARGET_X86)
if (SF_IsForwardDelegateStub(m_dwStubFlags))
{
// the delegate may have an intercept stub attached to its sync block so we should
// prevent it from being garbage collected when the call is in progress
pcsDispatch->EmitLoadThis();
pcsDispatch->EmitCALL(METHOD__GC__KEEP_ALIVE, 1, 0);
}
#endif // defined(TARGET_X86)
#ifdef VERIFY_HEAP
if (SF_IsForwardStub(m_dwStubFlags) && g_pConfig->InteropValidatePinnedObjects())
{
// call StubHelpers.ValidateObject/StubHelpers.ValidateByref on pinned locals
m_slIL.EmitObjectValidation(pcsDispatch, m_dwStubFlags);
}
#endif // VERIFY_HEAP
#if defined(PROFILING_SUPPORTED)
// Notify the profiler of return back into the runtime
if (dwMethodDescLocalNum != (DWORD)-1)
{
m_slIL.EmitProfilerEndTransitionCallback(pcsDispatch, m_dwStubFlags, dwMethodDescLocalNum);
}
#endif // PROFILING_SUPPORTED
#ifdef FEATURE_COMINTEROP
if (SF_IsForwardCOMStub(m_dwStubFlags))
{
// Make sure that the RCW stays alive for the duration of the call. Note that if we do HRESULT
// swapping, we'll pass 'this' to GetCOMHRExceptionObject after returning from the target so
// GC.KeepAlive is not necessary.
if (!SF_IsHRESULTSwapping(m_dwStubFlags))
{
m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags);
pcsDispatch->EmitCALL(METHOD__GC__KEEP_ALIVE, 1, 0);
}
}
#endif // FEATURE_COMINTEROP
if (SF_IsHRESULTSwapping(m_dwStubFlags))
{
if (SF_IsForwardStub(m_dwStubFlags))
{
ILCodeLabel* pSkipThrowLabel = pcsDispatch->NewCodeLabel();
pcsDispatch->EmitDUP();
pcsDispatch->EmitLDC(0); // Compare against S_OK (i.e. 0).
pcsDispatch->EmitBGE(pSkipThrowLabel);
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(m_dwStubFlags))
{
m_slIL.EmitLoadStubContext(pcsDispatch, m_dwStubFlags);
m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags);
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT, 3, 1);
}
else
#endif // FEATURE_COMINTEROP
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_HR_EXCEPTION_OBJECT, 1, 1);
}
pcsDispatch->EmitTHROW();
pcsDispatch->EmitLDC(0); // keep the IL stack balanced across the branch and the fall-through
pcsDispatch->EmitLabel(pSkipThrowLabel);
pcsDispatch->EmitPOP();
}
}
if (SF_IsCheckPendingException(m_dwStubFlags)
&& SF_IsForwardStub(m_dwStubFlags))
{
ILCodeLabel* pSkipThrowLabel = pcsDispatch->NewCodeLabel();
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_PENDING_EXCEPTION_OBJECT, 0, 1);
pcsDispatch->EmitDUP();
pcsDispatch->EmitBRFALSE(pSkipThrowLabel);
pcsDispatch->EmitTHROW();
pcsDispatch->EmitLDC(0); // keep the IL stack balanced across the branch and the fall-through
pcsDispatch->EmitLabel(pSkipThrowLabel);
pcsDispatch->EmitPOP();
}
m_slIL.End(m_dwStubFlags);
if (!hasTryCatchForHRESULT) // we will 'leave' the try scope and then 'ret' from outside
{
pcsUnmarshal->EmitRET();
}
CORJIT_FLAGS jitFlags(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB);
if (m_slIL.HasInteropParamExceptionInfo())
{
// This code will not use the secret parameter, so we do not
// tell the JIT to bother with it.
m_slIL.ClearCode();
m_slIL.GenerateInteropParamException(pcsMarshal);
}
else if (SF_IsFieldGetterStub(m_dwStubFlags) || SF_IsFieldSetterStub(m_dwStubFlags))
{
// Field access stubs are not shared and do not use the secret parameter.
}
else if (SF_IsStructMarshalStub(m_dwStubFlags))
{
// Struct marshal stubs don't actually call anything so they do not need the secrect parameter.
}
#ifndef HOST_64BIT
else if (SF_IsForwardDelegateStub(m_dwStubFlags))
{
// Forward delegate stubs get all the context they need in 'this' so they
// don't use the secret parameter. Except for AMD64 where we use the secret
// argument to pass the real target to the stub-for-host.
}
#endif // !HOST_64BIT
else
{
// All other IL stubs will need to use the secret parameter.
jitFlags.Set(CORJIT_FLAGS::CORJIT_FLAG_PUBLISH_SECRET_PARAM);
}
if (SF_IsReverseStub(m_dwStubFlags))
{
SwapStubSignatures(pStubMD);
}
ILCodeLabel* pTryBeginLabel = nullptr;
ILCodeLabel* pTryEndAndCatchBeginLabel = nullptr;
ILCodeLabel* pCatchEndLabel = nullptr;
if (hasTryCatchExceptionHandler)
{
EmitExceptionHandler(&nativeReturnType, &managedReturnType, &pTryBeginLabel, &pTryEndAndCatchBeginLabel, &pCatchEndLabel);
}
UINT maxStack;
size_t cbCode;
DWORD cbSig;
BYTE * pbBuffer;
BYTE * pbLocalSig;
cbCode = m_slIL.Link(&maxStack);
cbSig = m_slIL.GetLocalSigSize();
ILStubResolver * pResolver = pStubMD->AsDynamicMethodDesc()->GetILStubResolver();
COR_ILMETHOD_DECODER * pILHeader = pResolver->AllocGeneratedIL(cbCode, cbSig, maxStack);
pbBuffer = (BYTE *)pILHeader->Code;
pbLocalSig = (BYTE *)pILHeader->LocalVarSig;
_ASSERTE(cbSig == pILHeader->cbLocalVarSig);
ILStubEHClause cleanupTryFinally{};
m_slIL.GetCleanupFinallyOffsets(&cleanupTryFinally);
ILStubEHClause tryCatchClause{};
if (hasTryCatchExceptionHandler)
{
tryCatchClause.kind = ILStubEHClause::kTypedCatch;
tryCatchClause.dwTryBeginOffset = pTryBeginLabel != nullptr ? (DWORD)pTryBeginLabel->GetCodeOffset() : 0;
tryCatchClause.dwHandlerBeginOffset = ((DWORD)pTryEndAndCatchBeginLabel->GetCodeOffset());
tryCatchClause.cbTryLength = tryCatchClause.dwHandlerBeginOffset - tryCatchClause.dwTryBeginOffset;
tryCatchClause.cbHandlerLength = ((DWORD)pCatchEndLabel->GetCodeOffset()) - tryCatchClause.dwHandlerBeginOffset;
tryCatchClause.dwTypeToken = pcsMarshal->GetToken(g_pObjectClass);
}
int nEHClauses = 0;
if (tryCatchClause.cbHandlerLength != 0)
nEHClauses++;
if (cleanupTryFinally.cbHandlerLength != 0)
nEHClauses++;
if (nEHClauses > 0)
{
COR_ILMETHOD_SECT_EH* pEHSect = pResolver->AllocEHSect(nEHClauses);
PopulateEHSect(pEHSect, nEHClauses, &cleanupTryFinally, &tryCatchClause);
}
m_slIL.GenerateCode(pbBuffer, cbCode);
m_slIL.GetLocalSig(pbLocalSig, cbSig);
pResolver->SetJitFlags(jitFlags);
#ifdef LOGGING
LOG((LF_STUBS, LL_INFO1000, "---------------------------------------------------------------------\n"));
LOG((LF_STUBS, LL_INFO1000, "NDirect IL stub dump: %s::%s\n", pStubMD->m_pszDebugClassName, pStubMD->m_pszDebugMethodName));
if (LoggingEnabled() && LoggingOn(LF_STUBS, LL_INFO1000))
{
CQuickBytes qbManaged;
CQuickBytes qbLocal;
PCCOR_SIGNATURE pManagedSig;
ULONG cManagedSig;
IMDInternalImport* pIMDI = CoreLibBinder::GetModule()->GetMDImport();
pStubMD->GetSig(&pManagedSig, &cManagedSig);
PrettyPrintSig(pManagedSig, cManagedSig, "*", &qbManaged, pStubMD->GetMDImport(), NULL);
PrettyPrintSig(pbLocalSig, cbSig, NULL, &qbLocal, pIMDI, NULL);
LOG((LF_STUBS, LL_INFO1000, "incoming managed sig: %p: %s\n", pManagedSig, qbManaged.Ptr()));
LOG((LF_STUBS, LL_INFO1000, "locals sig: %p: %s\n", pbLocalSig+1, qbLocal.Ptr()));
if (cleanupTryFinally.cbHandlerLength != 0)
{
LOG((LF_STUBS, LL_INFO1000, "try_begin: 0x%04x try_end: 0x%04x finally_begin: 0x%04x finally_end: 0x%04x \n",
cleanupTryFinally.dwTryBeginOffset, cleanupTryFinally.dwTryBeginOffset + cleanupTryFinally.cbTryLength,
cleanupTryFinally.dwHandlerBeginOffset, cleanupTryFinally.dwHandlerBeginOffset + cleanupTryFinally.cbHandlerLength));
}
if (tryCatchClause.cbHandlerLength != 0)
{
LOG((LF_STUBS, LL_INFO1000, "try_begin: 0x%04x try_end: 0x%04x catch_begin: 0x%04x catch_end: 0x%04x type_token: 0x%08x\n",
tryCatchClause.dwTryBeginOffset, tryCatchClause.dwTryBeginOffset + tryCatchClause.cbTryLength,
tryCatchClause.dwHandlerBeginOffset, tryCatchClause.dwHandlerBeginOffset + tryCatchClause.cbHandlerLength,
tryCatchClause.dwTypeToken));
}
LogILStubFlags(LF_STUBS, LL_INFO1000, m_dwStubFlags);
m_slIL.LogILStub(jitFlags);
}
LOG((LF_STUBS, LL_INFO1000, "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"));
#endif // LOGGING
//
// Publish ETW events for IL stubs
//
// If the category and the event is enabled...
if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ILStubGenerated))
{
EtwOnILStubGenerated(
pStubMD,
pbLocalSig,
cbSig,
jitFlags,
&tryCatchClause,
&cleanupTryFinally,
maxStack,
(DWORD)cbCode
);
}
}
//
// Truncates a SString by first converting it to unicode and truncate it
// if it is larger than size. "..." will be appended if it is truncated.
//
void TruncateUnicodeString(SString &string, COUNT_T bufSize)
{
string.Normalize();
if ((string.GetCount() + 1) * sizeof(WCHAR) > bufSize)
{
_ASSERTE(bufSize / sizeof(WCHAR) > 4);
string.Truncate(string.Begin() + bufSize / sizeof(WCHAR) - 4);
string.Append(W("..."));
}
}
//---------------------------------------------------------------------------------------
//
void
EtwOnILStubGenerated(
MethodDesc * pStubMD,
PCCOR_SIGNATURE pbLocalSig,
DWORD cbSig,
CORJIT_FLAGS jitFlags,
ILStubEHClause * pConvertToHRTryCatchBounds,
ILStubEHClause * pCleanupTryFinallyBounds,
DWORD maxStack,
DWORD cbCode)
{
STANDARD_VM_CONTRACT;
//
// Interop Method Information
//
MethodDesc *pTargetMD = m_slIL.GetTargetMD();
SString strNamespaceOrClassName, strMethodName, strMethodSignature;
UINT64 uModuleId = 0;
if (pTargetMD)
{
pTargetMD->GetMethodInfoWithNewSig(strNamespaceOrClassName, strMethodName, strMethodSignature);
uModuleId = (UINT64)pTargetMD->GetModule()->GetAddrModuleID();
}
//
// Stub Method Signature
//
SString stubNamespaceOrClassName, stubMethodName, stubMethodSignature;
pStubMD->GetMethodInfoWithNewSig(stubNamespaceOrClassName, stubMethodName, stubMethodSignature);
IMDInternalImport *pStubImport = pStubMD->GetModule()->GetMDImport();
CQuickBytes qbLocal;
PrettyPrintSig(pbLocalSig, (DWORD)cbSig, NULL, &qbLocal, pStubImport, NULL);
SString strLocalSig(SString::Utf8, (LPCUTF8)qbLocal.Ptr());
//
// Native Signature
//
SString strNativeSignature(SString::Utf8);
if (m_dwStubFlags & NDIRECTSTUB_FL_REVERSE_INTEROP)
{
// Reverse interop. Use StubSignature
strNativeSignature = stubMethodSignature;
}
else
{
// Forward interop. Use StubTarget siganture
PCCOR_SIGNATURE pCallTargetSig = GetStubTargetMethodSig();
DWORD cCallTargetSig = GetStubTargetMethodSigLength();
CQuickBytes qbCallTargetSig;